@tallyui/core 4.2.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,6 +22,7 @@ var server_exports = {};
22
22
  __export(server_exports, {
23
23
  CommandResultError: () => CommandResultError,
24
24
  MAX_COMMANDS_PER_BATCH: () => MAX_COMMANDS_PER_BATCH,
25
+ NEEDS_ADMIN_MESSAGE_MAX: () => NEEDS_ADMIN_MESSAGE_MAX,
25
26
  ORDER_NOTE_MAX: () => ORDER_NOTE_MAX,
26
27
  SUPPORTED_ORDER_CREATE_VERSIONS: () => SUPPORTED_ORDER_CREATE_VERSIONS,
27
28
  SUPPORTED_ORDER_REFUND_VERSIONS: () => SUPPORTED_ORDER_REFUND_VERSIONS,
@@ -41,15 +42,19 @@ __export(server_exports, {
41
42
  majorToMinor: () => majorToMinor,
42
43
  minorToMajor: () => minorToMajor,
43
44
  minorUnitDigits: () => minorUnitDigits,
45
+ needsAdminOutcome: () => needsAdminOutcome,
44
46
  parseCommandResult: () => parseCommandResult,
45
47
  payloadBoundErrors: () => payloadBoundErrors,
46
48
  payloadShapeErrors: () => payloadShapeErrors,
47
49
  platformErrorResult: () => platformErrorResult,
48
50
  precheckCommand: () => precheckCommand,
51
+ priceRefund: () => priceRefund,
49
52
  ratePpmFromPercent: () => ratePpmFromPercent,
50
53
  refundPayloadErrors: () => refundPayloadErrors,
54
+ refundableLines: () => refundableLines,
51
55
  registerPayloadErrors: () => registerPayloadErrors,
52
56
  reopenPayloadErrors: () => reopenPayloadErrors,
57
+ roundRatio: () => roundRatio,
53
58
  totalWarnings: () => totalWarnings,
54
59
  transientOutcome: () => transientOutcome,
55
60
  updatePayloadErrors: () => updatePayloadErrors,
@@ -134,6 +139,7 @@ function commandFingerprint(envelope) {
134
139
  // src/commands.ts
135
140
  var MAX_COMMANDS_PER_BATCH = 50;
136
141
  var ORDER_NOTE_MAX = 1e3;
142
+ var NEEDS_ADMIN_MESSAGE_MAX = 500;
137
143
  var ORDER_TAX_IDS_MAX = 10;
138
144
  var ORDER_TAX_ID_TYPE_MAX = 32;
139
145
  var ORDER_TAX_ID_VALUE_MAX = 64;
@@ -194,6 +200,17 @@ function payloadShapeErrors(payload) {
194
200
  const lineDiscounts = (Array.isArray(payload.lines) ? payload.lines : []).reduce((sum, line, index) => sum + (object(line) ? discount(line.discountMinor, `lines[${index}].discountMinor`) : 0n), 0n);
195
201
  const orderDiscount = discount(payload.discountMinor, "discountMinor");
196
202
  if (errors.length === 0) check2(orderDiscount === lineDiscounts, "discountMinor", "the sum of lines[].discountMinor");
203
+ if (payload.cashRoundings !== void 0) {
204
+ const entries = payload.cashRoundings;
205
+ check2(Array.isArray(entries) && entries.length <= 16, "cashRoundings", "an array of at most 16 entries");
206
+ if (Array.isArray(entries) && entries.length <= 16) for (const [index, entry] of entries.entries()) {
207
+ const path = `cashRoundings[${index}]`;
208
+ check2(object(entry), path, "an object");
209
+ if (!object(entry)) continue;
210
+ check2(typeof entry.paymentId === "string" && entry.paymentId.length > 0, `${path}.paymentId`, "a non-empty string");
211
+ check2(Number.isSafeInteger(entry.minor), `${path}.minor`, "a safe integer");
212
+ }
213
+ }
197
214
  if (payload.customer !== void 0 && payload.customer !== null) {
198
215
  check2(object(payload.customer), "customer", "an object");
199
216
  if (object(payload.customer) && payload.customer.email !== void 0) {
@@ -543,6 +560,17 @@ function fiscalFiguresErrors(payload) {
543
560
  check2(!seen.has(line.clientLineId), `display.lines[${index}].clientLineId`, "no duplicate clientLineId");
544
561
  seen.add(line.clientLineId);
545
562
  });
563
+ if (!errors.length) {
564
+ const sum = (rows) => (rows ?? []).reduce((total, row) => total + BigInt(row.amountMinor), 0n);
565
+ const roundings = (payload.cashRoundings ?? []).reduce((total, entry) => total + BigInt(entry.minor), 0n);
566
+ check2(
567
+ BigInt(display.subtotalMinor) - BigInt(display.discountMinor) + sum(display.fees) + sum(display.shipping) + (display.taxInclusive ? 0n : BigInt(display.taxMinor)) + roundings === BigInt(display.totalMinor),
568
+ "display.totalMinor",
569
+ "subtotalMinor \u2212 discountMinor + fees + shipping (+ taxMinor when exclusive) + cashRoundings"
570
+ );
571
+ check2(sum(display.lines) === BigInt(display.subtotalMinor), "display.subtotalMinor", "the sum of display.lines[].amountMinor");
572
+ check2(BigInt(display.discountMinor) === BigInt(display.orderDiscountMinor) + display.lines.reduce((total, line) => total + sum(line.discounts), 0n) + sum(display.coupons), "display.discountMinor", "orderDiscountMinor + the line discount rows + the coupon rows");
573
+ }
546
574
  try {
547
575
  check2(display.exponent === currencyDecimals(payload.currency), "display.exponent", "the currency decimals");
548
576
  } catch {
@@ -561,7 +589,7 @@ function fiscalFiguresErrors(payload) {
561
589
 
562
590
  // src/server/versions.ts
563
591
  var SUPPORTED_ORDER_CREATE_VERSIONS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
564
- var SUPPORTED_REGISTER_VERSIONS = [1];
592
+ var SUPPORTED_REGISTER_VERSIONS = [1, 2, 3];
565
593
  var SUPPORTED_ORDER_REFUND_VERSIONS = [1];
566
594
  var SUPPORTED_ORDER_REOPEN_VERSIONS = [1];
567
595
  var SUPPORTED_ORDER_UPDATE_VERSIONS = [1];
@@ -581,6 +609,224 @@ function shapeErrors() {
581
609
  return { errors, check: check2, noNul };
582
610
  }
583
611
 
612
+ // src/server/refund-payload-shape.ts
613
+ function refundPayloadErrors(payload) {
614
+ const { errors, check: check2, noNul } = shapeErrors();
615
+ if (!isPlainObject(payload)) return ["payload: expected an object"];
616
+ const fields = [
617
+ "clientRefundId",
618
+ "orderId",
619
+ "registerId",
620
+ "sessionId",
621
+ "clientOrderId",
622
+ "cashierRef",
623
+ "lines",
624
+ "shippingMinor",
625
+ "totalMinor",
626
+ "adjustmentMinor",
627
+ "destination",
628
+ "reason",
629
+ "createdAt"
630
+ ];
631
+ for (const key of Object.keys(payload)) {
632
+ if (!fields.includes(key) && errors.length < 10) {
633
+ errors.push(`${key.includes("\0") ? JSON.stringify(key) : key}: unknown field for order.refund version 1`);
634
+ }
635
+ }
636
+ for (const field of ["clientRefundId", "orderId", "registerId", "sessionId", "clientOrderId", "cashierRef"]) {
637
+ const value = payload[field];
638
+ if (["clientOrderId", "cashierRef"].includes(field) && value === void 0) continue;
639
+ check2(
640
+ typeof value === "string" && value.length > 0 && value.length <= 64,
641
+ field,
642
+ "a non-empty string of at most 64 characters"
643
+ );
644
+ noNul(value, field);
645
+ }
646
+ check2(Array.isArray(payload.lines) && payload.lines.length <= 500, "lines", "an array of at most 500 lines");
647
+ const seen = /* @__PURE__ */ new Set();
648
+ if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
649
+ const path = `lines[${index}]`;
650
+ if (!isPlainObject(line)) {
651
+ check2(false, path, "an object");
652
+ return;
653
+ }
654
+ for (const key of Object.keys(line)) {
655
+ if (!["orderLineId", "quantity", "restock"].includes(key) && errors.length < 10) {
656
+ errors.push(`${path}.${key.includes("\0") ? JSON.stringify(key) : key}: unknown field for order.refund version 1`);
657
+ }
658
+ }
659
+ check2(
660
+ typeof line.orderLineId === "string" && line.orderLineId.length > 0 && line.orderLineId.length <= 64,
661
+ `${path}.orderLineId`,
662
+ "a non-empty string of at most 64 characters"
663
+ );
664
+ noNul(line.orderLineId, `${path}.orderLineId`);
665
+ if (typeof line.orderLineId === "string") {
666
+ check2(!seen.has(line.orderLineId), `${path}.orderLineId`, "unique in lines");
667
+ seen.add(line.orderLineId);
668
+ }
669
+ check2(Number.isSafeInteger(line.quantity) && line.quantity >= 1, `${path}.quantity`, "a safe integer >= 1");
670
+ check2(typeof line.restock === "boolean", `${path}.restock`, "a boolean");
671
+ });
672
+ for (const field of ["shippingMinor", "totalMinor"]) {
673
+ check2(Number.isSafeInteger(payload[field]) && payload[field] >= 0, field, "a safe integer >= 0");
674
+ }
675
+ check2(Number.isSafeInteger(payload.adjustmentMinor), "adjustmentMinor", "a safe integer");
676
+ check2(payload.destination === "original_method" || payload.destination === "cash", "destination", "original_method or cash");
677
+ noNul(payload.destination, "destination");
678
+ check2(
679
+ typeof payload.reason === "string" && payload.reason.trim().length > 0 && payload.reason.length <= 500,
680
+ "reason",
681
+ "a non-empty string after trim of at most 500 characters"
682
+ );
683
+ noNul(payload.reason, "reason");
684
+ check2(
685
+ typeof payload.createdAt === "string" && payload.createdAt.length > 0 && !Number.isNaN(Date.parse(payload.createdAt)),
686
+ "createdAt",
687
+ "a valid date"
688
+ );
689
+ noNul(payload.createdAt, "createdAt");
690
+ return errors;
691
+ }
692
+
693
+ // src/server/register-payload-shape.ts
694
+ function registerPayloadErrors(type, payload) {
695
+ const { errors, check: check2, noNul } = shapeErrors();
696
+ if (!isPlainObject(payload)) return ["payload: expected an object"];
697
+ const string = (field, optional = false) => {
698
+ const value = payload[field];
699
+ if (optional && value === void 0) return;
700
+ check2(typeof value === "string" && (optional || value.length > 0), field, optional ? "a string" : "a non-empty string");
701
+ if (typeof value === "string" && (field.endsWith("Id") || field === "voids")) check2(value.length <= 64, field, "at most 64 characters");
702
+ if (typeof value === "string" && ["openedAt", "at", "createdAt", "closedAt"].includes(field)) {
703
+ check2(!Number.isNaN(Date.parse(value)), field, "a valid date");
704
+ }
705
+ noNul(value, field);
706
+ };
707
+ const integer = (field, min = -Infinity) => check2(Number.isSafeInteger(payload[field]) && payload[field] >= min, field, `a safe integer >= ${min}`);
708
+ const record = (field) => {
709
+ const value = payload[field];
710
+ check2(isPlainObject(value), field, "a record of integers");
711
+ if (isPlainObject(value)) for (const [key, amount] of Object.entries(value)) {
712
+ check2(key.length > 0 && Number.isSafeInteger(amount), `${field}.${key}`, "a non-empty key with a safe integer");
713
+ noNul(key, `${field}.${JSON.stringify(key)}`);
714
+ }
715
+ };
716
+ string("sessionId");
717
+ switch (type) {
718
+ case "register.session.open":
719
+ for (const field of ["registerId", "openedAt"]) string(field);
720
+ for (const field of ["storeKey", "businessDay", "openedBy"]) string(field, true);
721
+ if (payload.deviceName !== void 0) {
722
+ check2(
723
+ typeof payload.deviceName === "string" && payload.deviceName.trim().length >= 1 && payload.deviceName.trim().length <= 64,
724
+ "deviceName",
725
+ "a string of 1 to 64 characters after trim"
726
+ );
727
+ noNul(payload.deviceName, "deviceName");
728
+ }
729
+ if (payload.supersedes !== void 0) {
730
+ check2(
731
+ typeof payload.supersedes === "string" && payload.supersedes.length > 0 && payload.supersedes.length <= 64,
732
+ "supersedes",
733
+ "a non-empty string of at most 64 characters"
734
+ );
735
+ noNul(payload.supersedes, "supersedes");
736
+ }
737
+ integer("countedFloatMinor", 0);
738
+ for (const field of ["expectedFloatMinor", "openingVarianceMinor"]) if (payload[field] !== void 0) integer(field);
739
+ break;
740
+ case "register.session.transition":
741
+ string("at");
742
+ check2(["open", "counting", "closed"].includes(payload.status), "status", "open, counting or closed");
743
+ for (const field of ["counted", "closedBy", "approvedBy"]) if (payload[field] !== void 0) {
744
+ check2(payload.status === "closed", field, "a closing transition");
745
+ if (field === "counted") record(field);
746
+ else string(field, true);
747
+ }
748
+ break;
749
+ case "register.movement.record":
750
+ case "register.movement.void":
751
+ for (const field of ["movementId", "createdAt"]) string(field);
752
+ string("createdBy", true);
753
+ if (type === "register.movement.void") string("voids");
754
+ else {
755
+ check2(
756
+ typeof payload.reason === "string" && payload.reason.trim().length > 0 && payload.reason.length <= 500,
757
+ "reason",
758
+ "a non-empty string after trim of at most 500 characters"
759
+ );
760
+ noNul(payload.reason, "reason");
761
+ check2(["paid_in", "paid_out", "no_sale"].includes(payload.type), "type", "paid_in, paid_out or no_sale");
762
+ integer("amountMinor", payload.type === "no_sale" ? 0 : 1);
763
+ if (payload.type === "no_sale") check2(payload.amountMinor === 0, "amountMinor", "0 for no_sale");
764
+ }
765
+ break;
766
+ case "register.closure.submit":
767
+ for (const field of ["closureId", "registerId", "openedAt", "closedAt", "softwareVersion"]) string(field);
768
+ for (const field of ["businessDay", "closedBy", "approvedBy"]) string(field, true);
769
+ if (payload.approval !== void 0) {
770
+ check2(typeof payload.approval === "string" && payload.approval.length > 0, "approval", "a non-empty string");
771
+ noNul(payload.approval, "approval");
772
+ }
773
+ integer("number", 1);
774
+ for (const field of [
775
+ "periodSalesTotalMinor",
776
+ "periodRefundsTotalMinor",
777
+ "perpetualSalesTotalMinor",
778
+ "perpetualRefundsTotalMinor",
779
+ "unsyncedCount",
780
+ "unsyncedTotalMinor"
781
+ ]) integer(field, 0);
782
+ for (const field of ["number", "unsyncedCount"])
783
+ check2(payload[field] <= 2147483647, field, "at most 2147483647");
784
+ for (const field of ["tillExpected", "counted"]) record(field);
785
+ for (const field of ["orderIds", "movementIds"]) {
786
+ const value = payload[field];
787
+ check2(Array.isArray(value), field, "an array of ids");
788
+ if (Array.isArray(value)) value.forEach((id, index) => {
789
+ check2(typeof id === "string" && id.length > 0 && id.length <= 64, `${field}[${index}]`, "a non-empty string of at most 64 characters");
790
+ noNul(id, `${field}[${index}]`);
791
+ });
792
+ }
793
+ break;
794
+ default:
795
+ check2(false, "type", "a register command type");
796
+ }
797
+ return errors;
798
+ }
799
+
800
+ // src/server/reopen-payload-shape.ts
801
+ function reopenPayloadErrors(payload) {
802
+ const { errors, check: check2, noNul } = shapeErrors();
803
+ if (!isPlainObject(payload)) return ["payload: expected an object"];
804
+ const fields = ["orderId", "clientOrderId", "baseRevision", "cashierRef", "registerId", "storeId", "createdAt"];
805
+ for (const key of Object.keys(payload)) {
806
+ if (!fields.includes(key) && errors.length < 10) {
807
+ errors.push(`${key.includes("\0") ? JSON.stringify(key) : key}: unknown field for order.reopen version 1`);
808
+ }
809
+ }
810
+ for (const field of ["orderId", "cashierRef", "registerId", "clientOrderId", "baseRevision", "storeId"]) {
811
+ const value = payload[field];
812
+ if (["clientOrderId", "baseRevision", "storeId"].includes(field) && value === void 0) continue;
813
+ const max = field === "baseRevision" ? 128 : 64;
814
+ check2(
815
+ typeof value === "string" && value.length > 0 && value.length <= max,
816
+ field,
817
+ `a non-empty string of at most ${max} characters`
818
+ );
819
+ noNul(value, field);
820
+ }
821
+ check2(
822
+ typeof payload.createdAt === "string" && payload.createdAt.length > 0 && !Number.isNaN(Date.parse(payload.createdAt)),
823
+ "createdAt",
824
+ "a valid date"
825
+ );
826
+ noNul(payload.createdAt, "createdAt");
827
+ return errors;
828
+ }
829
+
584
830
  // src/server/update-payload-shape.ts
585
831
  function updateOnlyErrors(payload) {
586
832
  const { errors, check: check2 } = shapeErrors();
@@ -667,6 +913,7 @@ function validateBatch(body) {
667
913
  }
668
914
  var rejected = (id, code, message, data) => ({ id, status: "rejected", error: data === void 0 ? { code, message } : { code, message, data } });
669
915
  var firstTen = (errors) => errors.slice(0, 10).join("; ");
916
+ var shapeRefusal = (id, errors) => errors.length ? rejected(id, "invalid_payload", firstTen(errors)) : void 0;
670
917
  function unsupportedOptional(envelope, key, versions, noun) {
671
918
  if (versions.includes(envelope.version)) return void 0;
672
919
  return rejected(
@@ -680,8 +927,12 @@ function precheckCommand(envelope, supported) {
680
927
  for (const key of ["orderCreate", "register"]) {
681
928
  if (!supported[key]?.length) throw new TypeError(`precheckCommand: supported.${key} must list at least one version`);
682
929
  }
683
- if (envelope.type === "order.refund") return unsupportedOptional(envelope, "orderRefund", supported.orderRefund ?? [], "refunds");
684
- if (envelope.type === "order.reopen") return unsupportedOptional(envelope, "orderReopen", supported.orderReopen ?? [], "reopens");
930
+ if (envelope.type === "order.refund") {
931
+ return unsupportedOptional(envelope, "orderRefund", supported.orderRefund ?? [], "refunds") ?? shapeRefusal(envelope.id, refundPayloadErrors(envelope.payload));
932
+ }
933
+ if (envelope.type === "order.reopen") {
934
+ return unsupportedOptional(envelope, "orderReopen", supported.orderReopen ?? [], "reopens") ?? shapeRefusal(envelope.id, reopenPayloadErrors(envelope.payload));
935
+ }
685
936
  if (envelope.type === "order.update") {
686
937
  const refusal = unsupportedOptional(envelope, "orderUpdate", supported.orderUpdate ?? [], "updates");
687
938
  if (refusal) return refusal;
@@ -701,7 +952,7 @@ function precheckCommand(envelope, supported) {
701
952
  { register: Math.max(...supported.register) }
702
953
  );
703
954
  }
704
- return void 0;
955
+ return shapeRefusal(envelope.id, registerPayloadErrors(envelope.type, envelope.payload));
705
956
  }
706
957
  const command = envelope;
707
958
  if (!supported.orderCreate.includes(command.version)) {
@@ -712,6 +963,9 @@ function precheckCommand(envelope, supported) {
712
963
  { orderCreate: Math.max(...supported.orderCreate) }
713
964
  );
714
965
  }
966
+ if (command.payload.cashRoundings !== void 0 && supported.cashRounding !== true) {
967
+ return rejected(command.id, "invalid_payload", "cashRoundings requires the cashRounding capability, which this server does not declare");
968
+ }
715
969
  const { lines, discountMinor } = command.payload;
716
970
  const discounted = discountMinor !== void 0 || Array.isArray(lines) && lines.some((line) => line?.discountMinor !== void 0);
717
971
  const payload = command.payload;
@@ -755,7 +1009,7 @@ function precheckCommand(envelope, supported) {
755
1009
  return rejected(command.id, "invalid_payload", firstTen(bounds));
756
1010
  }
757
1011
  const shape = payloadShapeErrors(payload);
758
- const errors = command.version >= 5 && shape.length ? shape : v3 && display !== void 0 && taxByRate !== void 0 && shape.length === 0 ? fiscalFiguresErrors(payload) : [];
1012
+ const errors = shape.length ? shape : v3 && display !== void 0 && taxByRate !== void 0 ? fiscalFiguresErrors(payload) : [];
759
1013
  if (errors.length) {
760
1014
  return rejected(command.id, "invalid_payload", firstTen(errors));
761
1015
  }
@@ -766,6 +1020,9 @@ function precheckCommand(envelope, supported) {
766
1020
  function inProgressOutcome(id) {
767
1021
  return { status: 409, body: { code: "in_progress", id } };
768
1022
  }
1023
+ function needsAdminOutcome(id, reason, message) {
1024
+ return { status: 409, body: { code: "needs_admin", id, reason, message: message.slice(0, NEEDS_ADMIN_MESSAGE_MAX) } };
1025
+ }
769
1026
  function transientOutcome(id) {
770
1027
  return { status: 503, body: { code: "transient", id, message: "Temporary failure, retry later." } };
771
1028
  }
@@ -827,7 +1084,8 @@ function parseCommandResult(value) {
827
1084
  return [key, amount];
828
1085
  }));
829
1086
  if (Object.values(byMethod).reduce((sum, amount) => sum + amount, 0) !== refund.totalMinor) throw new CommandResultError("Invalid refund.byMethod");
830
- if (!Array.isArray(refund.refunds) || refund.refunds.length === 0) throw new CommandResultError("Invalid refund.refunds");
1087
+ if (!Array.isArray(refund.refunds)) throw new CommandResultError("Invalid refund.refunds");
1088
+ if (refund.refunds.length === 0 && (refund.totalMinor !== 0 || Object.keys(byMethod).length > 0)) throw new CommandResultError("Invalid refund.refunds");
831
1089
  const refunds = refund.refunds.map((value2, index) => {
832
1090
  const field = `refund.refunds[${index}]`;
833
1091
  if (!object(value2)) throw new CommandResultError(`Invalid ${field}`);
@@ -967,224 +1225,6 @@ function parseCommandResult(value) {
967
1225
  return result;
968
1226
  }
969
1227
 
970
- // src/server/register-payload-shape.ts
971
- function registerPayloadErrors(type, payload) {
972
- const { errors, check: check2, noNul } = shapeErrors();
973
- if (!isPlainObject(payload)) return ["payload: expected an object"];
974
- const string = (field, optional = false) => {
975
- const value = payload[field];
976
- if (optional && value === void 0) return;
977
- check2(typeof value === "string" && (optional || value.length > 0), field, optional ? "a string" : "a non-empty string");
978
- if (typeof value === "string" && (field.endsWith("Id") || field === "voids")) check2(value.length <= 64, field, "at most 64 characters");
979
- if (typeof value === "string" && ["openedAt", "at", "createdAt", "closedAt"].includes(field)) {
980
- check2(!Number.isNaN(Date.parse(value)), field, "a valid date");
981
- }
982
- noNul(value, field);
983
- };
984
- const integer = (field, min = -Infinity) => check2(Number.isSafeInteger(payload[field]) && payload[field] >= min, field, `a safe integer >= ${min}`);
985
- const record = (field) => {
986
- const value = payload[field];
987
- check2(isPlainObject(value), field, "a record of integers");
988
- if (isPlainObject(value)) for (const [key, amount] of Object.entries(value)) {
989
- check2(key.length > 0 && Number.isSafeInteger(amount), `${field}.${key}`, "a non-empty key with a safe integer");
990
- noNul(key, `${field}.${JSON.stringify(key)}`);
991
- }
992
- };
993
- string("sessionId");
994
- switch (type) {
995
- case "register.session.open":
996
- for (const field of ["registerId", "openedAt"]) string(field);
997
- for (const field of ["storeKey", "businessDay", "openedBy"]) string(field, true);
998
- if (payload.deviceName !== void 0) {
999
- check2(
1000
- typeof payload.deviceName === "string" && payload.deviceName.trim().length >= 1 && payload.deviceName.trim().length <= 64,
1001
- "deviceName",
1002
- "a string of 1 to 64 characters after trim"
1003
- );
1004
- noNul(payload.deviceName, "deviceName");
1005
- }
1006
- if (payload.supersedes !== void 0) {
1007
- check2(
1008
- typeof payload.supersedes === "string" && payload.supersedes.length > 0 && payload.supersedes.length <= 64,
1009
- "supersedes",
1010
- "a non-empty string of at most 64 characters"
1011
- );
1012
- noNul(payload.supersedes, "supersedes");
1013
- }
1014
- integer("countedFloatMinor", 0);
1015
- for (const field of ["expectedFloatMinor", "openingVarianceMinor"]) if (payload[field] !== void 0) integer(field);
1016
- break;
1017
- case "register.session.transition":
1018
- string("at");
1019
- check2(["open", "counting", "closed"].includes(payload.status), "status", "open, counting or closed");
1020
- for (const field of ["counted", "closedBy", "approvedBy"]) if (payload[field] !== void 0) {
1021
- check2(payload.status === "closed", field, "a closing transition");
1022
- if (field === "counted") record(field);
1023
- else string(field, true);
1024
- }
1025
- break;
1026
- case "register.movement.record":
1027
- case "register.movement.void":
1028
- for (const field of ["movementId", "createdAt"]) string(field);
1029
- string("createdBy", true);
1030
- if (type === "register.movement.void") string("voids");
1031
- else {
1032
- check2(
1033
- typeof payload.reason === "string" && payload.reason.trim().length > 0 && payload.reason.length <= 500,
1034
- "reason",
1035
- "a non-empty string after trim of at most 500 characters"
1036
- );
1037
- noNul(payload.reason, "reason");
1038
- check2(["paid_in", "paid_out", "no_sale"].includes(payload.type), "type", "paid_in, paid_out or no_sale");
1039
- integer("amountMinor", payload.type === "no_sale" ? 0 : 1);
1040
- if (payload.type === "no_sale") check2(payload.amountMinor === 0, "amountMinor", "0 for no_sale");
1041
- }
1042
- break;
1043
- case "register.closure.submit":
1044
- for (const field of ["closureId", "registerId", "openedAt", "closedAt", "softwareVersion"]) string(field);
1045
- for (const field of ["businessDay", "closedBy", "approvedBy"]) string(field, true);
1046
- if (payload.approval !== void 0) {
1047
- check2(typeof payload.approval === "string" && payload.approval.length > 0, "approval", "a non-empty string");
1048
- noNul(payload.approval, "approval");
1049
- }
1050
- integer("number", 1);
1051
- for (const field of [
1052
- "periodSalesTotalMinor",
1053
- "periodRefundsTotalMinor",
1054
- "perpetualSalesTotalMinor",
1055
- "perpetualRefundsTotalMinor",
1056
- "unsyncedCount",
1057
- "unsyncedTotalMinor"
1058
- ]) integer(field, 0);
1059
- for (const field of ["number", "unsyncedCount"])
1060
- check2(payload[field] <= 2147483647, field, "at most 2147483647");
1061
- for (const field of ["tillExpected", "counted"]) record(field);
1062
- for (const field of ["orderIds", "movementIds"]) {
1063
- const value = payload[field];
1064
- check2(Array.isArray(value), field, "an array of ids");
1065
- if (Array.isArray(value)) value.forEach((id, index) => {
1066
- check2(typeof id === "string" && id.length > 0 && id.length <= 64, `${field}[${index}]`, "a non-empty string of at most 64 characters");
1067
- noNul(id, `${field}[${index}]`);
1068
- });
1069
- }
1070
- break;
1071
- default:
1072
- check2(false, "type", "a register command type");
1073
- }
1074
- return errors;
1075
- }
1076
-
1077
- // src/server/refund-payload-shape.ts
1078
- function refundPayloadErrors(payload) {
1079
- const { errors, check: check2, noNul } = shapeErrors();
1080
- if (!isPlainObject(payload)) return ["payload: expected an object"];
1081
- const fields = [
1082
- "clientRefundId",
1083
- "orderId",
1084
- "registerId",
1085
- "sessionId",
1086
- "clientOrderId",
1087
- "cashierRef",
1088
- "lines",
1089
- "shippingMinor",
1090
- "totalMinor",
1091
- "adjustmentMinor",
1092
- "destination",
1093
- "reason",
1094
- "createdAt"
1095
- ];
1096
- for (const key of Object.keys(payload)) {
1097
- if (!fields.includes(key) && errors.length < 10) {
1098
- errors.push(`${key.includes("\0") ? JSON.stringify(key) : key}: unknown field for order.refund version 1`);
1099
- }
1100
- }
1101
- for (const field of ["clientRefundId", "orderId", "registerId", "sessionId", "clientOrderId", "cashierRef"]) {
1102
- const value = payload[field];
1103
- if (["clientOrderId", "cashierRef"].includes(field) && value === void 0) continue;
1104
- check2(
1105
- typeof value === "string" && value.length > 0 && value.length <= 64,
1106
- field,
1107
- "a non-empty string of at most 64 characters"
1108
- );
1109
- noNul(value, field);
1110
- }
1111
- check2(Array.isArray(payload.lines) && payload.lines.length <= 500, "lines", "an array of at most 500 lines");
1112
- const seen = /* @__PURE__ */ new Set();
1113
- if (Array.isArray(payload.lines)) payload.lines.forEach((line, index) => {
1114
- const path = `lines[${index}]`;
1115
- if (!isPlainObject(line)) {
1116
- check2(false, path, "an object");
1117
- return;
1118
- }
1119
- for (const key of Object.keys(line)) {
1120
- if (!["orderLineId", "quantity", "restock"].includes(key) && errors.length < 10) {
1121
- errors.push(`${path}.${key.includes("\0") ? JSON.stringify(key) : key}: unknown field for order.refund version 1`);
1122
- }
1123
- }
1124
- check2(
1125
- typeof line.orderLineId === "string" && line.orderLineId.length > 0 && line.orderLineId.length <= 64,
1126
- `${path}.orderLineId`,
1127
- "a non-empty string of at most 64 characters"
1128
- );
1129
- noNul(line.orderLineId, `${path}.orderLineId`);
1130
- if (typeof line.orderLineId === "string") {
1131
- check2(!seen.has(line.orderLineId), `${path}.orderLineId`, "unique in lines");
1132
- seen.add(line.orderLineId);
1133
- }
1134
- check2(Number.isSafeInteger(line.quantity) && line.quantity >= 1, `${path}.quantity`, "a safe integer >= 1");
1135
- check2(typeof line.restock === "boolean", `${path}.restock`, "a boolean");
1136
- });
1137
- for (const field of ["shippingMinor", "totalMinor"]) {
1138
- check2(Number.isSafeInteger(payload[field]) && payload[field] >= 0, field, "a safe integer >= 0");
1139
- }
1140
- check2(Number.isSafeInteger(payload.adjustmentMinor), "adjustmentMinor", "a safe integer");
1141
- check2(payload.destination === "original_method" || payload.destination === "cash", "destination", "original_method or cash");
1142
- noNul(payload.destination, "destination");
1143
- check2(
1144
- typeof payload.reason === "string" && payload.reason.trim().length > 0 && payload.reason.length <= 500,
1145
- "reason",
1146
- "a non-empty string after trim of at most 500 characters"
1147
- );
1148
- noNul(payload.reason, "reason");
1149
- check2(
1150
- typeof payload.createdAt === "string" && payload.createdAt.length > 0 && !Number.isNaN(Date.parse(payload.createdAt)),
1151
- "createdAt",
1152
- "a valid date"
1153
- );
1154
- noNul(payload.createdAt, "createdAt");
1155
- return errors;
1156
- }
1157
-
1158
- // src/server/reopen-payload-shape.ts
1159
- function reopenPayloadErrors(payload) {
1160
- const { errors, check: check2, noNul } = shapeErrors();
1161
- if (!isPlainObject(payload)) return ["payload: expected an object"];
1162
- const fields = ["orderId", "clientOrderId", "baseRevision", "cashierRef", "registerId", "storeId", "createdAt"];
1163
- for (const key of Object.keys(payload)) {
1164
- if (!fields.includes(key) && errors.length < 10) {
1165
- errors.push(`${key.includes("\0") ? JSON.stringify(key) : key}: unknown field for order.reopen version 1`);
1166
- }
1167
- }
1168
- for (const field of ["orderId", "cashierRef", "registerId", "clientOrderId", "baseRevision", "storeId"]) {
1169
- const value = payload[field];
1170
- if (["clientOrderId", "baseRevision", "storeId"].includes(field) && value === void 0) continue;
1171
- const max = field === "baseRevision" ? 128 : 64;
1172
- check2(
1173
- typeof value === "string" && value.length > 0 && value.length <= max,
1174
- field,
1175
- `a non-empty string of at most ${max} characters`
1176
- );
1177
- noNul(value, field);
1178
- }
1179
- check2(
1180
- typeof payload.createdAt === "string" && payload.createdAt.length > 0 && !Number.isNaN(Date.parse(payload.createdAt)),
1181
- "createdAt",
1182
- "a valid date"
1183
- );
1184
- noNul(payload.createdAt, "createdAt");
1185
- return errors;
1186
- }
1187
-
1188
1228
  // src/server/register-figures.ts
1189
1229
  function deriveSessionFigures(input) {
1190
1230
  const expected = Object.assign(/* @__PURE__ */ Object.create(null), { cash: input.countedFloatMinor });
@@ -1884,10 +1924,65 @@ function displaySignallingContract(makeHarness) {
1884
1924
  };
1885
1925
  return Object.entries(cases).map(([name, run]) => ({ name, run: async () => run(await world(makeHarness)) }));
1886
1926
  }
1927
+
1928
+ // src/server/round-ratio.ts
1929
+ function roundRatio(n, d, mode = "half_away_from_zero") {
1930
+ if (mode === "half_away_from_zero" && n < 0n) return -roundRatio(-n, d, mode);
1931
+ const a = 2n * n + d, b = 2n * d;
1932
+ return a / b - (a < 0n && a % b !== 0n ? 1n : 0n);
1933
+ }
1934
+
1935
+ // src/server/refund-share.ts
1936
+ function refundableLines(lines, refunds) {
1937
+ const earlier = refunds.flatMap((refund) => refund.lines);
1938
+ for (const refund of earlier) {
1939
+ if (!Number.isSafeInteger(refund.quantity)) throw new RangeError("Earlier refund quantity must be a safe integer");
1940
+ }
1941
+ return lines.map((line) => {
1942
+ if (!Number.isSafeInteger(line.quantity) || line.quantity < 0 || !Number.isSafeInteger(line.totalMinor) || !Number.isSafeInteger(line.taxMinor)) {
1943
+ throw new RangeError("Order line values must be safe integers and quantity non-negative");
1944
+ }
1945
+ const refundedQuantity = earlier.reduce((sum, refund) => refund.orderLineId === line.id ? Math.min(line.quantity, sum + Math.abs(refund.quantity)) : sum, 0);
1946
+ const [netMinor, taxMinor] = [line.totalMinor, line.taxMinor].map((total) => line.quantity === 0 ? 0 : total - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), "half_up")));
1947
+ return {
1948
+ orderLineId: line.id,
1949
+ refundedQuantity,
1950
+ refundableQuantity: line.quantity - refundedQuantity,
1951
+ netMinor,
1952
+ taxMinor
1953
+ };
1954
+ });
1955
+ }
1956
+ function priceRefund(lines, refunds, request) {
1957
+ const available = refundableLines(lines, refunds);
1958
+ const seen = /* @__PURE__ */ new Set();
1959
+ const result = { lines: [], priced: [], clamped: [], netMinor: 0, taxMinor: 0, totalMinor: 0 };
1960
+ for (const { orderLineId, quantity: requestedQuantity, restock } of request) {
1961
+ if (!Number.isSafeInteger(requestedQuantity) || requestedQuantity < 0 || seen.has(orderLineId)) {
1962
+ throw new RangeError("Request quantities must be non-negative safe integers and line ids unique");
1963
+ }
1964
+ seen.add(orderLineId);
1965
+ const index = lines.findIndex((line2) => line2.id === orderLineId);
1966
+ const quantity = Math.min(requestedQuantity, available[index]?.refundableQuantity ?? 0);
1967
+ if (quantity < requestedQuantity) result.clamped.push({ orderLineId, requestedQuantity, quantity });
1968
+ if (quantity < 1) continue;
1969
+ const line = lines[index];
1970
+ const refundedQuantity = available[index].refundedQuantity;
1971
+ const [netMinor, taxMinor] = [line.totalMinor, line.taxMinor].map((total) => Number(roundRatio(BigInt(refundedQuantity + quantity) * BigInt(total), BigInt(line.quantity), "half_up")) - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), "half_up")));
1972
+ const totalMinor = netMinor + taxMinor;
1973
+ result.lines.push({ orderLineId, quantity, restock });
1974
+ result.priced.push({ orderLineId, quantity, netMinor, taxMinor, totalMinor });
1975
+ result.netMinor += netMinor;
1976
+ result.taxMinor += taxMinor;
1977
+ result.totalMinor += totalMinor;
1978
+ }
1979
+ return result;
1980
+ }
1887
1981
  // Annotate the CommonJS export names for ESM import in node:
1888
1982
  0 && (module.exports = {
1889
1983
  CommandResultError,
1890
1984
  MAX_COMMANDS_PER_BATCH,
1985
+ NEEDS_ADMIN_MESSAGE_MAX,
1891
1986
  ORDER_NOTE_MAX,
1892
1987
  SUPPORTED_ORDER_CREATE_VERSIONS,
1893
1988
  SUPPORTED_ORDER_REFUND_VERSIONS,
@@ -1907,15 +2002,19 @@ function displaySignallingContract(makeHarness) {
1907
2002
  majorToMinor,
1908
2003
  minorToMajor,
1909
2004
  minorUnitDigits,
2005
+ needsAdminOutcome,
1910
2006
  parseCommandResult,
1911
2007
  payloadBoundErrors,
1912
2008
  payloadShapeErrors,
1913
2009
  platformErrorResult,
1914
2010
  precheckCommand,
2011
+ priceRefund,
1915
2012
  ratePpmFromPercent,
1916
2013
  refundPayloadErrors,
2014
+ refundableLines,
1917
2015
  registerPayloadErrors,
1918
2016
  reopenPayloadErrors,
2017
+ roundRatio,
1919
2018
  totalWarnings,
1920
2019
  transientOutcome,
1921
2020
  updatePayloadErrors,