@mark1russell7/market 0.1.4 → 0.1.6
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.
- package/README.md +88 -1
- package/build/index.d.ts +155 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +348 -3
- package/build/index.js.map +1 -1
- package/build/plan.d.ts +104 -1
- package/build/plan.d.ts.map +1 -1
- package/build/plan.js +109 -36
- package/build/plan.js.map +1 -1
- package/build/{records-hK1UCmpm.js → records-DU5uvTYJ.js} +35 -2
- package/build/records-DU5uvTYJ.js.map +1 -0
- package/package.json +6 -4
- package/build/records-hK1UCmpm.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @mark1russell7/market
|
|
2
2
|
|
|
3
|
-
The records of a market: a product, an offer of a seller and a price reading, with their checks. The package also has the GTIN check, the match keys of a record, the cost of an order and the storage rules of a source. The offers of a part and the best offer join the observations of the sources to the parts that a buyer wants. The board keeps the current prices within the terms of each source, and plans the reads of a watch. A buy plan gives the best baskets of the parts that a need names.
|
|
3
|
+
The records of a market: a product, an offer of a seller and a price reading, with their checks. The package also has the GTIN check, the match keys of a record, the cost of an order and the storage rules of a source. The offers of a part and the best offer join the observations of the sources to the parts that a buyer wants. The board keeps the current prices within the terms of each source, and plans the reads of a watch. A buy plan gives the best baskets of the parts that a need names. A metered price gives the cost of a cloud resource from its usage, with tiers, free amounts and terms.
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
6
|
pnpm add @mark1russell7/market
|
|
@@ -112,6 +112,90 @@ const plan = planBuys(need, observations);
|
|
|
112
112
|
plan.front.map((choice) => [choice.price.value, choice.values["minutes"]]); // [[120, 20], [200, 50], [280, 80], [420, 100]]
|
|
113
113
|
```
|
|
114
114
|
|
|
115
|
+
## A buy order under a budget
|
|
116
|
+
|
|
117
|
+
A buy order chooses units of products, one unit at a time, under a budget. Each step buys the unit with the largest gain for each unit of money. The choice is `greedy` of `@mark1russell7/strategy-search`. The module knows no topic: the caller gives the value of a choice as a function.
|
|
118
|
+
|
|
119
|
+
- `buyCandidates(wants, observations, { currency, conditions })` gives a candidate for each product with a usable offer. The price is the cost of one unit with its shipping, from the in-stock offer with the lowest cost. Each unit is one order, so the price is an upper limit of the cost of more units. `unpriced` names each product with no usable offer.
|
|
120
|
+
- `orderBuys(candidates, { budget, stages, goal, start })` gives the order. Each stage has a name and a value function. A stage starts from the units of the stage before it, with the money that is left.
|
|
121
|
+
- **The value.** A value is a list of numbers, the most important number first. Thus a gain on the first number comes before each gain on the second number. With `goal: "min"`, a smaller value is better, as for a shortfall.
|
|
122
|
+
- **The stops.** A stage stops at `budget` when no unit fits the money that is left. It stops at `units` when each product is at its `max`. It stops at `no-gain` when no unit has a gain.
|
|
123
|
+
- **The bound.** With gains that do not increase as the order grows, the order holds at least `(1 - 1/e) / 2` of the best value. When two products give more together than apart, set `lazy` to `false`.
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
import { orderBuys, type BuyCandidate } from "@mark1russell7/market/plan";
|
|
127
|
+
|
|
128
|
+
const candidates: BuyCandidate[] = [
|
|
129
|
+
{ product: "JUG", price: 4, max: 10, quote: "a:1" },
|
|
130
|
+
{ product: "CAN", price: 1, max: 10, quote: "a:2" },
|
|
131
|
+
];
|
|
132
|
+
// The days short of a target: water first, then food. A jug gives 4/3 days, and a can gives 1 day.
|
|
133
|
+
const short = (target: number) => (units: Readonly<Record<string, number>>) => [Math.max(0, target - ((units["JUG"] ?? 0) * 4) / 3), Math.max(0, target - (units["CAN"] ?? 0))];
|
|
134
|
+
const order = orderBuys(candidates, { budget: 15, goal: "min", stages: [{ name: "2 days", value: short(2) }, { name: "5 days", value: short(5) }] });
|
|
135
|
+
order.units; // { JUG: 3, CAN: 3 }
|
|
136
|
+
order.stages.map((stage) => stage.spent); // [10, 5]
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Metered prices
|
|
140
|
+
|
|
141
|
+
A cloud resource has a metered price: a price for each unit of an amount that the provider meters. A metered amount is a `time` (the hours of a machine), a `data-time` (stored data in GiB-months), a `data` (a transfer) or a `count` (requests).
|
|
142
|
+
|
|
143
|
+
| Record | Schema | What it has |
|
|
144
|
+
| --- | --- | --- |
|
|
145
|
+
| Metered offer | `meteredOfferSchema` | One resource of a provider in one location, on one term: the source, the id at the source, the location, the term and the specifications. |
|
|
146
|
+
| Metered reading | `meteredReadingSchema` | The metered prices of one offer at one instant: the billing period, the meters, and the upfront money of a committed term. |
|
|
147
|
+
| Metered observation | `meteredObservationSchema` | A metered offer and a reading of that offer. |
|
|
148
|
+
|
|
149
|
+
- **Prices.** A metered price is a quantity with a compound unit of `@mark1russell7/quantity`, for example `USD/h`, `USD/GiB`, `USD/(GiB·mo)` or `USD/{request}`. `meteredKindOf(unit)` gives the kind of its metered amount.
|
|
150
|
+
- **Meters.** A reading has one meter or more, each with its own name. A meter has its tiers, and a free amount as an option.
|
|
151
|
+
- **Tiers.** A tier has its start and its price for each unit. The first tier starts at zero, and the starts increase. A start can have another unit of the same amount, for example `TiB` with prices in `USD/GiB`.
|
|
152
|
+
- **Free amounts.** A free amount is for each billing period. Its scope tells which usage shares it: the `account`, each `region` or each `resource`.
|
|
153
|
+
- **Terms.** The term of an offer is `on-demand`, `spot` or `committed`. The provider can end a `spot` use at any time, after the `notice`. A preemptible use is a `spot` use. A `committed` term has its `length`, and its readings can have `upfront` money.
|
|
154
|
+
- **Location.** The location of an offer has the provider, its region and its zone. The region and the zone are the ids of the provider. A source gives each location and each term its own offer id, so the readings of one offer make one series.
|
|
155
|
+
- **Terms of a source.** A metered reading has `offerId` and `at`, as a price reading has. Thus `keepUntil`, `isKept`, `permitsHistory` and `permitsTrend` apply to it.
|
|
156
|
+
|
|
157
|
+
`meteredCost(observation, usage, { freeUsed })` gives the cost of an offer for one period. `usage` has the amount of each meter in that period, by the name of the meter.
|
|
158
|
+
|
|
159
|
+
1. The free amount comes off the usage first. `freeUsed` is the part of the free amount that other usage in its scope used.
|
|
160
|
+
2. The tiers count the rest of the usage from zero. Each tier applies its price to its part of the usage.
|
|
161
|
+
3. A committed term adds its upfront money, times the period, divided by the length.
|
|
162
|
+
|
|
163
|
+
The arithmetic is exact, and the function does not round the cost to the cent. A meter with no usage costs zero. The result has the cost of each meter, the part of the upfront money, and the total.
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
import { meteredCost, type MeteredObservation } from "@mark1russell7/market";
|
|
167
|
+
|
|
168
|
+
const id = "example-cloud:egress/region-1";
|
|
169
|
+
const observation: MeteredObservation = {
|
|
170
|
+
offer: {
|
|
171
|
+
id,
|
|
172
|
+
source: "example-cloud",
|
|
173
|
+
sourceId: "egress/region-1",
|
|
174
|
+
title: "Data out to the internet",
|
|
175
|
+
location: { provider: "example-cloud", region: "region-1" },
|
|
176
|
+
term: { kind: "on-demand" },
|
|
177
|
+
specs: [],
|
|
178
|
+
},
|
|
179
|
+
reading: {
|
|
180
|
+
offerId: id,
|
|
181
|
+
at: "2026-11-12T18:00:00Z",
|
|
182
|
+
period: { value: 1, unit: "mo" },
|
|
183
|
+
meters: [
|
|
184
|
+
{
|
|
185
|
+
name: "egress",
|
|
186
|
+
tiers: [
|
|
187
|
+
{ from: { value: 0, unit: "GiB" }, unitPrice: { value: 0.09, unit: "USD/GiB" } },
|
|
188
|
+
{ from: { value: 10, unit: "TiB" }, unitPrice: { value: 0.085, unit: "USD/GiB" } },
|
|
189
|
+
],
|
|
190
|
+
free: { amount: { value: 100, unit: "GiB" }, scope: "account" },
|
|
191
|
+
},
|
|
192
|
+
],
|
|
193
|
+
},
|
|
194
|
+
};
|
|
195
|
+
// The free 100 GiB come off first. Then 10,240 GiB cost $0.09 each, and 1 GiB costs $0.085.
|
|
196
|
+
meteredCost(observation, { egress: { value: 10_341, unit: "GiB" } }).total; // { value: 921.685, unit: "USD" }
|
|
197
|
+
```
|
|
198
|
+
|
|
115
199
|
## Example
|
|
116
200
|
|
|
117
201
|
```ts
|
|
@@ -141,6 +225,9 @@ isKept(terms, reading, "2026-11-16T00:00:00Z"); // false
|
|
|
141
225
|
- The match keys do not know the aliases of a brand. `Western Digital` and `WD` give two keys. A want of a part names each form of the brand.
|
|
142
226
|
- A part number of a want matches each longer part number that starts with it. A want gives the full part number of the maker.
|
|
143
227
|
- The money of the quantity package has one currency: the US dollar.
|
|
228
|
+
- A month of the quantity package is 730.485 hours, the mean month of the calendar. Many providers bill a month as 730 hours. Give the usage in the unit of the price.
|
|
229
|
+
- The quantity package has no prefix for a count. Thus a price for each million requests is a price for each request: `0.0000004 USD/{request}`.
|
|
230
|
+
- `meteredCost` gives the cost of one offer. When offers share a free amount, the caller divides the free amount with `freeUsed`.
|
|
144
231
|
- The price of a basket adds the cost of each item. Each item is one order with its own shipping, so the plan does not know a shared shipping cost.
|
|
145
232
|
- A buy plan does not compare the count of an item with the count of the available units of its offer.
|
|
146
233
|
- The package has no history of prices yet. Roadmap item R5 adds it, after the owner chooses its source.
|
package/build/index.d.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* also has the GTIN check, the match keys of a record, the cost of an order and the storage rules of a source.
|
|
4
4
|
* The offers of a part and the best offer join the observations of the sources to the parts that a buyer wants.
|
|
5
5
|
* The board keeps the current prices within the terms of each source, and plans the reads of a watch.
|
|
6
|
+
* A metered offer has a price for each unit of a metered amount, in tiers, with a free amount and a term.
|
|
6
7
|
*/
|
|
7
8
|
import { A as priceBreakSchema, B as PartNumber, C as Spec, D as offerId, E as moneySchema, F as sourceOfOffer, H as matchKeys, I as sourceSchema, L as specSchema, M as productSchema, N as sellerSchema, O as offerSchema, P as shippingSchema, R as textSchema, S as Shipping, T as instantSchema, V as foldCode, _ as PriceBreak, a as PartWant, b as Rating, c as offersOfPart, d as Availability, f as CONDITIONS, g as Offer, h as Format, i as OfferChoice, j as priceReadingSchema, k as partNumberSchema, l as offersPart, m as FORMATS, n as BestOfferOptions, o as bestOffer, p as Condition, r as Observation, s as latestObservations, t as BestOffer, u as AVAILABILITIES, v as PriceReading, w as gtinSchema, x as Seller, y as Product, z as Identifiers } from "./offers-CVUAcRHs.js";
|
|
8
9
|
import { Quantity } from "@mark1russell7/quantity";
|
|
@@ -203,6 +204,159 @@ export declare function gtinCheckDigit(body: string): number;
|
|
|
203
204
|
* It refuses a length other than 8, 12, 13 or 14 digits, a wrong check digit, and a GTIN of zeros only.
|
|
204
205
|
*/
|
|
205
206
|
export declare function parseGtin(text: string): string | null;
|
|
207
|
+
/**
|
|
208
|
+
* The kinds of a metered amount: a time (the hours of a machine), data times time (stored data), data (a transfer)
|
|
209
|
+
* and a count (requests).
|
|
210
|
+
*/
|
|
211
|
+
export declare const METERED_KINDS: readonly ["time", "data-time", "data", "count"];
|
|
212
|
+
/** The kind of a metered amount. */
|
|
213
|
+
type MeteredKind = (typeof METERED_KINDS)[number];
|
|
214
|
+
/**
|
|
215
|
+
* The scopes of a free amount. With `account`, all the usage of the account in all regions shares one free amount.
|
|
216
|
+
* With `region`, each region has its own free amount. With `resource`, each resource has its own free amount.
|
|
217
|
+
*/
|
|
218
|
+
export declare const FREE_SCOPES: readonly ["account", "region", "resource"];
|
|
219
|
+
/** The scope of a free amount: the usage that shares it. */
|
|
220
|
+
type FreeScope = (typeof FREE_SCOPES)[number];
|
|
221
|
+
/** The location of a metered offer: the provider, and its region and zone, as the provider names them. */
|
|
222
|
+
interface Location {
|
|
223
|
+
readonly provider: string;
|
|
224
|
+
readonly region: string;
|
|
225
|
+
readonly zone?: string | undefined;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* The term of a metered price. A `spot` price is also a preemptible price: the provider can end the use at any time,
|
|
229
|
+
* after the `notice`. A `committed` price binds the buyer for its `length`.
|
|
230
|
+
*/
|
|
231
|
+
type PriceTerm = {
|
|
232
|
+
readonly kind: "on-demand";
|
|
233
|
+
} | {
|
|
234
|
+
readonly kind: "spot";
|
|
235
|
+
readonly notice?: Quantity | undefined;
|
|
236
|
+
} | {
|
|
237
|
+
readonly kind: "committed";
|
|
238
|
+
readonly length: Quantity;
|
|
239
|
+
};
|
|
240
|
+
/** A metered offer: one resource of a provider in one location, on one term, with the identifiers that the source gives. */
|
|
241
|
+
interface MeteredOffer {
|
|
242
|
+
readonly id: string;
|
|
243
|
+
readonly source: string;
|
|
244
|
+
readonly sourceId: string;
|
|
245
|
+
readonly productId?: string | undefined;
|
|
246
|
+
readonly title: string;
|
|
247
|
+
readonly url?: string | undefined;
|
|
248
|
+
readonly location: Location;
|
|
249
|
+
readonly term: PriceTerm;
|
|
250
|
+
readonly specs: readonly Spec[];
|
|
251
|
+
}
|
|
252
|
+
/** A tier of a meter: the price for each unit of the usage from `from` to the start of the next tier, in one period. */
|
|
253
|
+
interface Tier {
|
|
254
|
+
readonly from: Quantity;
|
|
255
|
+
readonly unitPrice: Quantity;
|
|
256
|
+
}
|
|
257
|
+
/** A free amount of a meter for each period, and the scope that shares it. */
|
|
258
|
+
interface FreeAmount {
|
|
259
|
+
readonly amount: Quantity;
|
|
260
|
+
readonly scope: FreeScope;
|
|
261
|
+
}
|
|
262
|
+
/** A meter of a metered reading: the tiers of the price of one metered amount, and its free amount. */
|
|
263
|
+
interface Meter {
|
|
264
|
+
readonly name: string;
|
|
265
|
+
readonly tiers: readonly Tier[];
|
|
266
|
+
readonly free?: FreeAmount | undefined;
|
|
267
|
+
}
|
|
268
|
+
/** A metered reading: the metered prices of one offer at one instant. */
|
|
269
|
+
interface MeteredReading {
|
|
270
|
+
readonly offerId: string;
|
|
271
|
+
readonly at: string;
|
|
272
|
+
readonly period: Quantity;
|
|
273
|
+
readonly meters: readonly Meter[];
|
|
274
|
+
readonly upfront?: Quantity | undefined;
|
|
275
|
+
}
|
|
276
|
+
/** One metered offer of a source, and its metered reading at one instant. */
|
|
277
|
+
interface MeteredObservation {
|
|
278
|
+
readonly offer: MeteredOffer;
|
|
279
|
+
readonly reading: MeteredReading;
|
|
280
|
+
}
|
|
281
|
+
/** The usage of each meter in one period, by the name of the meter. */
|
|
282
|
+
type MeteredUsage = Readonly<Record<string, Quantity>>;
|
|
283
|
+
/** These options change the cost of a metered offer. */
|
|
284
|
+
interface MeteredCostOptions {
|
|
285
|
+
/**
|
|
286
|
+
* The part of the free amount of each meter that other usage in its scope used in the same period. The keys are
|
|
287
|
+
* the names of the meters. The default is none.
|
|
288
|
+
*/
|
|
289
|
+
readonly freeUsed?: MeteredUsage | undefined;
|
|
290
|
+
}
|
|
291
|
+
/** The cost of the usage of one meter in one period. */
|
|
292
|
+
interface MeterCost {
|
|
293
|
+
readonly name: string;
|
|
294
|
+
readonly cost: Quantity;
|
|
295
|
+
}
|
|
296
|
+
/** The cost of a metered offer for one period. */
|
|
297
|
+
interface MeteredCost {
|
|
298
|
+
/** The cost of each meter, in the order of the meters of the reading. */
|
|
299
|
+
readonly meters: readonly MeterCost[];
|
|
300
|
+
/** The part of the upfront money of a committed term for one period, or zero. */
|
|
301
|
+
readonly upfront: Quantity;
|
|
302
|
+
/** The sum of the cost of each meter and the part of the upfront money. */
|
|
303
|
+
readonly total: Quantity;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* This function gives the kind of the metered amount of the unit of a metered price, for example `time` for `USD/h`
|
|
307
|
+
* and `data-time` for `USD/(GiB·mo)`.
|
|
308
|
+
*
|
|
309
|
+
* @throws RangeError when the unit is not a price for each unit of a metered amount.
|
|
310
|
+
*/
|
|
311
|
+
export declare function meteredKindOf(unit: string): MeteredKind;
|
|
312
|
+
/**
|
|
313
|
+
* This schema accepts the location of a metered offer. The name of the provider has small letters, digits and
|
|
314
|
+
* hyphens, as the name of a source. The region and the zone are the ids of the provider.
|
|
315
|
+
*/
|
|
316
|
+
export declare const locationSchema: z.ZodType<Location>;
|
|
317
|
+
/**
|
|
318
|
+
* This schema accepts the term of a metered price. A `spot` term can have the notice before the provider ends the
|
|
319
|
+
* use. A `committed` term has its length.
|
|
320
|
+
*/
|
|
321
|
+
export declare const priceTermSchema: z.ZodType<PriceTerm>;
|
|
322
|
+
/**
|
|
323
|
+
* This schema accepts a metered offer: one resource of a provider in one location, on one term. The id is the
|
|
324
|
+
* source and the source id, with a colon between them.
|
|
325
|
+
*/
|
|
326
|
+
export declare const meteredOfferSchema: z.ZodType<MeteredOffer>;
|
|
327
|
+
/**
|
|
328
|
+
* This schema accepts a metered price of zero or more: an amount of money for each unit of a metered amount, for
|
|
329
|
+
* example `{ "value": 0.0116, "unit": "USD/h" }`.
|
|
330
|
+
*/
|
|
331
|
+
export declare const meteredPriceSchema: z.ZodType<Quantity, Quantity>;
|
|
332
|
+
/** This schema accepts a tier: the start of its usage, and its price for each unit. The start measures the metered amount of the price. */
|
|
333
|
+
export declare const tierSchema: z.ZodType<Tier>;
|
|
334
|
+
/** This schema accepts a free amount of more than zero for each period, and its scope. */
|
|
335
|
+
export declare const freeAmountSchema: z.ZodType<FreeAmount>;
|
|
336
|
+
/**
|
|
337
|
+
* This schema accepts a meter. The first tier starts at zero, and the starts increase. The prices of the tiers and
|
|
338
|
+
* the free amount measure one metered amount.
|
|
339
|
+
*/
|
|
340
|
+
export declare const meterSchema: z.ZodType<Meter>;
|
|
341
|
+
/**
|
|
342
|
+
* This schema accepts a metered reading: the metered prices of one offer at one instant. The tiers and the free
|
|
343
|
+
* amounts count the usage of one `period`. Each meter has its own name.
|
|
344
|
+
*/
|
|
345
|
+
export declare const meteredReadingSchema: z.ZodType<MeteredReading>;
|
|
346
|
+
/** This schema accepts a metered observation: an offer, and a reading of that offer. Only a committed term has upfront money. */
|
|
347
|
+
export declare const meteredObservationSchema: z.ZodType<MeteredObservation>;
|
|
348
|
+
/**
|
|
349
|
+
* This function gives the cost of a metered offer for one period, from the usage of each meter in that period. A
|
|
350
|
+
* meter with no usage costs zero. The free amount of a meter comes off its usage first, less `freeUsed`. The tiers
|
|
351
|
+
* then count the rest of the usage from zero. A committed term adds its upfront money times the period over the length.
|
|
352
|
+
*
|
|
353
|
+
* The arithmetic is exact, and the function does not round the cost to the cent. Each value is the nearest number to
|
|
354
|
+
* the exact cost. The function converts the units with the exact factors of `@mark1russell7/quantity`.
|
|
355
|
+
*
|
|
356
|
+
* @throws RangeError when the usage names a meter that the reading does not have. It also throws when an amount
|
|
357
|
+
* of usage is negative, or does not measure the metered amount of its meter.
|
|
358
|
+
*/
|
|
359
|
+
export declare function meteredCost(observation: MeteredObservation, usage: MeteredUsage, options?: MeteredCostOptions): MeteredCost;
|
|
206
360
|
/**
|
|
207
361
|
* This function gives the unit price for an order of `count` units. The price of the largest break at or
|
|
208
362
|
* below the count applies, or the price of the reading when no break applies.
|
|
@@ -217,5 +371,5 @@ export declare function unitPriceFor(reading: PriceReading, count: number): Quan
|
|
|
217
371
|
* @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.
|
|
218
372
|
*/
|
|
219
373
|
export declare function costOf(reading: PriceReading, count: number): Quantity | null;
|
|
220
|
-
export { AVAILABILITIES, type Availability, type BestOffer, type BestOfferOptions, type Board, type BoardDrop, type BoardRead, CONDITIONS, type Condition, type Dropped, FORMATS, type Format, type Identifiers, type KeepOptions, type Kept, type Observation, type Offer, type OfferChoice, type PartNumber, type PartWant, type PriceBreak, type PriceReading, type Product, type Rating, type ReadInterval, type ReadPlan, type Retention, type ScheduleOptions, type Seller, type SettleOptions, type Settled, type Shipping, type SourceTerms, type Spec, type WatchEntry, bestOffer, foldCode, gtinSchema, instantSchema, latestObservations, matchKeys, moneySchema, offerId, offerSchema, offersOfPart, offersPart, partNumberSchema, priceBreakSchema, priceReadingSchema, productSchema, sellerSchema, shippingSchema, sourceOfOffer, sourceSchema, specSchema, textSchema };
|
|
374
|
+
export { AVAILABILITIES, type Availability, type BestOffer, type BestOfferOptions, type Board, type BoardDrop, type BoardRead, CONDITIONS, type Condition, type Dropped, FORMATS, type Format, type FreeAmount, type FreeScope, type Identifiers, type KeepOptions, type Kept, type Location, type Meter, type MeterCost, type MeteredCost, type MeteredCostOptions, type MeteredKind, type MeteredObservation, type MeteredOffer, type MeteredReading, type MeteredUsage, type Observation, type Offer, type OfferChoice, type PartNumber, type PartWant, type PriceBreak, type PriceReading, type PriceTerm, type Product, type Rating, type ReadInterval, type ReadPlan, type Retention, type ScheduleOptions, type Seller, type SettleOptions, type Settled, type Shipping, type SourceTerms, type Spec, type Tier, type WatchEntry, bestOffer, foldCode, gtinSchema, instantSchema, latestObservations, matchKeys, moneySchema, offerId, offerSchema, offersOfPart, offersPart, partNumberSchema, priceBreakSchema, priceReadingSchema, productSchema, sellerSchema, shippingSchema, sourceOfOffer, sourceSchema, specSchema, textSchema };
|
|
221
375
|
//# sourceMappingURL=index.d.ts.map
|
package/build/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/terms.ts","../src/board.ts","../src/gtin.ts","../src/price.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../src/terms.ts","../src/board.ts","../src/gtin.ts","../src/metered.ts","../src/price.ts"],"mappings":";;;;;;;;;;;KAMY;WACG;;WACA;WAA0B,KAAK;;WAC/B;;;UAGE;WACN;WACA,WAAW;WACX;WACA;WACA;;;;;;qBAOE,iBAAiB,EAAE,QAAQ;;;;;qBAU3B,mBAAmB,EAAE,QAAQ;;;;;wBAY1B,UAAU,OAAO,aAAa;WAAoB;;;;;;wBAalD,OAAO,OAAO,aAAa;WAAoB;GAAc,aAAa;;wBAW1E,eAAe,OAAO;;wBAKtB,aAAa,OAAO;;qBC7DvB;;qBAGA,mBAAmB,EAAE,QAAQ;;UAKzB;WACN;WACA;WACA,uBAAuB;;;UAIjB;WACN,eAAe;WACf;WACA,gBAAgB;;;qBAId,iBAAiB,EAAE,QAAQ;;qBAO3B,aAAa,EAAE,QAAQ;;UAOnB;WACN;WACA;;;UAIM;;WAEN,gBAAgB;;WAEhB;;WAEA;;;UAIM;;WAEN,eAAe;;WAEf,kBAAkB;;;;;;;;;;;wBAyBb,iBAAiB,uBAAuB,eAAe,SAAS,cAAc;;UA0B7E,sBAAsB;;WAE5B;;;UAIM,kBAAkB;WACxB;;;UAIM;WACN,OAAO;WACP,kBAAkB;;;;;;;;;;wBAab,YAAY,OAAO,OAAO,SAAS,eAAe,OAAO,YAAY;;;;;wBAwBrE,kBAAkB,OAAO,OAAO,SAAS,cAAc;;wBAKvD,UAAU,OAAO,QAAQ;;UAKxB;;WAEN;;WAEA;;WAEA,OAAO;;;qBAIL,kBAAkB,EAAE,QAAQ;;UAOxB;;WAEN,gBAAgB;;;;;WAKhB,OAAO;;;KAIN;WAA0B;WAAmB;;WAA0B;WAAoB;;;;;;;;wBAQvF,aAAa,OAAO,YAAY,SAAS,kBAAkB;;wBAc3D,cAAc,kBAAkB,cAAc,SAAS;;UAatD;;WAEN;;;;;;WAMA;;WAEA;;;;;;;;;wBAUK,UAAU,kBAAkB,cAAc,MAAM,SAAS,yBAAyB,aAAa,SAAS,kBAAkB;;;;;;wBC5P1H,eAAe;;;;;wBAcf,UAAU;;;;;qBCDb;;KAED,sBAAsB;;;;;qBAMrB;;KAED,oBAAoB;;UAGf;WACN;WACA;WACA;;;;;;KAOC;WACG;;WACA;WAAuB,SAAS;;WAChC;WAA4B,QAAQ;;;UAGlC;WACN;WACA;WACA;WACA;WACA;WACA;WACA,UAAU;WACV,MAAM;WACN,gBAAgB;;;UAIV;WACN,MAAM;WACN,WAAW;;;UAIL;WACN,QAAQ;WACR,OAAO;;;UAID;WACN;WACA,gBAAgB;WAChB,OAAO;;;UAID;WACN;WACA;WACA,QAAQ;WACR,iBAAiB;WACjB,UAAU;;;UAIJ;WACN,OAAO;WACP,SAAS;;;KAIR,eAAe,SAAS,eAAe;;UAGlC;;;;;WAKN,WAAW;;;UAIL;WACN;WACA,MAAM;;;UAIA;;WAEN,iBAAiB;;WAEjB,SAAS;;WAET,OAAO;;;;;;;;wBAiFF,cAAc,eAAe;;;;;qBAUhC,gBAAgB,EAAE,QAAQ;;;;;qBAU1B,iBAAiB,EAAE,QAAQ;;;;;qBAU3B,oBAAoB,EAAE,QAAQ;;;;;qBAqB9B,oBAAoB,EAAE,QAAQ,UAAU;;qBAQxC,YAAY,EAAE,QAAQ;;qBAatB,kBAAkB,EAAE,QAAQ;;;;;qBAS5B,aAAa,EAAE,QAAQ;;;;;qBA4CvB,sBAAsB,EAAE,QAAQ;;qBAchC,0BAA0B,EAAE,QAAQ;;;;;;;;;;;;wBAqFjC,YAAY,aAAa,oBAAoB,OAAO,cAAc,UAAS,qBAA0B;;;;;;;wBCrarG,aAAa,SAAS,cAAc,gBAAgB;;;;;;;wBAgBpD,OAAO,SAAS,cAAc,gBAAgB"}
|
package/build/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { valueIn } from "@mark1russell7/quantity";
|
|
1
|
+
import { D as matchKeys, E as foldCode, O as gtinCheckDigit, S as offersPart, T as unitPriceFor, _ as specSchema, a as instantSchema, b as latestObservations, c as offerSchema, d as priceReadingSchema, f as productSchema, g as sourceSchema, h as sourceOfOffer, i as gtinSchema, k as parseGtin, l as partNumberSchema, m as shippingSchema, n as CONDITIONS, o as moneySchema, p as sellerSchema, r as FORMATS, s as offerId, t as AVAILABILITIES, u as priceBreakSchema, v as textSchema, w as costOf, x as offersOfPart, y as bestOffer } from "./records-DU5uvTYJ.js";
|
|
2
|
+
import { UnitError, canonicalUnit, convertExact, convertible, parseUnit, quantity, rationals, valueIn } from "@mark1russell7/quantity";
|
|
3
3
|
import { quantitySchema } from "@mark1russell7/quantity/schema";
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
// src/terms.ts
|
|
@@ -284,6 +284,351 @@ function planReads(entries, last, now, options) {
|
|
|
284
284
|
next: Number.isFinite(next) ? new Date(next).toISOString() : null
|
|
285
285
|
};
|
|
286
286
|
}
|
|
287
|
-
|
|
287
|
+
// src/metered.ts
|
|
288
|
+
/**
|
|
289
|
+
* The kinds of a metered amount: a time (the hours of a machine), data times time (stored data), data (a transfer)
|
|
290
|
+
* and a count (requests).
|
|
291
|
+
*/
|
|
292
|
+
const METERED_KINDS = [
|
|
293
|
+
"time",
|
|
294
|
+
"data-time",
|
|
295
|
+
"data",
|
|
296
|
+
"count"
|
|
297
|
+
];
|
|
298
|
+
/**
|
|
299
|
+
* The scopes of a free amount. With `account`, all the usage of the account in all regions shares one free amount.
|
|
300
|
+
* With `region`, each region has its own free amount. With `resource`, each resource has its own free amount.
|
|
301
|
+
*/
|
|
302
|
+
const FREE_SCOPES = [
|
|
303
|
+
"account",
|
|
304
|
+
"region",
|
|
305
|
+
"resource"
|
|
306
|
+
];
|
|
307
|
+
/** This function gives the kind of a metered amount from the exponents of its data and its time, or undefined. */
|
|
308
|
+
function kindOfExponents(data, time) {
|
|
309
|
+
if (data === 0 && time === 0) return "count";
|
|
310
|
+
if (data === 0 && time === 1) return "time";
|
|
311
|
+
if (data === 1 && time === 0) return "data";
|
|
312
|
+
if (data === 1 && time === 1) return "data-time";
|
|
313
|
+
}
|
|
314
|
+
/** This function reads the unit of a metered price. It gives the parts of the unit, or the problem as a text. */
|
|
315
|
+
function readPriceUnit(unit) {
|
|
316
|
+
const refused = `The unit ${unit} is not a price for each unit of a metered amount, for example USD/h.`;
|
|
317
|
+
let parsed;
|
|
318
|
+
try {
|
|
319
|
+
parsed = parseUnit(unit);
|
|
320
|
+
} catch (error) {
|
|
321
|
+
if (error instanceof UnitError) return refused;
|
|
322
|
+
throw error;
|
|
323
|
+
}
|
|
324
|
+
const above = parsed.components.filter((component) => component.exponent > 0);
|
|
325
|
+
const [money] = above;
|
|
326
|
+
const atom = money?.atom;
|
|
327
|
+
const isMoney = atom !== void 0 && Object.keys(atom.vector).length === 1 && atom.vector.money === 1;
|
|
328
|
+
const below = parsed.components.some((component) => component.exponent < 0);
|
|
329
|
+
if (above.length !== 1 || money?.exponent !== 1 || money.annotation !== void 0 || !isMoney || !below) return refused;
|
|
330
|
+
const { money: units = 0, data = 0, time = 0, ...others } = parsed.vector;
|
|
331
|
+
const kind = Object.values(others).every((exponent) => exponent === 0) && units === 1 ? kindOfExponents(-data, -time) : void 0;
|
|
332
|
+
return kind === void 0 ? refused : {
|
|
333
|
+
money: atom.symbol,
|
|
334
|
+
kind
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
/** This function gives the unit of a price for each unit of an amount, for example `USD/(GiB·mo)` for `GiB·mo`. */
|
|
338
|
+
function priceUnitFor(money, amountUnit) {
|
|
339
|
+
try {
|
|
340
|
+
return canonicalUnit(`${money}/${amountUnit}`);
|
|
341
|
+
} catch (error) {
|
|
342
|
+
if (error instanceof UnitError) return void 0;
|
|
343
|
+
throw error;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
/** This function tells if an amount in one unit converts to another unit. A unit that the quantity package does not know does not convert. */
|
|
347
|
+
function converts(from, to) {
|
|
348
|
+
try {
|
|
349
|
+
return convertible(from, to);
|
|
350
|
+
} catch (error) {
|
|
351
|
+
if (error instanceof UnitError) return false;
|
|
352
|
+
throw error;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
/** This function gives the start of each tier in one unit, or undefined when a start does not convert to it. */
|
|
356
|
+
function startsOf(tiers, unit) {
|
|
357
|
+
try {
|
|
358
|
+
return tiers.map((tier) => convertExact(rationals.fromNumber(tier.from.value), tier.from.unit, unit));
|
|
359
|
+
} catch (error) {
|
|
360
|
+
if (error instanceof UnitError || error instanceof RangeError) return void 0;
|
|
361
|
+
throw error;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
/** This function tells if a unit of an amount measures the metered amount of a unit of price. */
|
|
365
|
+
function measures(amountUnit, priceUnit, money) {
|
|
366
|
+
const unit = priceUnitFor(money, amountUnit);
|
|
367
|
+
return unit !== void 0 && converts(unit, priceUnit);
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* This function gives the kind of the metered amount of the unit of a metered price, for example `time` for `USD/h`
|
|
371
|
+
* and `data-time` for `USD/(GiB·mo)`.
|
|
372
|
+
*
|
|
373
|
+
* @throws RangeError when the unit is not a price for each unit of a metered amount.
|
|
374
|
+
*/
|
|
375
|
+
function meteredKindOf(unit) {
|
|
376
|
+
const parts = readPriceUnit(unit);
|
|
377
|
+
if (typeof parts === "string") throw new RangeError(parts);
|
|
378
|
+
return parts.kind;
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* This schema accepts the location of a metered offer. The name of the provider has small letters, digits and
|
|
382
|
+
* hyphens, as the name of a source. The region and the zone are the ids of the provider.
|
|
383
|
+
*/
|
|
384
|
+
const locationSchema = z.strictObject({
|
|
385
|
+
provider: sourceSchema,
|
|
386
|
+
region: textSchema,
|
|
387
|
+
zone: textSchema.optional()
|
|
388
|
+
});
|
|
389
|
+
/**
|
|
390
|
+
* This schema accepts the term of a metered price. A `spot` term can have the notice before the provider ends the
|
|
391
|
+
* use. A `committed` term has its length.
|
|
392
|
+
*/
|
|
393
|
+
const priceTermSchema = z.discriminatedUnion("kind", [
|
|
394
|
+
z.strictObject({ kind: z.literal("on-demand") }),
|
|
395
|
+
z.strictObject({
|
|
396
|
+
kind: z.literal("spot"),
|
|
397
|
+
notice: quantitySchema("time", { nonnegative: true }).optional()
|
|
398
|
+
}),
|
|
399
|
+
z.strictObject({
|
|
400
|
+
kind: z.literal("committed"),
|
|
401
|
+
length: quantitySchema("time", { positive: true })
|
|
402
|
+
})
|
|
403
|
+
]);
|
|
404
|
+
/**
|
|
405
|
+
* This schema accepts a metered offer: one resource of a provider in one location, on one term. The id is the
|
|
406
|
+
* source and the source id, with a colon between them.
|
|
407
|
+
*/
|
|
408
|
+
const meteredOfferSchema = z.strictObject({
|
|
409
|
+
id: textSchema,
|
|
410
|
+
source: sourceSchema,
|
|
411
|
+
sourceId: textSchema,
|
|
412
|
+
productId: textSchema.optional(),
|
|
413
|
+
title: textSchema,
|
|
414
|
+
url: z.url({ protocol: /^https$/ }).optional(),
|
|
415
|
+
location: locationSchema,
|
|
416
|
+
term: priceTermSchema,
|
|
417
|
+
specs: z.array(specSchema)
|
|
418
|
+
}).refine((offer) => offer.id === offerId(offer.source, offer.sourceId), {
|
|
419
|
+
message: "The id of an offer is its source and its source id, with a colon between them.",
|
|
420
|
+
path: ["id"]
|
|
421
|
+
});
|
|
422
|
+
/**
|
|
423
|
+
* This schema accepts a metered price of zero or more: an amount of money for each unit of a metered amount, for
|
|
424
|
+
* example `{ "value": 0.0116, "unit": "USD/h" }`.
|
|
425
|
+
*/
|
|
426
|
+
const meteredPriceSchema = quantitySchema(void 0, { nonnegative: true }).superRefine((price, context) => {
|
|
427
|
+
const parts = readPriceUnit(price.unit);
|
|
428
|
+
if (typeof parts === "string") context.addIssue({
|
|
429
|
+
code: "custom",
|
|
430
|
+
message: parts
|
|
431
|
+
});
|
|
432
|
+
});
|
|
433
|
+
/** This schema accepts a tier: the start of its usage, and its price for each unit. The start measures the metered amount of the price. */
|
|
434
|
+
const tierSchema = z.strictObject({
|
|
435
|
+
from: quantitySchema(void 0, { nonnegative: true }),
|
|
436
|
+
unitPrice: meteredPriceSchema
|
|
437
|
+
}).superRefine((tier, context) => {
|
|
438
|
+
const parts = readPriceUnit(tier.unitPrice.unit);
|
|
439
|
+
if (typeof parts === "string" || measures(tier.from.unit, tier.unitPrice.unit, parts.money)) return;
|
|
440
|
+
context.addIssue({
|
|
441
|
+
code: "custom",
|
|
442
|
+
message: `The start ${tier.from.unit} does not measure the metered amount of the price ${tier.unitPrice.unit}.`,
|
|
443
|
+
path: ["from"]
|
|
444
|
+
});
|
|
445
|
+
});
|
|
446
|
+
/** This schema accepts a free amount of more than zero for each period, and its scope. */
|
|
447
|
+
const freeAmountSchema = z.strictObject({
|
|
448
|
+
amount: quantitySchema(void 0, { positive: true }),
|
|
449
|
+
scope: z.enum(FREE_SCOPES)
|
|
450
|
+
});
|
|
451
|
+
/**
|
|
452
|
+
* This schema accepts a meter. The first tier starts at zero, and the starts increase. The prices of the tiers and
|
|
453
|
+
* the free amount measure one metered amount.
|
|
454
|
+
*/
|
|
455
|
+
const meterSchema = z.strictObject({
|
|
456
|
+
name: textSchema,
|
|
457
|
+
tiers: z.array(tierSchema).min(1),
|
|
458
|
+
free: freeAmountSchema.optional()
|
|
459
|
+
}).superRefine((meter, context) => {
|
|
460
|
+
const [first] = meter.tiers;
|
|
461
|
+
if (first === void 0) return;
|
|
462
|
+
const parts = readPriceUnit(first.unitPrice.unit);
|
|
463
|
+
if (typeof parts === "string") return;
|
|
464
|
+
let units = true;
|
|
465
|
+
for (const [index, tier] of meter.tiers.entries()) {
|
|
466
|
+
if (converts(tier.unitPrice.unit, first.unitPrice.unit) && measures(tier.from.unit, first.unitPrice.unit, parts.money)) continue;
|
|
467
|
+
units = false;
|
|
468
|
+
context.addIssue({
|
|
469
|
+
code: "custom",
|
|
470
|
+
message: `The tier ${index} does not measure the metered amount of the price ${first.unitPrice.unit}.`,
|
|
471
|
+
path: ["tiers", index]
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
if (meter.free !== void 0 && !measures(meter.free.amount.unit, first.unitPrice.unit, parts.money)) context.addIssue({
|
|
475
|
+
code: "custom",
|
|
476
|
+
message: `The free amount ${meter.free.amount.unit} does not measure the metered amount of the price ${first.unitPrice.unit}.`,
|
|
477
|
+
path: ["free", "amount"]
|
|
478
|
+
});
|
|
479
|
+
if (!units) return;
|
|
480
|
+
const starts = startsOf(meter.tiers, first.from.unit);
|
|
481
|
+
if (starts === void 0) return;
|
|
482
|
+
if (rationals.sign(starts[0] ?? rationals.ZERO) !== 0) context.addIssue({
|
|
483
|
+
code: "custom",
|
|
484
|
+
message: "The first tier does not start at zero.",
|
|
485
|
+
path: [
|
|
486
|
+
"tiers",
|
|
487
|
+
0,
|
|
488
|
+
"from"
|
|
489
|
+
]
|
|
490
|
+
});
|
|
491
|
+
for (let index = 1; index < starts.length; index += 1) {
|
|
492
|
+
if (rationals.cmp(starts[index] ?? rationals.ZERO, starts[index - 1] ?? rationals.ZERO) > 0) continue;
|
|
493
|
+
context.addIssue({
|
|
494
|
+
code: "custom",
|
|
495
|
+
message: `The tier ${index} does not start after the tier ${index - 1}.`,
|
|
496
|
+
path: [
|
|
497
|
+
"tiers",
|
|
498
|
+
index,
|
|
499
|
+
"from"
|
|
500
|
+
]
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
});
|
|
504
|
+
/**
|
|
505
|
+
* This schema accepts a metered reading: the metered prices of one offer at one instant. The tiers and the free
|
|
506
|
+
* amounts count the usage of one `period`. Each meter has its own name.
|
|
507
|
+
*/
|
|
508
|
+
const meteredReadingSchema = z.strictObject({
|
|
509
|
+
offerId: textSchema,
|
|
510
|
+
at: instantSchema,
|
|
511
|
+
period: quantitySchema("time", { positive: true }),
|
|
512
|
+
meters: z.array(meterSchema).min(1),
|
|
513
|
+
upfront: moneySchema.optional()
|
|
514
|
+
}).refine((reading) => new Set(reading.meters.map((meter) => meter.name)).size === reading.meters.length, {
|
|
515
|
+
message: "The reading has two meters with one name.",
|
|
516
|
+
path: ["meters"]
|
|
517
|
+
});
|
|
518
|
+
/** This schema accepts a metered observation: an offer, and a reading of that offer. Only a committed term has upfront money. */
|
|
519
|
+
const meteredObservationSchema = z.strictObject({
|
|
520
|
+
offer: meteredOfferSchema,
|
|
521
|
+
reading: meteredReadingSchema
|
|
522
|
+
}).superRefine((each, context) => {
|
|
523
|
+
if (each.reading.offerId !== each.offer.id) context.addIssue({
|
|
524
|
+
code: "custom",
|
|
525
|
+
message: "The reading is not a reading of the offer.",
|
|
526
|
+
path: ["reading", "offerId"]
|
|
527
|
+
});
|
|
528
|
+
if (each.reading.upfront !== void 0 && each.offer.term.kind !== "committed") context.addIssue({
|
|
529
|
+
code: "custom",
|
|
530
|
+
message: `The term ${each.offer.term.kind} has no upfront money.`,
|
|
531
|
+
path: ["reading", "upfront"]
|
|
532
|
+
});
|
|
533
|
+
});
|
|
534
|
+
/** This function gives the value of an amount in a unit, as an exact rational. */
|
|
535
|
+
function exactIn(amount, unit) {
|
|
536
|
+
return convertExact(rationals.fromNumber(amount.value), amount.unit, unit);
|
|
537
|
+
}
|
|
538
|
+
/** This function gives the larger of two rationals. */
|
|
539
|
+
function larger(a, b) {
|
|
540
|
+
return rationals.cmp(a, b) >= 0 ? a : b;
|
|
541
|
+
}
|
|
542
|
+
/** This function gives the smaller of two rationals. */
|
|
543
|
+
function smaller(a, b) {
|
|
544
|
+
return rationals.cmp(a, b) <= 0 ? a : b;
|
|
545
|
+
}
|
|
546
|
+
/** This function examines an amount of usage of a meter, and gives its value in its own unit. */
|
|
547
|
+
function usageValue(meter, amount, priceUnit, money, what) {
|
|
548
|
+
if (!Number.isFinite(amount.value) || amount.value < 0) throw new RangeError(`The ${what} of the meter ${meter.name} is ${amount.value}, not an amount of zero or more.`);
|
|
549
|
+
if (!measures(amount.unit, priceUnit, money)) throw new RangeError(`The ${what} of the meter ${meter.name} is in ${amount.unit}, which does not measure the price ${priceUnit}.`);
|
|
550
|
+
return rationals.fromNumber(amount.value);
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* This function gives the exact cost of the usage of one meter, in the unit of money of its first tier. The free
|
|
554
|
+
* amount comes off the usage first. The tiers then count the rest of the usage from zero.
|
|
555
|
+
*/
|
|
556
|
+
function costOfMeter(meter, used, freeUsed) {
|
|
557
|
+
const [first] = meter.tiers;
|
|
558
|
+
if (first === void 0) throw new RangeError(`The meter ${meter.name} has no tier.`);
|
|
559
|
+
const parts = readPriceUnit(first.unitPrice.unit);
|
|
560
|
+
if (typeof parts === "string") throw new RangeError(parts);
|
|
561
|
+
const { money } = parts;
|
|
562
|
+
if (used === void 0) return {
|
|
563
|
+
money,
|
|
564
|
+
cost: rationals.ZERO
|
|
565
|
+
};
|
|
566
|
+
const amount = usageValue(meter, used, first.unitPrice.unit, money, "usage");
|
|
567
|
+
const unit = used.unit;
|
|
568
|
+
const perUnit = priceUnitFor(money, unit);
|
|
569
|
+
if (perUnit === void 0) throw new RangeError(`The usage of the meter ${meter.name} is in ${unit}, which has no price unit.`);
|
|
570
|
+
let free = rationals.ZERO;
|
|
571
|
+
if (meter.free !== void 0) free = exactIn(meter.free.amount, unit);
|
|
572
|
+
if (freeUsed !== void 0) {
|
|
573
|
+
usageValue(meter, freeUsed, first.unitPrice.unit, money, "used free amount");
|
|
574
|
+
free = larger(rationals.ZERO, rationals.sub(free, exactIn(freeUsed, unit)));
|
|
575
|
+
}
|
|
576
|
+
const billed = larger(rationals.ZERO, rationals.sub(amount, free));
|
|
577
|
+
let cost = rationals.ZERO;
|
|
578
|
+
for (const [index, tier] of meter.tiers.entries()) {
|
|
579
|
+
const start = exactIn(tier.from, unit);
|
|
580
|
+
const next = meter.tiers[index + 1];
|
|
581
|
+
const end = next === void 0 ? billed : smaller(billed, exactIn(next.from, unit));
|
|
582
|
+
if (rationals.cmp(end, start) <= 0) continue;
|
|
583
|
+
cost = rationals.add(cost, rationals.mul(rationals.sub(end, start), exactIn(tier.unitPrice, perUnit)));
|
|
584
|
+
}
|
|
585
|
+
return {
|
|
586
|
+
money,
|
|
587
|
+
cost
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* This function gives the cost of a metered offer for one period, from the usage of each meter in that period. A
|
|
592
|
+
* meter with no usage costs zero. The free amount of a meter comes off its usage first, less `freeUsed`. The tiers
|
|
593
|
+
* then count the rest of the usage from zero. A committed term adds its upfront money times the period over the length.
|
|
594
|
+
*
|
|
595
|
+
* The arithmetic is exact, and the function does not round the cost to the cent. Each value is the nearest number to
|
|
596
|
+
* the exact cost. The function converts the units with the exact factors of `@mark1russell7/quantity`.
|
|
597
|
+
*
|
|
598
|
+
* @throws RangeError when the usage names a meter that the reading does not have. It also throws when an amount
|
|
599
|
+
* of usage is negative, or does not measure the metered amount of its meter.
|
|
600
|
+
*/
|
|
601
|
+
function meteredCost(observation, usage, options = {}) {
|
|
602
|
+
const { offer, reading } = observation;
|
|
603
|
+
const { freeUsed = {} } = options;
|
|
604
|
+
const names = new Set(reading.meters.map((meter) => meter.name));
|
|
605
|
+
for (const name of [...Object.keys(usage), ...Object.keys(freeUsed)]) if (!names.has(name)) throw new RangeError(`The reading of ${reading.offerId} has no meter ${name}.`);
|
|
606
|
+
const at = (record, name) => Object.hasOwn(record, name) ? record[name] : void 0;
|
|
607
|
+
const costs = reading.meters.map((meter) => ({
|
|
608
|
+
name: meter.name,
|
|
609
|
+
...costOfMeter(meter, at(usage, meter.name), at(freeUsed, meter.name))
|
|
610
|
+
}));
|
|
611
|
+
const unit = costs[0]?.money;
|
|
612
|
+
if (unit === void 0) throw new RangeError(`The reading of ${reading.offerId} has no meter.`);
|
|
613
|
+
let total = rationals.ZERO;
|
|
614
|
+
for (const each of costs) total = rationals.add(total, convertExact(each.cost, each.money, unit));
|
|
615
|
+
const meters = costs.map((each) => ({
|
|
616
|
+
name: each.name,
|
|
617
|
+
cost: quantity(rationals.toNumber(each.cost), each.money)
|
|
618
|
+
}));
|
|
619
|
+
let upfront = rationals.ZERO;
|
|
620
|
+
if (offer.term.kind === "committed" && reading.upfront !== void 0) {
|
|
621
|
+
const { length } = offer.term;
|
|
622
|
+
const share = rationals.div(exactIn(reading.period, length.unit), rationals.fromNumber(length.value));
|
|
623
|
+
upfront = rationals.mul(exactIn(reading.upfront, unit), share);
|
|
624
|
+
}
|
|
625
|
+
total = rationals.add(total, upfront);
|
|
626
|
+
return {
|
|
627
|
+
meters,
|
|
628
|
+
upfront: quantity(rationals.toNumber(upfront), unit),
|
|
629
|
+
total: quantity(rationals.toNumber(total), unit)
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
export { AVAILABILITIES, BOARD_FORMAT, CONDITIONS, FORMATS, FREE_SCOPES, METERED_KINDS, bestOffer, boardObservations, boardReadSchema, boardSchema, costOf, foldCode, freeAmountSchema, gtinCheckDigit, gtinSchema, instantSchema, isKept, keepObservations, keepUntil, lastReads, latestObservations, locationSchema, matchKeys, meterSchema, meteredCost, meteredKindOf, meteredObservationSchema, meteredOfferSchema, meteredPriceSchema, meteredReadingSchema, moneySchema, observationSchema, offerId, offerSchema, offersOfPart, offersPart, parseGtin, partNumberSchema, permitsHistory, permitsTrend, planReads, priceBreakSchema, priceReadingSchema, priceTermSchema, productSchema, readInterval, retentionSchema, sellerSchema, settleBoard, shippingSchema, sourceOfOffer, sourceSchema, sourceTermsSchema, specSchema, textSchema, tierSchema, unitPriceFor, watchEntrySchema, watchProblems };
|
|
288
633
|
|
|
289
634
|
//# sourceMappingURL=index.js.map
|