All files / src/pricing matrix.ts

0% Statements 0/114
0% Branches 0/54
0% Functions 0/22
0% Lines 0/83

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import {
  BuildPriceMatrixOptions,
  DiscountGroup,
  GroupSelection,
  PriceMatrix,
  PriceMatrixBand,
  PriceMatrixCell,
  PricingField,
  PricingRules,
  QuoteResult,
  Selections,
} from './types.js';
import { estimateQuote } from './estimate.js';
 
function toQuantity(value: unknown): number {
  const n = Number(value);
  return Number.isFinite(n) ? n : 0;
}
 
function floorMinQuantity(value: unknown): number {
  const n = toQuantity(value);
  return n >= 1 ? Math.round(n) : 1;
}
 
function addDiscountLimits(
  group: DiscountGroup | null | undefined,
  limits: Set<number>,
  minQuantity: number
): void {
  Iif (!group || !group.discounts) return;
  for (const discount of group.discounts) {
    const n = Number(discount.lowerLimit);
    Iif (!Number.isFinite(n)) continue;
    const qty = Math.round(n);
    Iif (qty > minQuantity) limits.add(qty);
  }
}
 
function collectFieldDiscountLimits(
  field: PricingField,
  limits: Set<number>,
  minQuantity: number
): void {
  addDiscountLimits(field.variationCostDiscountGroup, limits, minQuantity);
  addDiscountLimits(field.variationUnitCostDiscountGroup, limits, minQuantity);
  addDiscountLimits(field.heightVariationCostDiscountGroup, limits, minQuantity);
  addDiscountLimits(field.heightVariationUnitCostDiscountGroup, limits, minQuantity);
  addDiscountLimits(field.widthVariationCostDiscountGroup, limits, minQuantity);
  addDiscountLimits(field.widthVariationUnitCostDiscountGroup, limits, minQuantity);
  for (const option of field.options) {
    addDiscountLimits(option.variationCostDiscountGroup, limits, minQuantity);
    addDiscountLimits(option.variationUnitCostDiscountGroup, limits, minQuantity);
  }
}
 
function collectQuantityBreaks(
  rules: PricingRules,
  minQuantity: number
): number[] {
  const limits = new Set<number>([minQuantity]);
  addDiscountLimits(rules.product.discountGroup, limits, minQuantity);
  for (const item of rules.fields) {
    collectFieldDiscountLimits(item, limits, minQuantity);
  }
  for (const item of rules.groupFields) {
    collectFieldDiscountLimits(item, limits, minQuantity);
  }
  return Array.from(limits).sort((a, b) => a - b);
}
 
function groupHasValues(group: GroupSelection): boolean {
  const values = group.fieldValues || {};
  return Object.keys(values).some((key) => {
    const selection = values[Number(key)];
    Iif (!selection) return false;
    Iif (selection.selectedOptionIds && selection.selectedOptionIds.length) {
      return true;
    }
    const value = selection.value;
    return !(
      value === undefined ||
      value === null ||
      value === '' ||
      value === 0
    );
  });
}
 
function representativeGroupIndex(groups: GroupSelection[]): number {
  const idx = groups.findIndex(groupHasValues);
  return idx >= 0 ? idx : 0;
}
 
function selectionsAtQuantity(
  selections: Selections,
  qty: number
): Selections {
  const groups = selections.groups;
  Iif (groups && groups.length > 0) {
    const quantities = groups.map((group) => toQuantity(group.quantity));
    const total = quantities.reduce((sum, value) => sum + value, 0);
    Iif (total <= 0) {
      const idx = representativeGroupIndex(groups);
      return {
        fieldValues: selections.fieldValues || {},
        groups: groups.map((group, i) => ({
          ...group,
          quantity: i === idx ? qty : 0,
        })),
      };
    }
    const scaled: number[] = new Array(groups.length).fill(0);
    let allocated = 0;
    for (let i = 0; i < groups.length - 1; i++) {
      scaled[i] = Math.round((quantities[i] / total) * qty);
      allocated += scaled[i];
    }
    scaled[groups.length - 1] = Math.max(0, qty - allocated);
    return {
      fieldValues: selections.fieldValues || {},
      groups: groups.map((group, i) => ({
        ...group,
        quantity: scaled[i],
      })),
    };
  }
  return {
    fieldValues: selections.fieldValues || {},
    quantity: qty,
  };
}
 
function formatBandLabel(quantity: number, upperLimit: number | null): string {
  Iif (upperLimit == null) return `${quantity}+`;
  Iif (upperLimit === quantity) return `${quantity}`;
  return `${quantity}–${upperLimit}`;
}
 
function samePrice(a: PriceMatrixCell, b: PriceMatrixCell): boolean {
  return (
    Math.abs(a.costPerUnit - b.costPerUnit) < 0.001 &&
    Math.abs(a.unitPrice - b.unitPrice) < 0.001
  );
}
 
function withBandBounds(quantities: number[]): PriceMatrixBand[] {
  return quantities.map((quantity, i) => {
    const next = quantities[i + 1];
    const upperLimit = next == null ? null : next - 1;
    return {
      quantity,
      upperLimit,
      label: formatBandLabel(quantity, upperLimit),
    };
  });
}
 
/**
 * Quantity-break price table for the current selection.
 *
 * Columns are unique quantity thresholds from every discount group on the
 * product, fields, and options. Each cell is `estimateQuote` at that quantity
 * so the table matches what the form will charge. Returns null when there are
 * fewer than two distinct prices (nothing useful to show).
 */
export function buildPriceMatrix(
  rules: PricingRules,
  Iselections: Selections = { fieldValues: {} },
  Ioptions: BuildPriceMatrixOptions = {}
): PriceMatrix | null {
  Iif (rules.unsupported) return null;
 
  const safeRules: PricingRules = {
    ...rules,
    fields: (rules.fields || []).map((item) => ({
      ...item,
      options: item.options || [],
    })),
    groupFields: (rules.groupFields || []).map((item) => ({
      ...item,
      options: item.options || [],
    })),
  };
  const minQuantity = floorMinQuantity(options.minQuantity);
  const quantities = collectQuantityBreaks(safeRules, minQuantity);
  const quoted: PriceMatrixCell[] = [];
 
  for (const quantity of quantities) {
    const quote = estimateQuote(
      safeRules,
      selectionsAtQuantity(selections, quantity)
    ) as QuoteResult;
    quoted.push({
      quantity,
      costPerUnit: quote.costPerUnit,
      unitPrice: quote.cost / quantity,
      cost: quote.cost,
      taxAmount: quote.taxAmount,
      totalCost: quote.totalCost,
    });
  }
 
  const cells: PriceMatrixCell[] = [];
  for (const cell of quoted) {
    const prev = cells[cells.length - 1];
    Iif (prev && samePrice(prev, cell)) continue;
    cells.push(cell);
  }
  Iif (cells.length < 2) return null;
 
  return {
    currency: rules.currency,
    taxPercent: rules.taxPercent,
    bands: withBandBounds(cells.map((cell) => cell.quantity)),
    cells,
  };
}