@peabody-soft/mbs-model-ts 1.6.0 → 1.7.1

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.
@@ -2,10 +2,10 @@
2
2
  // A caller is expected to catch them and decide what to do: sign in again, retry, or show the shop
3
3
  // it has cached. They mirror Java com.merabills.repository.client.exception, so both clients of
4
4
  // this server describe a failure the same way.
5
- // Each carries the status code. The derived classes let a caller catch the one case it can handle
6
- // without testing a number.
7
- // A call reached the server and the server refused it. Thrown directly for a status code none of the
8
- // classes below names, so an unrecognised failure is still a ServiceException.
5
+ // Each ServiceException carries the status code. The derived classes let a caller catch the one
6
+ // case it can handle without testing a number.
7
+ // A call reached the server and the server refused it. Thrown directly for a status code that no
8
+ // class below covers, so an unrecognised failure is still a ServiceException.
9
9
  export class ServiceException extends Error {
10
10
  constructor(httpStatusCode, message) {
11
11
  super(message);
@@ -21,7 +21,7 @@ export class BadRequestException extends ServiceException {
21
21
  }
22
22
  }
23
23
  BadRequestException.STATUS_CODE = 400;
24
- // HTTP 401 - the credentials were missing, expired or not the caller's to present
24
+ // HTTP 401 - the credentials were missing, expired or did not belong to the caller
25
25
  export class UnauthorizedException extends ServiceException {
26
26
  constructor(message) {
27
27
  super(UnauthorizedException.STATUS_CODE, message);
@@ -80,4 +80,4 @@ export class NetworkConnectionException extends Error {
80
80
  this.name = new.target.name;
81
81
  }
82
82
  }
83
- // The status code each of these stands for is mapped in HttpStatusCodes.ts.
83
+ // HttpStatusCodes.ts maps each status code to its class.
@@ -13,12 +13,12 @@ import Routes from "./Routes";
13
13
  import { NetworkConnectionException } from "./ServiceExceptions";
14
14
  // A Service that reaches a real MeraBills server. Every call is one POST to the route named after
15
15
  // it, with the encoded request message as the body and the encoded response message as the answer.
16
- // This class translates nothing and reads no field of either.
17
- // One call is one page: the loop over a paged sync out belongs to whoever caches what comes back,
18
- // so each page is written as it arrives (see Model.businessSyncIn).
16
+ // This class only encodes and decodes the messages, and reads none of their fields.
17
+ // One call is one page. The caller that caches the pages runs the loop over a paged sync out, so
18
+ // that each page is written as it arrives (see Model.businessSyncIn).
19
19
  export default class ServiceProxy {
20
- // The base url is everything before the route, with or without a trailing slash or a path of its
21
- // own. The route is joined onto it, so a server reached under a prefix works.
20
+ // The base url is everything before the route. It may end in a slash and may include a path. The
21
+ // route is appended to it, so a server reached under a prefix works.
22
22
  constructor(serviceBaseUrl, fetchFunction = null) {
23
23
  this._serviceBaseUrl = serviceBaseUrl.replace(TRAILING_SLASHES, "");
24
24
  this._fetchFunction = fetchFunction;
@@ -35,23 +35,23 @@ export default class ServiceProxy {
35
35
  async createUser(request, authTokens) {
36
36
  return this.post(Routes.CREATE_USER, proto_CreateUserRequest, request, proto_ProfileSyncOutResponse, authTokens);
37
37
  }
38
- // The User is the whole request, there being no wrapper message for one
38
+ // The User is the whole request, since there is no wrapper message for it
39
39
  async updateUser(user, authTokens) {
40
40
  return this.post(Routes.UPDATE_USER, proto_User, user, proto_ProfileSyncOutResponse, authTokens);
41
41
  }
42
- // One call: encode, send, turn a refusal into its exception, decode. The message types are
43
- // passed in so every route is sent and read the same way.
42
+ // One call: encode, send, throw the matching exception on an error status, decode. The message
43
+ // types are passed in so every route is sent and read the same way.
44
44
  async post(route, requestType, request, responseType, authTokens) {
45
45
  const response = await this.send(route, requestType.toBinary(request), authTokens);
46
- // The body of a failure is not a response message, so it has to be dealt with before decoding
46
+ // The body of a failure is not a response message, so the status is checked before decoding
47
47
  if (isError(response.status))
48
48
  throwOnError(response.status, await ServiceProxy.readErrorMessage(route, response));
49
49
  return responseType.fromBinary(new Uint8Array(await response.arrayBuffer()));
50
50
  }
51
51
  async send(route, body, authTokens) {
52
52
  const headers = { [CONTENT_TYPE_HEADER]: CONTENT_TYPE_PROTOBUF };
53
- // An anonymous visitor gets no header, not an empty one. The protocol has no anonymous form of
54
- // the message, so the absence says nobody claims to be calling.
53
+ // An anonymous visitor sends no header rather than an empty one. The protocol has no anonymous
54
+ // form of the message, so a missing header means the caller is anonymous.
55
55
  if (authTokens !== null)
56
56
  headers[AUTHORIZATION_HEADER] = toBase64(buildAuthTokensBytes(authTokens));
57
57
  try {
@@ -79,9 +79,10 @@ export default class ServiceProxy {
79
79
  // Bound, because fetch called detached from globalThis is refused by browsers
80
80
  return platform.bind(globalThis);
81
81
  }
82
- // What the response says went wrong, if anything. This protocol has no error message of its own
83
- // yet, so a failure body can be anything (a stack trace, an HTML page) and only its start is
84
- // worth carrying. A body that cannot be read adds nothing to the status code.
82
+ // The message for a failed response: the route, plus the start of the body when there is one. The
83
+ // protocol defines no error message, so a failure body can be anything (a stack trace, an HTML
84
+ // page) and only its first MAX_ERROR_MESSAGE_LENGTH characters are kept. A body that cannot be
85
+ // read is left out.
85
86
  static async readErrorMessage(route, response) {
86
87
  let body;
87
88
  try {
@@ -8,21 +8,22 @@ import TaxHelper from "./TaxHelper";
8
8
  // A list of packages being bought: a shopping cart, or what an order contains.
9
9
  //
10
10
  // Every unit price on a list is WITHOUT taxes, with the taxes worked out on top (see
11
- // ShoppingListItem). Each item also offers the price WITH taxes that a customer is shown.
12
- // Everything that adds up (line totals, the list's total, a discount) already has its taxes in it.
13
- // The taxes inside a total are available by type (computedTaxes).
11
+ // ShoppingListItem). Each item also has the price WITH taxes that a customer is shown.
12
+ // Line totals, the list's total and a discount are all amounts with taxes included. computedTaxes
13
+ // gives the taxes inside a total, by type.
14
14
  //
15
- // Wire totals are authoritative: totalAmount is the number to display. The computed ones reproduce
16
- // Java's arithmetic to the unit for the items that are here, so they match the wire whenever the
17
- // items were sent. A list can arrive without its items, and then only the wire total covers it.
15
+ // Wire totals are authoritative: totalAmount is the number to display. The computed totals
16
+ // reproduce Java's arithmetic to the unit for the items that are here, so they match the wire
17
+ // whenever the items were sent. A list can arrive without its items, and then only the wire total
18
+ // is complete.
18
19
  class ShoppingList {
19
20
  // For ProtoMap, which sees totals still multiplied by Constants.AMOUNT_FACTOR.
20
21
  static fromScaledValues(isFinal, autoAddDeliveryCharge, autoAddServiceCharge, inventoryLocationId, priceListId, scaledTotalAmountBeforeDiscount, scaledDiscount, existingItemCount, deletedItemCount, existingItems, deletedItems) {
21
22
  return new ShoppingList(isFinal, autoAddDeliveryCharge, autoAddServiceCharge, inventoryLocationId, priceListId, amountFromScaledValue(scaledTotalAmountBeforeDiscount), amountFromScaledValue(scaledDiscount), existingItemCount, deletedItemCount, existingItems, deletedItems);
22
23
  }
23
- // What these items come to, taxes included and each item's own discount taken off: the sum of
24
- // their finalPrice, which a list of them has as totalAmountBeforeDiscount. Added in scaled values
25
- // and unscaled once, so adding unscaled numbers adds no rounding error.
24
+ // The sum of finalPrice over these items: taxes included, each item's discount taken off. A list
25
+ // of them has this as totalAmountBeforeDiscount. It adds in scaled values and unscales once, to
26
+ // avoid floating point rounding error.
26
27
  static sumOfFinalPrices(items) {
27
28
  return amountFromScaledValue(sumOf(items, (pricing) => pricing.finalPrice));
28
29
  }
@@ -39,17 +40,17 @@ class ShoppingList {
39
40
  this._existingItems = _existingItems;
40
41
  this._deletedItems = _deletedItems;
41
42
  }
42
- // True once the customer is done editing, after which the business may edit it. Only a final
43
- // list can have deleted items. It is never unset.
43
+ // True once the customer has finished editing, after which the business may edit it. Only a
44
+ // final list can have deleted items. It is never unset.
44
45
  get isFinal() {
45
46
  return this._isFinal;
46
47
  }
47
- // True when the delivery charge is a line of its own, carrying the reserved package id
48
- // ReservedPackage.DELIVERY_CHARGE_PACKAGE, rather than being added to the total
48
+ // True when the delivery charge is an item with the reserved package id
49
+ // ReservedPackage.DELIVERY_CHARGE_PACKAGE, rather than an amount added to the total
49
50
  get autoAddDeliveryCharge() {
50
51
  return this._autoAddDeliveryCharge;
51
52
  }
52
- // The same, for ReservedPackage.SERVICE_CHARGE_PACKAGE
53
+ // The same for the service charge, with ReservedPackage.SERVICE_CHARGE_PACKAGE
53
54
  get autoAddServiceCharge() {
54
55
  return this._autoAddServiceCharge;
55
56
  }
@@ -57,8 +58,9 @@ class ShoppingList {
57
58
  get inventoryLocationId() {
58
59
  return this._inventoryLocationId;
59
60
  }
60
- // The price list these prices came from, which is the one a storefront sells from: a cart with
61
- // none uses Constants.MERABILLS_ONLINE_PRICE_LIST_ID, the list Catalog.priceList holds.
61
+ // The id of the price list these prices came from. A storefront sells from
62
+ // Constants.MERABILLS_ONLINE_PRICE_LIST_ID, the list in Catalog.priceList, and CartEditor falls
63
+ // back to that id when the catalog has no price list.
62
64
  get priceListId() {
63
65
  return this._priceListId;
64
66
  }
@@ -66,15 +68,13 @@ class ShoppingList {
66
68
  get totalAmountBeforeDiscount() {
67
69
  return this._totalAmountBeforeDiscount;
68
70
  }
69
- // The discount on the whole list, not on one line. It comes off a total that already has its
70
- // taxes in it.
71
+ // The discount on the whole list, not on one line. It comes off a total that includes taxes.
71
72
  get discount() {
72
73
  return this._discount;
73
74
  }
74
- // What the customer owes, taxes included. Derived from the authoritative totals above, so it is
75
- // the number to display. Never less than zero, as in Java ShoppingList.getTotalAmount: a discount
76
- // greater than the total leaves nothing to pay. Worked out in scaled values, so there is no
77
- // floating point error.
75
+ // The amount to pay, taxes included, and the number to display. Calculated from the wire totals
76
+ // above. Never less than zero, as in Java ShoppingList.getTotalAmount: a discount greater than
77
+ // the total gives zero. It subtracts in scaled values to avoid floating point error.
78
78
  get totalAmount() {
79
79
  const total = amountToScaledValue(this._totalAmountBeforeDiscount) - amountToScaledValue(this._discount);
80
80
  return total > 0n ? amountFromScaledValue(total) : 0;
@@ -99,15 +99,15 @@ class ShoppingList {
99
99
  return this._deletedItems;
100
100
  }
101
101
  // The existing items that are packages bought from the catalog, in the order of the list
102
- // (shoppingListOrder). The server sends them by package id, so that differs from the order
103
- // received. The charge lines are in chargeItems, and the items taken out since the list was made
104
- // final are in removedItems.
102
+ // (shoppingListOrder). The server sends items in package id order, so this differs from the
103
+ // order received. The charge lines are in chargeItems, and the items deleted or replaced since
104
+ // the list was made final are in removedItems.
105
105
  get goodsItems() {
106
106
  return this.derived.goods;
107
107
  }
108
108
  // The existing items that are charge lines (the delivery charge and the service charge), in the
109
- // order of the list. The other two reserved ids, for a discount and a total, are summary lines a
110
- // list does not carry as items. They are discount and totalAmount.
109
+ // order of the list. A list does not carry the other two reserved ids, for a discount and a
110
+ // total, as items. It has them as discount and totalAmount.
111
111
  get chargeItems() {
112
112
  return this.derived.charges;
113
113
  }
@@ -115,23 +115,23 @@ class ShoppingList {
115
115
  get deliveryCharge() {
116
116
  return (this._existingItems.find((item) => item.reservedPackage === proto_ReservedPackage.DELIVERY_CHARGE_PACKAGE) ?? null);
117
117
  }
118
- // The service charge, in the same way
118
+ // The service charge item, or null when this list has none
119
119
  get serviceCharge() {
120
120
  return (this._existingItems.find((item) => item.reservedPackage === proto_ReservedPackage.SERVICE_CHARGE_PACKAGE) ?? null);
121
121
  }
122
- // The items the business took out of the list after the customer made it final, or replaced with
123
- // a changed one, as the customer ordered them. It is deletedItems in the order of the list. A
124
- // deleted charge line is among them, and is told apart by reservedPackage.
122
+ // The items the business deleted or replaced after the customer made the list final, as the
123
+ // customer ordered them. This is deletedItems in the order of the list. A deleted charge line is
124
+ // included, and reservedPackage identifies it.
125
125
  get removedItems() {
126
126
  return this.derived.removed;
127
127
  }
128
- // What the business has done to one line of this list since the customer made it final. It is
129
- // ShoppingListItem.change, except for a legacy order, written by a storefront that did not set
130
- // isOriginal (CartEditor, up to 1.4.0). Every line of such an order reads as added by the
131
- // business. A final list with no original, modified or deleted line is taken to be one, since no
132
- // change the business can make leaves that (adding a line keeps the others original, taking one
133
- // out leaves it in deletedItems, changing one leaves the old line there too).
134
- // Show a list's marks with this, not ShoppingListItem.change.
128
+ // What the business has done to one line of this list since the customer made it final. This is
129
+ // ShoppingListItem.change, except for a legacy order: one written by a storefront that did not
130
+ // set isOriginal (CartEditor, up to 1.4.0). Every line of such an order has change ADDED. A
131
+ // final list with no original, modified or deleted line is taken to be a legacy order, because
132
+ // no change by the business can produce that state: adding a line keeps the others original,
133
+ // deleting one leaves it in deletedItems, and changing one leaves the old line there too.
134
+ // Use this to show a list's marks, not ShoppingListItem.change.
135
135
  changeOf(item) {
136
136
  const change = item.change;
137
137
  if (change !== ItemChange.ADDED)
@@ -139,12 +139,12 @@ class ShoppingList {
139
139
  return this.derived.isUntouchedLegacyOrder ? ItemChange.NONE : ItemChange.ADDED;
140
140
  }
141
141
  // Sum of finalPrice over existingItems, taxes included. Not authoritative (the wire total is),
142
- // and only covers the whole list when existingItems.length equals existingItemCount.
142
+ // and complete only when existingItems.length equals existingItemCount.
143
143
  get computedTotal() {
144
144
  return ShoppingList.sumOfFinalPrices(this._existingItems);
145
145
  }
146
- // The same for the goods alone: what the packages come to, without the charges on top of them.
147
- // This is what the free delivery threshold is measured against.
146
+ // The same for goodsItems alone: what the packages come to, without the charges. The free
147
+ // delivery threshold is compared with this.
148
148
  get computedGoodsTotal() {
149
149
  return ShoppingList.sumOfFinalPrices(this.goodsItems);
150
150
  }
@@ -154,12 +154,12 @@ class ShoppingList {
154
154
  return amountFromScaledValue(sumOf(this._existingItems, (pricing) => pricing.totalTax));
155
155
  }
156
156
  // The taxes inside computedTotal, one entry per TYPE of tax, in the order of the types, added up
157
- // over every item. A type none of the items has is not here. An amount can be zero, for a type
157
+ // over every item. A type none of the items has is not listed. An amount can be zero, for a type
158
158
  // that applies only to free items. Java ShoppingList.getTotalTaxesByTaxCode leaves such a type
159
159
  // out (JavaVectorsTest pins that), and a bill shows no line for it.
160
- // A discount does not change the taxes: it comes off a price that already has them in it.
161
- // Worked out once, like derived but kept apart: this prices the items, and an item that cannot be
162
- // priced must not stop the list's lines being listed.
160
+ // A discount does not change the taxes, because it comes off a price that already includes them.
161
+ // Computed once, like derived but stored apart from it: this prices the items, and an item that
162
+ // cannot be priced must not stop the list's lines from being listed.
163
163
  get computedTaxes() {
164
164
  const existing = TAXES.get(this);
165
165
  if (existing !== undefined)
@@ -177,24 +177,24 @@ class ShoppingList {
177
177
  TAXES.set(this, created);
178
178
  return created;
179
179
  }
180
- // What the existing items come to at their regular prices, with their taxes and none of their own
181
- // discounts taken off: the total had nothing been on offer. Compared with totalAmount it gives
182
- // what the customer saved. Same caveat as computedTotal.
180
+ // The existing items at their regular prices, taxes included and no item discounts taken off:
181
+ // the total if nothing had been on offer. Its difference from totalAmount is what the customer
182
+ // saved (see savings). Same caveat as computedTotal.
183
183
  get computedTotalWithoutDiscounts() {
184
184
  return amountFromScaledValue(sumOf(this._existingItems, (pricing) => pricing.finalPriceWithoutDiscounts));
185
185
  }
186
186
  // What the offers on the items, the discounts on them and the discount on the list took off,
187
- // taxes included, shown on a bill as savings. A waived delivery charge counts too, being an item
188
- // with a price discount like any other, as in the merchant app's total row. So a basket can save
189
- // more once delivery is in the list. Zero when nothing was taken off, never negative. Same caveat
190
- // as computedTotal: it needs the items.
187
+ // taxes included. A bill shows it as savings. A waived delivery charge counts too, as an item
188
+ // with a price discount like any other, as in the merchant app's total row. So the savings can
189
+ // rise once the delivery charge is in the list. Zero when nothing was taken off, never negative.
190
+ // Same caveat as computedTotal: it needs the items.
191
191
  get savings() {
192
192
  const saved = sumOf(this._existingItems, (pricing) => pricing.finalPriceWithoutDiscounts) -
193
193
  amountToScaledValue(this.totalAmount);
194
194
  return saved > 0n ? amountFromScaledValue(saved) : 0;
195
195
  }
196
- // Worked out once, since the list never changes, so a UI reads the same array every time (a
197
- // stable dependency) and the list is not sorted at every render
196
+ // Computed once, because the list never changes. A UI gets the same array on every read (a
197
+ // stable dependency), and the items are not sorted on every render.
198
198
  get derived() {
199
199
  const existing = DERIVED.get(this);
200
200
  if (existing !== undefined)
@@ -221,13 +221,13 @@ export default ShoppingList;
221
221
  //
222
222
  // THE PRICE IS STORED WITHOUT TAXES: unitPrice and priceDiscount are before taxes, which are worked
223
223
  // out on top, as in Java ShoppingListItem and ShoppingListItem.proto. A customer sees prices WITH
224
- // taxes, so CartEditor takes them out on the way in and the *WithTaxes members put them back. Show
225
- // those, never unitPrice, which is not what a customer is charged for a unit.
224
+ // taxes, so CartEditor takes them out on the way in and the *WithTaxes members add them back. Show
225
+ // those, never unitPrice, which leaves out taxes and so is not what a customer is charged.
226
226
  //
227
- // The arithmetic is Java's to the unit and rounds in the same places: the tax base (unit price
228
- // times quantity) to a whole amount, then each tax on its own, half up (see TaxHelper). An amount
229
- // of Transaction.MAX_AMOUNT or more throws an InvalidArgumentException when something first reads
230
- // a price off the item, as in Java (see validatePricing).
227
+ // The arithmetic matches Java to the unit and rounds in the same places: the tax base (unit price
228
+ // times quantity) to a whole amount, then each tax separately, half up (see TaxHelper). An amount
229
+ // of Transaction.MAX_AMOUNT or more throws an InvalidArgumentException the first time a price is
230
+ // read off the item, as in Java (see validatePricing).
231
231
  export class ShoppingListItem {
232
232
  // For ProtoMap, which sees a quantity multiplied by Constants.QUANTITY_FACTOR and prices
233
233
  // multiplied by Constants.AMOUNT_FACTOR.
@@ -254,11 +254,11 @@ export class ShoppingListItem {
254
254
  return this._packageId;
255
255
  }
256
256
  // True when this line is a charge/summary (delivery, service charge, discount, or total) rather
257
- // than a catalog package. A UI must label such lines itself.
257
+ // than a catalog package. Such a line has no catalog name, so a UI must label it.
258
258
  get isReservedPackage() {
259
259
  return Ids.isReservedPackageId(this._packageId);
260
260
  }
261
- // Which of the four that is, and null for a catalog package
261
+ // Which of the four reserved ids this is, or null for a catalog package
262
262
  get reservedPackage() {
263
263
  return this.isReservedPackage
264
264
  ? Number(Ids.getLowPart(this._packageId))
@@ -276,22 +276,23 @@ export class ShoppingListItem {
276
276
  get shoppingListOrder() {
277
277
  return this._shoppingListOrder;
278
278
  }
279
- // True when this line was created before the list was made final. Everything a customer puts in
280
- // a cart is, which separates it from what the business adds or changes afterwards.
279
+ // True when this line was created before the list was made final. Every line a customer puts in
280
+ // a cart is original. Lines the business adds or changes afterwards are not.
281
281
  get isOriginal() {
282
282
  return this._isOriginal;
283
283
  }
284
- // True when this line has been deleted or replaced since the list was made final. Original and
285
- // modified: deleted (and in ShoppingList.deletedItems). Not original but modified: replaced an
286
- // original one. Neither: added by the business.
284
+ // True when the business deleted this line, or made it to replace another, since the list was
285
+ // made final. Original and modified: deleted (and in ShoppingList.deletedItems). Not original but
286
+ // modified: the replacement of an original line. Neither original nor modified: added by the
287
+ // business.
287
288
  get isModified() {
288
289
  return this._isModified;
289
290
  }
290
291
  // What the business has done to this line since the customer made the list final, read off
291
- // isOriginal and isModified as the merchant app does: a "+" beside a line it added, an "x" beside
292
- // one it changed, and the old line listed apart as removed. This reads the line's own flags only.
293
- // To show a list use ShoppingList.changeOf, which also knows that an order written before 1.5.0
294
- // flagged its lines wrongly.
292
+ // isOriginal and isModified as the merchant app does: it marks an added line with "+", a changed
293
+ // line with "x", and lists the old line apart as removed. This uses the line's own flags only.
294
+ // To show a list use ShoppingList.changeOf, which also handles orders written before 1.5.0 that
295
+ // flagged their lines wrongly.
295
296
  get change() {
296
297
  if (this._isOriginal)
297
298
  return this._isModified ? ItemChange.REMOVED : ItemChange.NONE;
@@ -326,10 +327,10 @@ export class ShoppingListItem {
326
327
  return amountFromScaledValue(pricingOf(this).regularUnitPrice);
327
328
  }
328
329
  // What one unit costs a customer: unitPrice with the taxes on it, the offer price when the
329
- // package is on offer. It is the price the customer saw when adding it, and the one to show
330
- // wherever the item is shown. Each tax is rounded, so not every price with taxes can be reached.
331
- // When it cannot, this is the nearest that can, which differs from the catalog's by a thousandth
332
- // or so (Java ShoppingListItem.setDetailsFromTaxInclusivePrices).
330
+ // package is on offer. It is the price the customer saw when adding it, and the one to show for
331
+ // the item. Each tax is rounded, so not every price with taxes can be reached. When it cannot,
332
+ // this is the nearest price that can, which differs from the catalog's by a thousandth or so
333
+ // (Java ShoppingListItem.setDetailsFromTaxInclusivePrices).
333
334
  get unitPriceWithTaxes() {
334
335
  return amountFromScaledValue(pricingOf(this).unitPriceWithTaxes);
335
336
  }
@@ -344,7 +345,7 @@ export class ShoppingListItem {
344
345
  return amountFromScaledValue(pricingOf(this).taxBase);
345
346
  }
346
347
  // Each tax on this line, in the order of taxes: that tax's rate on amount, rounded half up. All
347
- // zero when amount is, since a tax only applies to something that costs. Included in finalPrice.
348
+ // zero when amount is, since a tax applies only to an amount above zero. Included in finalPrice.
348
349
  get taxAmounts() {
349
350
  return pricingOf(this).unscaledTaxes;
350
351
  }
@@ -357,20 +358,20 @@ export class ShoppingListItem {
357
358
  get finalPrice() {
358
359
  return amountFromScaledValue(pricingOf(this).finalPrice);
359
360
  }
360
- // What this line would add at the package's regular price, taxes included, with none of its own
361
- // discount taken off: what a customer would have paid had nothing been on offer. Strike it
361
+ // What this line would add at the package's regular price, taxes included, with the line's
362
+ // discount not taken off: what a customer would have paid if nothing had been on offer. Strike it
362
363
  // through beside finalPrice when it is greater (Java calculateFinalPriceWithoutDiscounts).
363
364
  get finalPriceWithoutDiscounts() {
364
365
  return amountFromScaledValue(pricingOf(this).finalPriceWithoutDiscounts);
365
366
  }
366
- // True when this line costs less than at the regular price with none of its discount, so
367
- // finalPriceWithoutDiscounts is worth striking through beside finalPrice
367
+ // True when finalPrice is less than finalPriceWithoutDiscounts, so the latter can be struck
368
+ // through beside finalPrice
368
369
  get isDiscounted() {
369
370
  const pricing = pricingOf(this);
370
371
  return pricing.finalPriceWithoutDiscounts > pricing.finalPrice;
371
372
  }
372
373
  // True when this line costs nothing though it would have cost something: a delivery charge that
373
- // has been waived, a package given away. A bill reads FREE, with finalPriceWithoutDiscounts
374
+ // has been waived, a package given away. A bill shows FREE, with finalPriceWithoutDiscounts
374
375
  // struck through.
375
376
  get isFree() {
376
377
  const pricing = pricingOf(this);
@@ -378,8 +379,8 @@ export class ShoppingListItem {
378
379
  }
379
380
  }
380
381
  // What the business has done to a line of an order since the customer made it final. The merchant
381
- // app marks the second and third with a "+" and an "x" and explains them in a legend, and lists the
382
- // fourth under "Removed by merchant".
382
+ // app marks ADDED with a "+" and MODIFIED with an "x", explains them in a legend, and lists
383
+ // REMOVED under "Removed by merchant".
383
384
  export var ItemChange;
384
385
  (function (ItemChange) {
385
386
  // As the customer ordered it. Every line of a list that is not final yet is this.
@@ -393,11 +394,11 @@ export var ItemChange;
393
394
  // ShoppingList.deletedItems.
394
395
  ItemChange[ItemChange["REMOVED"] = 3] = "REMOVED";
395
396
  })(ItemChange || (ItemChange = {}));
396
- // Kept beside the item so it stays a plain value: two equal items compare equal whether or not
397
- // either has been priced.
397
+ // Held in a WeakMap rather than a field, so the item stays a plain value: two equal items compare
398
+ // equal whether or not either has been priced.
398
399
  const PRICINGS = new WeakMap();
399
400
  const DERIVED = new WeakMap();
400
- // The taxes of a list by type, which only a list whose items can be priced has
401
+ // The taxes of a list by type. See computedTaxes for why this is stored apart from DERIVED.
401
402
  const TAXES = new WeakMap();
402
403
  function pricingOf(item) {
403
404
  const existing = PRICINGS.get(item);
@@ -423,26 +424,26 @@ function pricingOf(item) {
423
424
  finalPrice: discounted > 0n ? discounted : 0n,
424
425
  finalPriceWithoutDiscounts: TaxHelper.addTaxes(scaledProduct(regularUnitPrice, item.quantity), rates),
425
426
  };
426
- // Before it is kept, so that an item that cannot be priced is refused every time it is asked
427
+ // Validate before storing, so an item that cannot be priced throws on every read
427
428
  validateAmounts(created);
428
429
  PRICINGS.set(item, created);
429
430
  return created;
430
431
  }
431
432
  // Throws an InvalidArgumentException unless every amount the item works out is one the protocol can
432
- // carry. CartEditor calls it before keeping a line. Anything else finds out when it first reads a
433
- // price off the item.
433
+ // carry. CartEditor calls it before storing a line's quantity. Other code gets the exception the
434
+ // first time it reads a price off the item.
434
435
  export function validatePricing(item) {
435
436
  pricingOf(item);
436
437
  }
437
- // Java Transaction.validateAmount refuses an amount of MAX_AMOUNT or more. This applies it to the
438
+ // Java Transaction.validateAmount rejects an amount of MAX_AMOUNT or more. This applies it to the
438
439
  // amounts Java checks on an item: each tax and the final price (recalculate), and the results of
439
440
  // calculateFinalPriceWithoutDiscounts, calculateUnitPriceWithTaxes and
440
- // calculateUnitRegularPriceWithTaxes. They are checked together, once, where the item is priced, so
441
- // an item answers as Java does however it was made (a cart line or the wire) and hands out no
441
+ // calculateUnitRegularPriceWithTaxes. They are checked together, once, when the item is priced.
442
+ // So an item behaves as in Java however it was made (a cart line or the wire), and never returns a
442
443
  // number the protocol cannot carry.
443
- // The amounts are not independent. finalPriceWithoutDiscounts is the cost at the regular price,
444
- // never less than the offer price, and each tax and the final price are parts of it. So none of
445
- // them is over the limit unless that cost is (test/JavaVectors.ts shows this item by item).
444
+ // The amounts are related. finalPriceWithoutDiscounts is the cost at the regular price, never less
445
+ // than the offer price, and each tax and the final price are parts of it. So none of them is over
446
+ // the limit unless that cost is (test/JavaVectors.ts shows this item by item).
446
447
  function validateAmounts(pricing) {
447
448
  const amounts = [
448
449
  ...pricing.taxes.map((tax) => ["tax", tax]),
@@ -458,17 +459,17 @@ function validateAmounts(pricing) {
458
459
  // A scaled amount times a quantity, rounded to a whole amount as Java does:
459
460
  // Math.round(((double) amount) * NumberHelper.intToFloat(scaledQuantity, QUANTITY_FACTOR)). The
460
461
  // quantity is a FLOAT there, so it is one here (fround), and a quantity like 0.7 is not quite 0.7
461
- // in either. That matters only where the product lands on a half.
462
+ // in either. That changes the result only when the product is a half.
462
463
  function scaledProduct(scaledAmount, quantity) {
463
464
  const scaledQuantity = quantityToScaledValue(quantity);
464
465
  const floatQuantity = Math.fround(Math.fround(scaledQuantity) / proto_Constants.QUANTITY_FACTOR);
465
466
  const product = Math.round(Number(scaledAmount) * floatQuantity);
466
467
  return Number.isFinite(product) ? BigInt(product) : 0n;
467
468
  }
468
- // A copy in the order of the list. Java sorts the existing items by shoppingListOrder before
469
- // showing a list (ShoppingListAdapter), and an order arrives with its items in package id order.
470
- // The merchant app shows the removed items in package id order, having no better one. This library
471
- // uses the order they had, which is the customer's.
469
+ // A copy sorted by shoppingListOrder. Java sorts the existing items this way before showing a
470
+ // list (ShoppingListAdapter), and an order arrives with its items in package id order. The
471
+ // merchant app shows the removed items in package id order. This library uses their
472
+ // shoppingListOrder, which is the order the customer made.
472
473
  function sortedByOrder(items) {
473
474
  return [...items].sort((left, right) => left.shoppingListOrder - right.shoppingListOrder);
474
475
  }