expectedSalesTax function

double? expectedSalesTax(
  1. Object? item
)

The sales tax FBR expects on a line, in rupees, or null when the rate is not a plain percentage or per-unit amount (spec §7, errors 0102, 0104, 0105):

  • N% on Third Schedule goods: retail price × rate (0102);
  • N% otherwise: value excluding sales tax × rate (0104);
  • Rs.N: quantity × N (0105).

item is an FbrInvoiceItem (only rate, saleType, quantity, valueSalesExcludingST and fixedNotifiedValueOrRetailPrice are read). Rounded half up to the paisa (the specification allows 2 decimals and gives no rounding rule). Never throws.

expectedSalesTax({'rate': 'Rs.3', 'quantity': 12}); // 36
expectedSalesTax({'rate': '18%', 'valueSalesExcludingST': 1234}); // 222.12

Implementation

double? expectedSalesTax(Object? item) {
  if (item is! Map) return null;
  final rateText = item['rate'];
  if (rateText is! String) return null;
  final rate = jsTrim(rateText);
  final percent = _percentRate.firstMatch(rate);
  if (percent != null) {
    final base = _saleTypeKey(item['saleType']) == '3rd schedule goods'
        ? item['fixedNotifiedValueOrRetailPrice']
        : item['valueSalesExcludingST'];
    if (base is! num) return null;
    return calculateSalesTax(base, rate: double.parse(percent.group(1)!))?.tax;
  }
  final perUnit = _perUnitRate.firstMatch(rate);
  if (perUnit != null) {
    final quantityValue = item['quantity'];
    if (quantityValue is! num) return null;
    final quantity = toUnits(quantityValue, 4);
    final price = toUnits(double.parse(perUnit.group(1)!), 2);
    if (quantity == null || price == null) return null;
    // As `divideHalfUp`, but kept as a BigInt until the end: the product can
    // pass 2^63, and JavaScript then rounds it to the nearest double.
    final numerator = BigInt.from(quantity) * BigInt.from(price);
    final denominator = BigInt.from(10000);
    final quotient = numerator ~/ denominator;
    final paisa = numerator.remainder(denominator) * BigInt.two >= denominator
        ? quotient + BigInt.one
        : quotient;
    return paisa.toDouble() / 100;
  }
  return null;
}