@mark1russell7/market 0.1.7 → 0.1.9
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 +22 -0
- package/build/average-B29bynFb.js +106 -0
- package/build/average-B29bynFb.js.map +1 -0
- package/build/average-Bj0GkSLo.d.ts +40 -0
- package/build/average-Bj0GkSLo.d.ts.map +1 -0
- package/build/index.d.ts +3 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js +4 -2
- package/build/index.js.map +1 -1
- package/build/{records-DU5uvTYJ.js → offers-h_HvMkH_.js} +3 -186
- package/build/offers-h_HvMkH_.js.map +1 -0
- package/build/plan.js +2 -1
- package/build/plan.js.map +1 -1
- package/build/records-W6sPyhTQ.js +187 -0
- package/build/records-W6sPyhTQ.js.map +1 -0
- package/build/supplies-entry.d.ts +132 -2
- package/build/supplies-entry.d.ts.map +1 -1
- package/build/supplies-entry.js +215 -2
- package/build/supplies-entry.js.map +1 -1
- package/package.json +1 -1
- package/build/records-DU5uvTYJ.js.map +0 -1
|
@@ -1,41 +1,5 @@
|
|
|
1
|
+
import { b as parseGtin } from "./records-W6sPyhTQ.js";
|
|
1
2
|
import { UnitError, add, compare, convert, convertible, kindOf, scale } from "@mark1russell7/quantity";
|
|
2
|
-
import { quantitySchema } from "@mark1russell7/quantity/schema";
|
|
3
|
-
import { z } from "zod";
|
|
4
|
-
// src/gtin.ts
|
|
5
|
-
/**
|
|
6
|
-
* This module reads the GTIN of a product: a GTIN-8, a UPC-A (12 digits), an EAN-13 or a GTIN-14.
|
|
7
|
-
* The last digit is a check digit. The sum of the other digits, with the weights 3 and 1 from the right, gives it.
|
|
8
|
-
*/
|
|
9
|
-
const LENGTHS = /* @__PURE__ */ new Set([
|
|
10
|
-
8,
|
|
11
|
-
12,
|
|
12
|
-
13,
|
|
13
|
-
14
|
|
14
|
-
]);
|
|
15
|
-
/**
|
|
16
|
-
* This function gives the check digit of the digits of a GTIN without its last digit.
|
|
17
|
-
*
|
|
18
|
-
* @throws RangeError when the text has a character that is not a digit, or no character.
|
|
19
|
-
*/
|
|
20
|
-
function gtinCheckDigit(body) {
|
|
21
|
-
if (!/^\d+$/.test(body)) throw new RangeError(`The text ${JSON.stringify(body)} is not a string of digits.`);
|
|
22
|
-
let total = 0;
|
|
23
|
-
for (let i = 0; i < body.length; i += 1) {
|
|
24
|
-
const digit = body.charCodeAt(body.length - 1 - i) - 48;
|
|
25
|
-
total += i % 2 === 0 ? digit * 3 : digit;
|
|
26
|
-
}
|
|
27
|
-
return (10 - total % 10) % 10;
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* This function gives the GTIN-14 form of a GTIN, or null. It removes the spaces and the hyphens first.
|
|
31
|
-
* It refuses a length other than 8, 12, 13 or 14 digits, a wrong check digit, and a GTIN of zeros only.
|
|
32
|
-
*/
|
|
33
|
-
function parseGtin(text) {
|
|
34
|
-
const digits = text.replace(/[\s-]/g, "");
|
|
35
|
-
if (!/^\d+$/.test(digits) || !LENGTHS.has(digits.length) || /^0+$/.test(digits)) return null;
|
|
36
|
-
if (gtinCheckDigit(digits.slice(0, -1)) !== Number(digits.slice(-1))) return null;
|
|
37
|
-
return digits.padStart(14, "0");
|
|
38
|
-
}
|
|
39
3
|
// src/identifiers.ts
|
|
40
4
|
/**
|
|
41
5
|
* This function folds a brand or a part number for a comparison. The result has only capital letters A to Z
|
|
@@ -227,153 +191,6 @@ function priceOf(observations, count, need) {
|
|
|
227
191
|
why: first === void 0 ? "No offer matches the part." : `No offer is usable. The first offer that the choice skipped: ${first.why}`
|
|
228
192
|
};
|
|
229
193
|
}
|
|
230
|
-
|
|
231
|
-
/**
|
|
232
|
-
* The conditions of an offer. A source maps its own condition to one of them, and it keeps its own text in
|
|
233
|
-
* the field `grade` of the offer.
|
|
234
|
-
*/
|
|
235
|
-
const CONDITIONS = [
|
|
236
|
-
"new",
|
|
237
|
-
"open-box",
|
|
238
|
-
"refurbished",
|
|
239
|
-
"used",
|
|
240
|
-
"for-parts",
|
|
241
|
-
"unknown"
|
|
242
|
-
];
|
|
243
|
-
/** The states of the stock of an offer at the time of a reading. */
|
|
244
|
-
const AVAILABILITIES = [
|
|
245
|
-
"in-stock",
|
|
246
|
-
"low-stock",
|
|
247
|
-
"out-of-stock",
|
|
248
|
-
"preorder",
|
|
249
|
-
"unknown"
|
|
250
|
-
];
|
|
251
|
-
/** The buying formats of an offer. In an auction, the price of a reading is the current bid. */
|
|
252
|
-
const FORMATS = ["fixed-price", "auction"];
|
|
253
|
-
/** This schema accepts a text with a character that is not a space, and with no space at an end. */
|
|
254
|
-
const textSchema = z.string().refine((text) => text !== "" && text === text.trim(), "The text is empty, or it has a space at an end.");
|
|
255
|
-
/** This schema accepts the name of a source: small letters, digits and hyphens, with a letter first. */
|
|
256
|
-
const sourceSchema = z.string().regex(/^[a-z][a-z0-9-]*$/, "The name of a source has small letters, digits and hyphens, with a letter first.");
|
|
257
|
-
/** This schema accepts a GTIN in its GTIN-14 form, with a correct check digit. `parseGtin` gives this form. */
|
|
258
|
-
const gtinSchema = z.string().refine((text) => /^\d{14}$/.test(text) && parseGtin(text) === text, "The GTIN is not a GTIN-14 with a correct check digit.");
|
|
259
|
-
/** This schema accepts an amount of money of zero or more, for example `{ "value": 129.99, "unit": "USD" }`. */
|
|
260
|
-
const moneySchema = quantitySchema("money", { nonnegative: true });
|
|
261
|
-
/** This schema accepts an instant in UTC in the ISO 8601 form, for example `2026-11-12T18:00:00Z`. */
|
|
262
|
-
const instantSchema = z.iso.datetime();
|
|
263
|
-
/** This schema accepts a part number of a maker. */
|
|
264
|
-
const partNumberSchema = z.strictObject({
|
|
265
|
-
brand: textSchema,
|
|
266
|
-
partNumber: textSchema
|
|
267
|
-
});
|
|
268
|
-
/** This schema accepts one specification as text, for example `{ "name": "Capacity", "value": "1 TB" }`. */
|
|
269
|
-
const specSchema = z.strictObject({
|
|
270
|
-
name: textSchema,
|
|
271
|
-
value: textSchema
|
|
272
|
-
});
|
|
273
|
-
/** This schema accepts a seller. A rating is the percent of good feedback and the count of the feedback. */
|
|
274
|
-
const sellerSchema = z.strictObject({
|
|
275
|
-
id: textSchema.optional(),
|
|
276
|
-
name: textSchema.optional(),
|
|
277
|
-
rating: z.strictObject({
|
|
278
|
-
percent: z.number().min(0).max(100),
|
|
279
|
-
count: z.int().nonnegative()
|
|
280
|
-
}).optional()
|
|
281
|
-
});
|
|
282
|
-
/** This schema accepts a product: one thing that a person can buy, with its identifiers and its specifications. */
|
|
283
|
-
const productSchema = z.strictObject({
|
|
284
|
-
id: textSchema,
|
|
285
|
-
title: textSchema,
|
|
286
|
-
brand: textSchema.optional(),
|
|
287
|
-
category: z.array(textSchema).optional(),
|
|
288
|
-
gtins: z.array(gtinSchema),
|
|
289
|
-
partNumbers: z.array(partNumberSchema),
|
|
290
|
-
specs: z.array(specSchema)
|
|
291
|
-
});
|
|
292
|
-
/** This function gives the id of an offer: the name of its source, a colon, and the id at the source. */
|
|
293
|
-
function offerId(source, sourceId) {
|
|
294
|
-
return `${source}:${sourceId}`;
|
|
295
|
-
}
|
|
296
|
-
/** This function gives the name of the source of an offer id: the text before the first colon. */
|
|
297
|
-
function sourceOfOffer(id) {
|
|
298
|
-
const colon = id.indexOf(":");
|
|
299
|
-
if (colon <= 0) throw new RangeError(`The offer id ${JSON.stringify(id)} has no source.`);
|
|
300
|
-
return id.slice(0, colon);
|
|
301
|
-
}
|
|
302
|
-
/**
|
|
303
|
-
* This schema accepts an offer: one product at one seller. The offer has the identifiers that the source gives.
|
|
304
|
-
* `productId` names the product of the catalog after a match.
|
|
305
|
-
*/
|
|
306
|
-
const offerSchema = z.strictObject({
|
|
307
|
-
id: textSchema,
|
|
308
|
-
source: sourceSchema,
|
|
309
|
-
sourceId: textSchema,
|
|
310
|
-
productId: textSchema.optional(),
|
|
311
|
-
title: textSchema,
|
|
312
|
-
url: z.url({ protocol: /^https$/ }).optional(),
|
|
313
|
-
seller: sellerSchema,
|
|
314
|
-
condition: z.enum(CONDITIONS),
|
|
315
|
-
grade: textSchema.optional(),
|
|
316
|
-
format: z.enum(FORMATS),
|
|
317
|
-
endsAt: instantSchema.optional(),
|
|
318
|
-
gtins: z.array(gtinSchema),
|
|
319
|
-
partNumbers: z.array(partNumberSchema),
|
|
320
|
-
specs: z.array(specSchema)
|
|
321
|
-
}).refine((offer) => offer.id === offerId(offer.source, offer.sourceId), {
|
|
322
|
-
message: "The id of an offer is its source and its source id, with a colon between them.",
|
|
323
|
-
path: ["id"]
|
|
324
|
-
});
|
|
325
|
-
/** This schema accepts the shipping of a reading. A calculated cost depends on the address of the buyer. */
|
|
326
|
-
const shippingSchema = z.discriminatedUnion("kind", [
|
|
327
|
-
z.strictObject({ kind: z.literal("free") }),
|
|
328
|
-
z.strictObject({
|
|
329
|
-
kind: z.literal("fixed"),
|
|
330
|
-
cost: moneySchema
|
|
331
|
-
}),
|
|
332
|
-
z.strictObject({ kind: z.literal("calculated") }),
|
|
333
|
-
z.strictObject({ kind: z.literal("unknown") })
|
|
334
|
-
]);
|
|
335
|
-
/** This schema accepts a price break: the unit price for an order of `quantity` units or more. */
|
|
336
|
-
const priceBreakSchema = z.strictObject({
|
|
337
|
-
quantity: z.int().min(2),
|
|
338
|
-
unitPrice: moneySchema
|
|
339
|
-
});
|
|
340
|
-
/**
|
|
341
|
-
* This schema accepts a price reading: the state of one offer at one instant. `price` is the unit price for an
|
|
342
|
-
* order of `minimumQuantity` units, or of one unit. The quantities of the breaks increase, and each is more
|
|
343
|
-
* than the minimum.
|
|
344
|
-
*/
|
|
345
|
-
const priceReadingSchema = z.strictObject({
|
|
346
|
-
offerId: textSchema,
|
|
347
|
-
at: instantSchema,
|
|
348
|
-
price: moneySchema,
|
|
349
|
-
listPrice: moneySchema.optional(),
|
|
350
|
-
shipping: shippingSchema,
|
|
351
|
-
availability: z.enum(AVAILABILITIES),
|
|
352
|
-
available: z.int().nonnegative().optional(),
|
|
353
|
-
minimumQuantity: z.int().min(1).optional(),
|
|
354
|
-
priceBreaks: z.array(priceBreakSchema).optional()
|
|
355
|
-
}).superRefine((reading, context) => {
|
|
356
|
-
let last = reading.minimumQuantity ?? 1;
|
|
357
|
-
for (const [index, entry] of (reading.priceBreaks ?? []).entries()) {
|
|
358
|
-
if (entry.quantity <= last) context.addIssue({
|
|
359
|
-
code: "custom",
|
|
360
|
-
message: `The break ${index} has the quantity ${entry.quantity}, which is not more than ${last}.`,
|
|
361
|
-
path: [
|
|
362
|
-
"priceBreaks",
|
|
363
|
-
index,
|
|
364
|
-
"quantity"
|
|
365
|
-
]
|
|
366
|
-
});
|
|
367
|
-
last = Math.max(last, entry.quantity);
|
|
368
|
-
}
|
|
369
|
-
const { availability, available } = reading;
|
|
370
|
-
if (available === void 0 || availability === "unknown" || availability === "preorder") return;
|
|
371
|
-
if (availability === "out-of-stock" !== (available === 0)) context.addIssue({
|
|
372
|
-
code: "custom",
|
|
373
|
-
message: `The availability ${availability} does not agree with the count ${available}.`,
|
|
374
|
-
path: ["available"]
|
|
375
|
-
});
|
|
376
|
-
});
|
|
377
|
-
export { priceOf as C, matchKeys as D, foldCode as E, gtinCheckDigit as O, offersPart as S, unitPriceFor as T, specSchema as _, instantSchema as a, latestObservations as b, offerSchema as c, priceReadingSchema as d, productSchema as f, sourceSchema as g, sourceOfOffer as h, gtinSchema as i, parseGtin as k, partNumberSchema as l, shippingSchema as m, CONDITIONS as n, moneySchema as o, sellerSchema as p, FORMATS as r, offerId as s, AVAILABILITIES as t, priceBreakSchema as u, textSchema as v, costOf as w, offersOfPart as x, bestOffer as y };
|
|
194
|
+
export { priceOf as a, foldCode as c, offersPart as i, matchKeys as l, latestObservations as n, costOf as o, offersOfPart as r, unitPriceFor as s, bestOffer as t };
|
|
378
195
|
|
|
379
|
-
//# sourceMappingURL=
|
|
196
|
+
//# sourceMappingURL=offers-h_HvMkH_.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"offers-h_HvMkH_.js","names":[],"sources":["../src/identifiers.ts","../src/price.ts","../src/offers.ts"],"sourcesContent":["import { parseGtin } from \"./gtin.ts\";\n\n/** A part number of a maker: the brand, and the number that the maker gives to the part. */\nexport interface PartNumber {\n readonly brand: string;\n readonly partNumber: string;\n}\n\n/** The identifiers of a product or of an offer. */\nexport interface Identifiers {\n readonly gtins: readonly string[];\n readonly partNumbers: readonly PartNumber[];\n}\n\n/**\n * This function folds a brand or a part number for a comparison. The result has only capital letters A to Z\n * and digits. Thus `MZ-V8V1T0B/AM` and `mzv8v1t0bam` fold to one text.\n */\nexport function foldCode(text: string): string {\n return text.normalize(\"NFKD\").toUpperCase().replace(/[^A-Z0-9]/g, \"\");\n}\n\n/**\n * This function gives the match keys of a record, sorted and with no copy. A key is `gtin:` with the GTIN-14,\n * or `part:` with the folded brand and part number. Two records with a key in common name one product.\n * The function ignores a GTIN that is not valid, and a part number whose brand or number folds to no text.\n */\nexport function matchKeys(identifiers: Identifiers): string[] {\n const keys = new Set<string>();\n for (const text of identifiers.gtins) {\n const gtin = parseGtin(text);\n if (gtin !== null) keys.add(`gtin:${gtin}`);\n }\n for (const { brand, partNumber } of identifiers.partNumbers) {\n const folded = [foldCode(brand), foldCode(partNumber)];\n if (folded.every((part) => part !== \"\")) keys.add(`part:${folded.join(\"/\")}`);\n }\n return [...keys].sort();\n}\n","import { add, scale, type Quantity } from \"@mark1russell7/quantity\";\nimport type { PriceReading } from \"./records.ts\";\n\n/**\n * This function gives the unit price for an order of `count` units. The price of the largest break at or\n * below the count applies, or the price of the reading when no break applies.\n *\n * @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.\n */\nexport function unitPriceFor(reading: PriceReading, count: number): Quantity {\n const minimum = reading.minimumQuantity ?? 1;\n if (!Number.isSafeInteger(count) || count < minimum) {\n throw new RangeError(`The count ${count} is not a whole number of ${minimum} or more.`);\n }\n let price: Quantity = reading.price;\n for (const entry of reading.priceBreaks ?? []) if (entry.quantity <= count) price = entry.unitPrice;\n return price;\n}\n\n/**\n * This function gives the cost of an order of `count` units with its shipping, or null when the shipping\n * cost is not known. The cost is exact, and the function does not round it to the cent.\n *\n * @throws RangeError when the count is not a whole number, or when it is less than the minimum of the reading.\n */\nexport function costOf(reading: PriceReading, count: number): Quantity | null {\n const goods = scale(unitPriceFor(reading, count), count);\n switch (reading.shipping.kind) {\n case \"free\":\n return goods;\n case \"fixed\":\n return add(goods, reading.shipping.cost);\n default:\n return null;\n }\n}\n","import { compare, convert, convertible, kindOf, scale, UnitError, type Quantity } from \"@mark1russell7/quantity\";\nimport { foldCode } from \"./identifiers.ts\";\nimport { costOf, unitPriceFor } from \"./price.ts\";\nimport type { Condition, Offer, PriceReading } from \"./records.ts\";\n\n/** One offer of a source, and its price reading at one instant. */\nexport interface Observation {\n readonly offer: Offer;\n readonly reading: PriceReading;\n}\n\n/**\n * This record names a part that a buyer wants: the names of its maker, and its part numbers. A seller can write\n * the brand of one maker in more than one form, so the want has a list of names.\n */\nexport interface PartWant {\n /** The names of the maker, as the sellers write the brand. */\n readonly brands: readonly string[];\n /** The part numbers of the maker. A part number of an offer matches when it starts with one of them, after the fold. */\n readonly partNumbers: readonly string[];\n}\n\n/**\n * This function tells if an offer is an offer of the part. One part number of the offer must have a brand of the\n * want and start with a part number of the want. `foldCode` folds each text before the comparison. A part number\n * of another maker does not match: many makers use short numbers like `A1383`.\n */\nexport function offersPart(offer: Pick<Offer, \"partNumbers\">, want: PartWant): boolean {\n const brands = new Set(want.brands.map(foldCode).filter((brand) => brand !== \"\"));\n const parts = want.partNumbers.map(foldCode).filter((part) => part !== \"\");\n return offer.partNumbers.some(({ brand, partNumber }) => {\n const folded = foldCode(partNumber);\n return brands.has(foldCode(brand)) && parts.some((part) => folded.startsWith(part));\n });\n}\n\n/**\n * This function gives the latest observation of each offer, in the order of the offer ids. When two readings of\n * one offer have the same instant, the later one in the list applies.\n */\nexport function latestObservations(observations: readonly Observation[]): Observation[] {\n const latest = new Map<string, Observation>();\n for (const each of observations) {\n const seen = latest.get(each.offer.id);\n if (seen === undefined || Date.parse(seen.reading.at) <= Date.parse(each.reading.at)) latest.set(each.offer.id, each);\n }\n return [...latest.values()].sort((a, b) => order(a.offer.id, b.offer.id));\n}\n\n/** This function gives the latest observation of each offer of the part, in the order of the offer ids. */\nexport function offersOfPart(observations: readonly Observation[], want: PartWant): Observation[] {\n return latestObservations(observations.filter((each) => offersPart(each.offer, want)));\n}\n\n/** This record is one offer that a buyer can choose, with the price of an order in the currency of the buyer. */\nexport interface OfferChoice {\n readonly observation: Observation;\n /** The unit price for the count, times the count. */\n readonly goods: Quantity;\n /** The goods and the shipping, or null when the shipping cost is not known. */\n readonly cost: Quantity | null;\n /** True when the availability is `in-stock` or `low-stock`. */\n readonly inStock: boolean;\n}\n\n/** These options change the choice of an offer. */\nexport interface BestOfferOptions {\n /** The currency of the prices, a unit of money of `@mark1russell7/quantity`, for example `USD`. An offer with a price in another currency is skipped. */\n readonly currency: string;\n /** The count of units of the order. The default is 1. */\n readonly count?: number;\n /** The conditions that the buyer accepts. The default is `new` only. */\n readonly conditions?: readonly Condition[];\n}\n\n/** This record is the choice of an offer: the best offer, each offer in the order of the price, and each skipped offer. */\nexport interface BestOffer {\n /** The offer with the lowest price that is in stock, or else the offer with the lowest price, or null with no offer. */\n readonly best: OfferChoice | null;\n /** The offers, from the lowest price of the goods. Equal prices go in the order of the cost, then of the offer id. */\n readonly offers: readonly OfferChoice[];\n /** The offers that the choice skipped, each with the reason. */\n readonly skipped: readonly { readonly offerId: string; readonly why: string }[];\n}\n\n/**\n * This function chooses the offer to buy from the latest observation of each offer. It skips an offer with a\n * condition that the buyer does not accept, a price in another currency, or a minimum above the count.\n *\n * @throws RangeError when the count is not a whole number of 1 or more, or when the currency is not a unit of money.\n */\nexport function bestOffer(observations: readonly Observation[], options: BestOfferOptions): BestOffer {\n const { currency, count = 1, conditions = [\"new\"] } = options;\n if (!Number.isSafeInteger(count) || count < 1) throw new RangeError(`The count ${count} is not a whole number of 1 or more.`);\n if (!isMoney(currency)) throw new RangeError(`The currency ${currency} is not a unit of money of @mark1russell7/quantity.`);\n const accepted = new Set<Condition>(conditions);\n const offers: OfferChoice[] = [];\n const skipped: { offerId: string; why: string }[] = [];\n for (const observation of latestObservations(observations)) {\n const { offer, reading } = observation;\n const minimum = reading.minimumQuantity ?? 1;\n if (!accepted.has(offer.condition)) skipped.push({ offerId: offer.id, why: `The condition ${offer.condition} is not a condition that the buyer accepts.` });\n else if (!converts(reading.price.unit, currency)) skipped.push({ offerId: offer.id, why: `The price is in ${reading.price.unit}, not in ${currency}.` });\n else if (count < minimum) skipped.push({ offerId: offer.id, why: `The minimum order is ${minimum} units, more than the count ${count}.` });\n else {\n const goods = convert(scale(unitPriceFor(reading, count), count), currency);\n // A shipping cost in another currency is not known in the currency of the buyer.\n const shipping = reading.shipping.kind !== \"fixed\" || converts(reading.shipping.cost.unit, currency);\n const total = shipping ? costOf(reading, count) : null;\n const cost = total === null ? null : convert(total, currency);\n const inStock = reading.availability === \"in-stock\" || reading.availability === \"low-stock\";\n offers.push({ observation, goods, cost, inStock });\n }\n }\n offers.sort((a, b) => compare(a.goods, b.goods) || byCost(a.cost, b.cost) || order(a.observation.offer.id, b.observation.offer.id));\n const best = offers.find((choice) => choice.inStock) ?? offers[0] ?? null;\n return { best, offers, skipped };\n}\n\n/** This function tells if a unit is a unit of money that the quantity package knows. */\nfunction isMoney(unit: string): boolean {\n try {\n return kindOf(unit) === \"money\";\n } catch (error) {\n if (error instanceof UnitError) return false;\n throw error;\n }\n}\n\n/** 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. */\nfunction converts(from: string, to: string): boolean {\n try {\n return convertible(from, to);\n } catch (error) {\n if (error instanceof UnitError) return false;\n throw error;\n }\n}\n\n/** This function orders two costs. A known cost comes before a cost that is not known. */\nfunction byCost(a: Quantity | null, b: Quantity | null): number {\n if (a === null || b === null) return a === b ? 0 : a === null ? 1 : -1;\n return compare(a, b);\n}\n\n/** This function orders two texts by their code units, so the order does not depend on the locale. */\nfunction order(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** The offer to buy for one count of a part, or the reason that no offer is usable. */\nexport type Priced = { readonly ok: true; readonly offerId: string; readonly cost: Quantity } | { readonly ok: false; readonly why: string };\n\n/**\n * This function chooses the offer to buy for a count of a part: the in-stock offer with the lowest cost, with the\n * shipping. An offer with a cost that is not known is not usable. Equal costs keep the order of `bestOffer`.\n */\nexport function priceOf(observations: readonly Observation[], count: number, need: { readonly currency: string; readonly conditions?: readonly Condition[] | undefined }): Priced {\n const choice = bestOffer(observations, { currency: need.currency, count, ...(need.conditions === undefined ? {} : { conditions: need.conditions }) });\n let pick: (OfferChoice & { readonly cost: Quantity }) | undefined;\n for (const offer of choice.offers) {\n const cost = offer.cost;\n if (offer.inStock && cost !== null && (pick === undefined || compare(cost, pick.cost) < 0)) pick = { ...offer, cost };\n }\n if (pick !== undefined) return { ok: true, offerId: pick.observation.offer.id, cost: pick.cost };\n if (choice.offers.length > 0) return { ok: false, why: `No offer of ${String(count)} units is in stock with a known cost.` };\n const first = choice.skipped[0];\n return { ok: false, why: first === undefined ? \"No offer matches the part.\" : `No offer is usable. The first offer that the choice skipped: ${first.why}` };\n}\n"],"mappings":";;;;;;;AAkBA,SAAgB,SAAS,MAAsB;CAC7C,OAAO,KAAK,UAAU,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC,QAAQ,cAAc,EAAE;AACtE;;;;;;AAOA,SAAgB,UAAU,aAAoC;CAC5D,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,QAAQ,YAAY,OAAO;EACpC,MAAM,OAAO,UAAU,IAAI;EAC3B,IAAI,SAAS,MAAM,KAAK,IAAI,QAAQ,MAAM;CAC5C;CACA,KAAK,MAAM,EAAE,OAAO,gBAAgB,YAAY,aAAa;EAC3D,MAAM,SAAS,CAAC,SAAS,KAAK,GAAG,SAAS,UAAU,CAAC;EACrD,IAAI,OAAO,OAAO,SAAS,SAAS,EAAE,GAAG,KAAK,IAAI,QAAQ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AAU,KAAK;EAAU;EAAO,GAAI,KAAK,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,KAAK,WAAW;CAAG,CAAC;CACpJ,IAAI;CACJ,KAAK,MAAM,SAAS,OAAO,QAAQ;EACjC,MAAM,OAAO,MAAM;EACnB,IAAI,MAAM,WAAW,SAAS,SAAS,SAAS,KAAA,KAAa,QAAQ,MAAM,KAAK,IAAI,IAAI,IAAI,OAAO;GAAE,GAAG;GAAO;EAAK;CACtH;CACA,IAAI,SAAS,KAAA,GAAW,OAAO;EAAE,IAAI;EAAM,SAAS,KAAK,YAAY,MAAM;EAAI,MAAM,KAAK;CAAK;CAC/F,IAAI,OAAO,OAAO,SAAS,GAAG,OAAO;EAAE,IAAI;EAAO,KAAK,eAAe,OAAO,KAAK,EAAE;CAAuC;CAC3H,MAAM,QAAQ,OAAO,QAAQ;CAC7B,OAAO;EAAE,IAAI;EAAO,KAAK,UAAU,KAAA,IAAY,+BAA+B,gEAAgE,MAAM;CAAM;AAC5J"}
|
package/build/plan.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as priceOf, r as offersOfPart } from "./offers-h_HvMkH_.js";
|
|
2
|
+
import { n as CONDITIONS, v as textSchema } from "./records-W6sPyhTQ.js";
|
|
2
3
|
import { compare, sum, valueIn } from "@mark1russell7/quantity";
|
|
3
4
|
import { z } from "zod";
|
|
4
5
|
import { evolve, frontOf, greedy, sweep } from "@mark1russell7/strategy-search";
|
package/build/plan.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plan.js","names":[],"sources":["../src/order.ts","../src/plan.ts"],"sourcesContent":["import { valueIn } from \"@mark1russell7/quantity\";\nimport { greedy, type Goal, type GreedyStop, type Selection } from \"@mark1russell7/strategy-search\";\nimport { offersOfPart, priceOf, type Observation, type PartWant } from \"./offers.ts\";\nimport type { Condition } from \"./records.ts\";\n\n/*\n * This module calculates a buy order: the purchases that give the most value for each unit of money under a budget.\n * The candidates come from the offers. The order is a budgeted greedy choice of strategy-search, in stages, for\n * example a first target and then a second target. The module knows no topic: the caller gives the value of a choice.\n */\n\n/** One product that a buyer wants: its key, the part that the offers must match, and the largest count of its units. */\nexport interface ProductWant {\n readonly product: string;\n readonly want: PartWant;\n /** The largest count of units to buy. The default is 1. */\n readonly max?: number | undefined;\n}\n\n/** One candidate of a buy order: a product, the price of one unit, the largest count of units and the offer. */\nexport interface BuyCandidate {\n readonly product: string;\n /** The cost of one unit with its shipping, in the currency of the order. */\n readonly price: number;\n readonly max: number;\n /** The `id` of the offer of the price. */\n readonly quote: string;\n}\n\n/** The candidates of a buy order, and the products that have no usable offer. */\nexport interface BuyCandidates {\n readonly currency: string;\n readonly candidates: readonly BuyCandidate[];\n readonly unpriced: readonly { readonly product: string; readonly why: string }[];\n}\n\n/** The options of the candidates: the currency and the conditions that the buyer accepts. */\nexport interface CandidateOptions {\n /** The currency of the prices, a unit of money of `@mark1russell7/quantity`, for example `USD`. */\n readonly currency: string;\n /** The conditions that the buyer accepts. The default is `new` only. */\n readonly conditions?: readonly Condition[] | undefined;\n}\n\n/**\n * This function gives a candidate for each product with a usable offer. The price is the cost of one unit with its\n * shipping, from the in-stock offer with the lowest cost, as in `planBuys`. Each unit is one order, so the price is an\n * upper limit of the cost of more units.\n *\n * @param wants - The products, in the order of the result\n * @param observations - The observations of the offers\n * @param options - The currency and the conditions\n * @throws RangeError when the currency is not a unit of money, or when a product is twice in `wants`\n */\nexport function buyCandidates(wants: readonly ProductWant[], observations: readonly Observation[], options: CandidateOptions): BuyCandidates {\n const seen = new Set<string>();\n const candidates: BuyCandidate[] = [];\n const unpriced: { product: string; why: string }[] = [];\n for (const want of wants) {\n if (seen.has(want.product)) throw new RangeError(`The product ${want.product} is twice in the wants.`);\n seen.add(want.product);\n const max = want.max ?? 1;\n if (!(Number.isSafeInteger(max) && max >= 0)) throw new RangeError(`The max of the product ${want.product} is ${String(max)}. It must be a whole number of 0 or more.`);\n const priced = priceOf(offersOfPart(observations, want.want), 1, options);\n if (priced.ok) candidates.push({ product: want.product, price: valueIn(priced.cost, options.currency), max, quote: priced.offerId });\n else unpriced.push({ product: want.product, why: priced.why });\n }\n return { currency: options.currency, candidates, unpriced };\n}\n\n/** One stage of a buy order: its name and the value of a choice, the most important number first. */\nexport interface OrderStage {\n readonly name: string;\n /** The value of the units of each product. It is a pure function. */\n readonly value: (units: Selection) => readonly number[];\n}\n\n/** The options of a buy order. */\nexport interface OrderOptions {\n /** The money of the order, in the currency of the candidates. */\n readonly budget: number;\n /** The stages, in order. Each stage starts from the units of the stage before it, with the money that is left. */\n readonly stages: readonly OrderStage[];\n /** The goal of each number of a value. Use `min` for a shortfall. The default is `max`. */\n readonly goal?: Goal | undefined;\n /** The units that the buyer has before the order. Their cost is not in the budget. */\n readonly start?: Selection | undefined;\n /** With `false`, each step evaluates each product again. Use it when two products give more together than apart. */\n readonly lazy?: boolean | undefined;\n}\n\n/** One purchase of a buy order: one unit of a product, its offer and its cost, and its gain in its stage. */\nexport interface OrderBuy {\n readonly stage: string;\n readonly product: string;\n readonly quote: string;\n readonly cost: number;\n readonly gain: readonly number[];\n}\n\n/** The result of one stage: the value before and after it, the money that it spends and the reason that it stops. */\nexport interface OrderStageResult {\n readonly name: string;\n readonly method: \"greedy\" | \"single\";\n readonly before: readonly number[];\n readonly after: readonly number[];\n readonly spent: number;\n readonly stop: GreedyStop;\n readonly evaluations: number;\n}\n\n/** A buy order: the purchases in the order of the choice, the units of each product, and the result of each stage. */\nexport interface BuyOrder {\n readonly budget: number;\n readonly spent: number;\n readonly buys: readonly OrderBuy[];\n /** The units of each product after the order, with the units of `start`. */\n readonly units: Selection;\n readonly stages: readonly OrderStageResult[];\n}\n\n/**\n * This function calculates a buy order with a budgeted greedy choice in each stage. Each step buys one unit of the\n * product with the largest gain for each unit of money. The choice is `greedy` of `@mark1russell7/strategy-search`.\n *\n * - A stage starts from the units of the stage before it, and it spends only the money that is left.\n * - A stage can give the best single unit in place of its steps, when that unit has a better value (`method: \"single\"`).\n *\n * @param candidates - The candidates, from `buyCandidates`\n * @param options - The budget, the stages, the goal and the start\n * @returns The buy order\n * @throws RangeError when the options are bad, or when a value is not a list of finite numbers with one length\n */\nexport function orderBuys(candidates: readonly BuyCandidate[], options: OrderOptions): BuyOrder {\n if (options.stages.length === 0) throw new RangeError(\"The order has no stage.\");\n if (!(Number.isFinite(options.budget) && options.budget >= 0)) throw new RangeError(`The budget is ${String(options.budget)}. It must be a finite number of 0 or more.`);\n const byProduct = new Map(candidates.map((candidate) => [candidate.product, candidate]));\n const items = candidates.map((candidate) => ({ id: candidate.product, cost: candidate.price, max: candidate.max }));\n const start: Selection = options.start ?? {};\n let units: Selection = start;\n let left = options.budget;\n let spent = 0;\n const buys: OrderBuy[] = [];\n const stages: OrderStageResult[] = [];\n for (const stage of options.stages) {\n // The max of each item is what is left after the stages before.\n const open = items.map((item) => ({ ...item, max: item.max - ((units[item.id] ?? 0) - (start[item.id] ?? 0)) }));\n const run = greedy({\n items: open,\n budget: Math.max(0, left),\n value: stage.value,\n start: units,\n ...(options.goal === undefined ? {} : { goal: options.goal }),\n ...(options.lazy === undefined ? {} : { lazy: options.lazy }),\n });\n for (const pick of run.picks) buys.push({ stage: stage.name, product: pick.id, quote: byProduct.get(pick.id)?.quote ?? \"\", cost: pick.cost, gain: pick.gain });\n units = run.selection;\n left -= run.spent;\n spent += run.spent;\n stages.push({ name: stage.name, method: run.method, before: run.before, after: run.after, spent: run.spent, stop: run.stop, evaluations: run.evaluations });\n }\n return { budget: options.budget, spent, buys, units, stages };\n}\n","import { compare, sum, valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { evolve, frontOf, sweep, type EvaluationRow, type Measure, type Objective, type SweepCounts } from \"@mark1russell7/strategy-search\";\nimport { spaceSize, STRATEGY_SPACE_SCHEMA, type SpaceParam, type StrategyConfig, type StrategySpace } from \"@mark1russell7/strategy-space\";\nimport { compile, isFieldName, parse, space, type AnyDomain, type Program } from \"@mark1russell7/vex\";\nimport { BoolDomain, NumDomain, TextDomain } from \"@mark1russell7/vex-domains\";\nimport { z } from \"zod\";\nimport { offersOfPart, priceOf, type Observation, type PartWant, type Priced } from \"./offers.ts\";\nimport { CONDITIONS, textSchema, type Condition } from \"./records.ts\";\n\n/*\n * This module calculates a buy plan. A need names the slots of a purchase, the parts that can fill each slot, and\n * the measures and the rules of a basket as Vex programs. The plan searches the baskets with strategy-search, and it\n * gives the front of the price against the measures. The module knows no part class: the facts of each part and the\n * programs come from the need. Each function of this module is a calculation with no effect.\n */\n\n/** The format name of a need record. */\nexport const NEED_FORMAT = \"buy-need/1\";\n\n/** The format name of a plan record. */\nexport const PLAN_FORMAT = \"buy-plan/1\";\n\n/** The key of the inputs of a need in the space of a basket. A slot cannot have this name. */\nexport const NEED_KEY = \"need\";\n\n/** The fields that the plan writes in the record of each slot. A fact of a part cannot have one of these names. */\nexport const SLOT_FIELDS = [\"slot\", \"part\", \"count\", \"cost\"] as const;\n\n/** The largest count of evaluations of a plan, when the options do not give a count. */\nexport const PLAN_EVALUATIONS = 2000;\n\n/** The domains of the programs of a need: numbers, booleans and texts. */\nconst DOMAINS: readonly AnyDomain[] = [NumDomain, BoolDomain, TextDomain];\n\n/** A fact of a part, or an input of a need: a number, a text or a boolean. */\nexport type Fact = number | string | boolean;\n\n/** One part that can fill a slot: its key in the slot, the part that the offers must match, and its facts. */\nexport interface NeedPart {\n readonly key: string;\n readonly want: PartWant;\n /** The facts of the part that the programs read, for example its watts. */\n readonly facts?: Readonly<Record<string, Fact>> | undefined;\n}\n\n/** The count of units of a slot. With `min` 0, a basket can leave the slot empty. */\nexport interface SlotCount {\n readonly min: number;\n readonly max: number;\n}\n\n/** One slot of a need: its name, the parts that can fill it, and the count of its units. The default count is 1. */\nexport interface NeedSlot {\n readonly name: string;\n readonly parts: readonly NeedPart[];\n readonly count?: SlotCount | undefined;\n}\n\n/**\n * One measure of a basket: a Vex program that gives a number. With `goal`, the measure is an objective of the search.\n * A value below `min` or above `max` breaks the basket.\n */\nexport interface NeedMeasure {\n readonly name: string;\n /** The program, as the JSON form of a Vex expression. */\n readonly program: unknown;\n readonly goal?: \"min\" | \"max\" | undefined;\n /** The unit of the values, as text for a reader. */\n readonly unit?: string | undefined;\n readonly min?: number | undefined;\n readonly max?: number | undefined;\n}\n\n/** One rule of a basket: a Vex program that gives `true` when the basket keeps the rule. */\nexport interface NeedRule {\n readonly name: string;\n /** The program, as the JSON form of a Vex expression. */\n readonly program: unknown;\n}\n\n/** This record is a need: the currency and the conditions of the offers, the inputs, the slots, the measures and the rules. */\nexport interface BuyNeed {\n readonly format: typeof NEED_FORMAT;\n readonly id: string;\n /** The currency of the prices, a unit of money of `@mark1russell7/quantity`, for example `USD`. */\n readonly currency: string;\n /** The conditions that the buyer accepts. The default is `new` only. */\n readonly conditions?: readonly Condition[] | undefined;\n /** The inputs that the programs read at the key `need`, for example the load in watts. */\n readonly inputs?: Readonly<Record<string, Fact>> | undefined;\n readonly slots: readonly NeedSlot[];\n readonly measures?: readonly NeedMeasure[] | undefined;\n readonly rules?: readonly NeedRule[] | undefined;\n}\n\nconst factSchema: z.ZodType<Fact> = z.union([z.number().refine(Number.isFinite, \"The number is not finite.\"), z.string(), z.boolean()]);\nconst factsSchema: z.ZodType<Readonly<Record<string, Fact>>> = z.record(textSchema, factSchema);\nconst wantSchema: z.ZodType<PartWant> = z.strictObject({ brands: z.array(textSchema).min(1), partNumbers: z.array(textSchema).min(1) });\nconst wholeSchema = z.number().int().nonnegative();\n\n/** This schema accepts the form of a need. `needProblems` examines the names, the counts and the programs. */\nexport const buyNeedSchema: z.ZodType<BuyNeed> = z.strictObject({\n format: z.literal(NEED_FORMAT),\n id: textSchema,\n currency: textSchema,\n conditions: z.array(z.enum(CONDITIONS)).min(1).optional(),\n inputs: factsSchema.optional(),\n slots: z\n .array(\n z.strictObject({\n name: textSchema,\n parts: z.array(z.strictObject({ key: textSchema, want: wantSchema, facts: factsSchema.optional() })).min(1),\n count: z.strictObject({ min: wholeSchema, max: wholeSchema }).optional(),\n }),\n )\n .min(1),\n measures: z\n .array(\n z.strictObject({\n name: textSchema,\n program: z.unknown(),\n goal: z.enum([\"min\", \"max\"]).optional(),\n unit: textSchema.optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n }),\n )\n .optional(),\n rules: z.array(z.strictObject({ name: textSchema, program: z.unknown() })).optional(),\n});\n\n/** This function gives the count of a slot, with the default 1 to 1. */\nfunction countOf(slot: NeedSlot): SlotCount {\n return slot.count ?? { min: 1, max: 1 };\n}\n\n/** This function reads a program of a need. It gives the expression, or the reason that the program is not valid. */\nfunction readProgram(program: unknown): { readonly ok: true; readonly program: Program } | { readonly ok: false; readonly why: string } {\n const text = program === undefined ? undefined : JSON.stringify(program);\n if (text === undefined) return { ok: false, why: \"The program is missing.\" };\n const read = parse(text, DOMAINS);\n return read.ok ? { ok: true, program: compile(read.value, { domains: DOMAINS }) } : { ok: false, why: read.error.message };\n}\n\n/** This function compiles a program that `needProblems` accepts. */\nfunction programOf(program: unknown): Program {\n const read = readProgram(program);\n if (!read.ok) throw new RangeError(read.why);\n return read.program;\n}\n\n/**\n * This function gives the problems of a need. Two slots, parts, measures or rules with one name are a problem. A bad\n * count is a problem. The slot name `need` and the measure name `price` are problems. A fact with the name of a field\n * of a slot is a problem. A program that is not valid is a problem.\n */\nexport function needProblems(need: BuyNeed): string[] {\n const problems: string[] = [];\n const twice = (names: readonly string[], what: string): void => {\n const seen = new Set<string>();\n for (const name of names) {\n if (seen.has(name)) problems.push(`Two ${what} have the name ${name}.`);\n seen.add(name);\n }\n };\n twice(\n need.slots.map((slot) => slot.name),\n \"slots\",\n );\n for (const name of Object.keys(need.inputs ?? {})) if (!isFieldName(name)) problems.push(`The input ${name} is not a name of a field.`);\n for (const slot of need.slots) {\n if (slot.name === NEED_KEY) problems.push(`The slot ${NEED_KEY} has the name of the inputs.`);\n else if (!isFieldName(slot.name)) problems.push(`The slot ${slot.name} is not a name of a field.`);\n twice(\n slot.parts.map((part) => part.key),\n `parts of the slot ${slot.name}`,\n );\n const { min, max } = countOf(slot);\n if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) || min < 0 || max < 1 || min > max)\n problems.push(`The count of the slot ${slot.name} is ${String(min)} to ${String(max)}. It must be whole numbers, with a maximum of 1 or more and not below the minimum.`);\n for (const part of slot.parts) {\n for (const name of Object.keys(part.facts ?? {})) {\n if ((SLOT_FIELDS as readonly string[]).includes(name)) problems.push(`The part ${part.key} of the slot ${slot.name} has the fact ${name}, which is a field of the slot.`);\n else if (!isFieldName(name)) problems.push(`The fact ${name} of the part ${part.key} is not a name of a field.`);\n }\n }\n }\n const measures = need.measures ?? [];\n const rules = need.rules ?? [];\n twice(\n measures.map((measure) => measure.name),\n \"measures\",\n );\n twice(\n rules.map((rule) => rule.name),\n \"rules\",\n );\n for (const measure of measures) {\n if (measure.name === \"price\") problems.push(\"A measure has the name price, which is the objective of the cost.\");\n if (measure.min !== undefined && measure.max !== undefined && measure.min > measure.max) problems.push(`The measure ${measure.name} has a minimum above its maximum.`);\n const read = readProgram(measure.program);\n if (!read.ok) problems.push(`The program of the measure ${measure.name} is not valid: ${read.why}`);\n }\n for (const rule of rules) {\n const read = readProgram(rule.program);\n if (!read.ok) problems.push(`The program of the rule ${rule.name} is not valid: ${read.why}`);\n }\n return problems;\n}\n\n/** This record is one item of a basket: the slot, the part, the count, the offer to buy and the cost with the shipping. */\nexport interface BuyItem {\n readonly slot: string;\n readonly part: string;\n readonly count: number;\n readonly offerId: string;\n readonly cost: Quantity;\n}\n\n/** This record is one basket of the front: its config id, its price, the value of each measure and its items. */\nexport interface BuyChoice {\n readonly config: string;\n /** The sum of the cost of each item. Each item is one order, with its own shipping. */\n readonly price: Quantity;\n readonly values: Readonly<Record<string, number>>;\n readonly items: readonly BuyItem[];\n}\n\n/** This record counts the baskets that break one constraint, with the reason of the first such basket. */\nexport interface BuyBreak {\n /** The constraint: `price:<slot>`, `measure:<name>`, `limit:<name>` or `rule:<name>`. */\n readonly name: string;\n readonly count: number;\n readonly why: string;\n}\n\n/** This record is a part that no basket can have, because no offer of the part is usable at a count of its slot. */\nexport interface UnpricedPart {\n readonly slot: string;\n readonly part: string;\n readonly why: string;\n}\n\n/** This record is a buy plan: the method of the search, its counts, the front of the baskets and the reasons of the breaks. */\nexport interface BuyPlan {\n readonly format: typeof PLAN_FORMAT;\n /** The id of the need. */\n readonly need: string;\n readonly currency: string;\n /** `grid` evaluates each basket. `evolve` is a genetic search. `none` tells that a slot that must have a part has no part with an offer. */\n readonly method: \"grid\" | \"evolve\" | \"none\";\n /** The seed of a genetic search, or null. */\n readonly seed: number | null;\n /** The id of the run of strategy-search, or null for `none`. */\n readonly run: string | null;\n readonly objectives: readonly Objective[];\n readonly counts: SweepCounts;\n /** The baskets on the Pareto front, from the lowest price. Equal prices go in the order of the config id. */\n readonly front: readonly BuyChoice[];\n /** The constraints that the evaluated baskets break, in the order of their names. */\n readonly breaks: readonly BuyBreak[];\n /** The parts with no usable offer, in the order of the slots and of their parts. */\n readonly unpriced: readonly UnpricedPart[];\n}\n\nexport { buyCandidates, orderBuys, type BuyCandidate, type BuyCandidates, type BuyOrder, type CandidateOptions, type OrderBuy, type OrderOptions, type OrderStage, type OrderStageResult, type ProductWant } from \"./order.ts\";\n\n/** These options change the search of a plan. */\nexport interface PlanOptions {\n /** The largest count of evaluations. A space with no more baskets gets a grid of each basket. The default is `PLAN_EVALUATIONS`. */\n readonly evaluations?: number | undefined;\n /** The seed of a genetic search. The default is the id of the need. */\n readonly seed?: number | string | undefined;\n /** The count of the baskets of a generation of a genetic search. The default is the default of strategy-search. */\n readonly population?: number | undefined;\n}\n\n\n/** The breaks, the values and the items of one basket. */\ninterface Assessed {\n readonly breaks: readonly { readonly name: string; readonly why: string }[];\n readonly values: Readonly<Record<string, number>>;\n readonly price: Quantity | null;\n readonly items: readonly BuyItem[];\n}\n\n\n/**\n * This function makes a buy plan from a need and the observations of the offers. Each slot is a stage of a strategy\n * space. Each part with a usable offer is an option of its stage, with a param `count`. The price of a basket is the sum\n * of the cost of each item.\n *\n * Each measure and each rule is a Vex program that evaluates at the key `need` of a record space. The key `need` has\n * the inputs. The key of each slot has the facts of its part, `slot`, `part`, `count` and `cost`. A slot with no part\n * has only `slot`, the count 0 and the cost 0. Thus the axis `others` gives the slots.\n *\n * A space with no more baskets than `evaluations` gets a grid of each basket, and a larger space gets a genetic search.\n *\n * @throws RangeError when the need or its currency is not valid, or when `evaluations` is not a whole number of 1 or more.\n * The function also throws a RangeError when strategy-search refuses the options.\n */\nexport function planBuys(need: BuyNeed, observations: readonly Observation[], options: PlanOptions = {}): BuyPlan {\n const shape = buyNeedSchema.safeParse(need);\n if (!shape.success) throw new RangeError(`The need is not valid: ${shape.error.issues.map((issue) => `${issue.path.join(\".\")}: ${issue.message}`).join(\" \")}`);\n const problems = needProblems(need);\n if (problems.length > 0) throw new RangeError(`The need is not valid: ${problems.join(\" \")}`);\n const evaluations = options.evaluations ?? PLAN_EVALUATIONS;\n if (!Number.isSafeInteger(evaluations) || evaluations < 1) throw new RangeError(`The count of evaluations ${String(evaluations)} is not a whole number of 1 or more.`);\n\n const measures = (need.measures ?? []).map((measure) => ({ measure, program: programOf(measure.program) }));\n const rules = (need.rules ?? []).map((rule) => ({ rule, program: programOf(rule.program) }));\n const objectives: Objective[] = [\n { name: \"price\", goal: \"min\", unit: need.currency },\n ...measures.flatMap(({ measure }) => (measure.goal === undefined ? [] : [measure.unit === undefined ? { name: measure.name, goal: measure.goal } : { name: measure.name, goal: measure.goal, unit: measure.unit }])),\n ];\n\n // The price of each count of each part, once. A part with no usable offer at any count is not an option.\n const prices = new Map<string, Map<number, Priced>>();\n const unpriced: UnpricedPart[] = [];\n const stages: StrategySpace[\"stages\"][number][] = [];\n let blocked = false;\n for (const slot of need.slots) {\n const { min, max } = countOf(slot);\n const low = Math.max(1, min);\n const params: SpaceParam[] = max > low ? [{ name: \"count\", kind: \"int\", min: low, max, default: low }] : [];\n const usable: string[] = [];\n for (const part of slot.parts) {\n const offers = offersOfPart(observations, part.want);\n const byCount = new Map<number, Priced>();\n for (let count = low; count <= max; count++) byCount.set(count, priceOf(offers, count, need));\n prices.set(`${slot.name}\\u0000${part.key}`, byCount);\n const first = byCount.get(low);\n if ([...byCount.values()].some((priced) => priced.ok)) usable.push(part.key);\n else unpriced.push({ slot: slot.name, part: part.key, why: first === undefined || first.ok ? \"No offer is usable.\" : first.why });\n }\n if (usable.length > 0) stages.push({ name: slot.name, options: usable.map((id) => ({ id, params })), ...(min === 0 ? { optional: true } : {}) });\n else if (min > 0) blocked = true;\n }\n const none: BuyPlan = { format: PLAN_FORMAT, need: need.id, currency: need.currency, method: \"none\", seed: null, run: null, objectives, counts: { feasible: 0, breaks: 0, unread: 0, front: 0 }, front: [], breaks: [], unpriced };\n if (blocked || stages.length === 0) return none;\n\n const strategySpace: StrategySpace = { schema: STRATEGY_SPACE_SCHEMA, engine: \"buy-plan\", version: \"1\", stages };\n\n const assess = (config: StrategyConfig): Assessed => {\n const breaks: { name: string; why: string }[] = [];\n const items: BuyItem[] = [];\n const records: Record<string, Readonly<Record<string, Fact>>> = { [NEED_KEY]: need.inputs ?? {} };\n for (const slot of need.slots) {\n const choice = config.stages[slot.name] ?? null;\n if (choice === null) {\n records[slot.name] = { slot: slot.name, count: 0, cost: 0 };\n continue;\n }\n const part = slot.parts.find((each) => each.key === choice.option) as NeedPart;\n const count = Number(choice.params?.[\"count\"] ?? Math.max(1, countOf(slot).min));\n const priced = prices.get(`${slot.name}\\u0000${part.key}`)?.get(count) ?? { ok: false, why: `The count ${String(count)} is not a count of the slot.` };\n if (!priced.ok) {\n breaks.push({ name: `price:${slot.name}`, why: `The part ${part.key} of the slot ${slot.name}: ${priced.why}` });\n records[slot.name] = { ...part.facts, slot: slot.name, part: part.key, count, cost: 0 };\n continue;\n }\n items.push({ slot: slot.name, part: part.key, count, offerId: priced.offerId, cost: priced.cost });\n records[slot.name] = { ...part.facts, slot: slot.name, part: part.key, count, cost: valueIn(priced.cost, need.currency) };\n }\n const price = breaks.length > 0 ? null : sum(items.map((item) => item.cost), need.currency);\n const values: Record<string, number> = price === null ? {} : { price: valueIn(price, need.currency) };\n const basket = space.record(records);\n for (const { measure, program } of measures) {\n const result = program.run({ space: basket, origin: NEED_KEY });\n if (!result.ok) breaks.push({ name: `measure:${measure.name}`, why: result.error.message });\n else if (typeof result.value !== \"number\" || !Number.isFinite(result.value)) breaks.push({ name: `measure:${measure.name}`, why: `The value ${String(result.value)} is not a finite number.` });\n else {\n values[measure.name] = result.value;\n if (measure.min !== undefined && result.value < measure.min) breaks.push({ name: `limit:${measure.name}`, why: `The value ${String(result.value)} is below the minimum ${String(measure.min)}.` });\n if (measure.max !== undefined && result.value > measure.max) breaks.push({ name: `limit:${measure.name}`, why: `The value ${String(result.value)} is above the maximum ${String(measure.max)}.` });\n }\n }\n for (const { rule, program } of rules) {\n const result = program.run({ space: basket, origin: NEED_KEY });\n if (!result.ok) breaks.push({ name: `rule:${rule.name}`, why: result.error.message });\n else if (result.value !== true) breaks.push({ name: `rule:${rule.name}`, why: result.value === false ? \"The basket breaks the rule.\" : `The value ${String(result.value)} is not a boolean.` });\n }\n return { breaks, values, price, items };\n };\n\n // The reason of the first basket that breaks each constraint.\n const firstWhy = new Map<string, string>();\n const evaluate = (config: StrategyConfig): Measure => {\n const assessed = assess(config);\n for (const { name, why } of assessed.breaks) if (!firstWhy.has(name)) firstWhy.set(name, why);\n return { breaks: [...new Set(assessed.breaks.map((each) => each.name))], values: assessed.values };\n };\n\n const levels = Math.max(1, ...need.slots.map((slot) => countOf(slot).max - Math.max(1, countOf(slot).min) + 1));\n const grid = spaceSize(strategySpace, { levels }).base <= BigInt(evaluations);\n const evaluator = `buy-need:${need.id}`;\n const run = grid\n ? sweep(strategySpace, { objectives, evaluate, enumerate: { mode: \"grid\", levels, limit: evaluations }, evaluator })\n : evolve(strategySpace, {\n objectives,\n evaluate,\n seed: options.seed ?? need.id,\n evaluations,\n ...(options.population === undefined ? {} : { population: options.population }),\n evaluator,\n });\n\n const front = frontOf(run)\n .map(({ row, config }): BuyChoice => {\n const assessed = assess(config);\n const values = Object.fromEntries(Object.entries(assessed.values).filter(([name]) => name !== \"price\"));\n return { config: row.config, price: assessed.price as Quantity, values, items: assessed.items };\n })\n .sort((a, b) => compare(a.price, b.price) || (a.config < b.config ? -1 : a.config > b.config ? 1 : 0));\n return {\n ...none,\n method: grid ? \"grid\" : \"evolve\",\n seed: run.seed,\n run: run.run,\n counts: run.counts,\n front,\n breaks: breaksOf(run.rows, firstWhy),\n unpriced,\n };\n}\n\n/** This function counts the rows that break each constraint, in the order of the names. */\nfunction breaksOf(rows: readonly EvaluationRow[], firstWhy: ReadonlyMap<string, string>): BuyBreak[] {\n const counts = new Map<string, number>();\n for (const row of rows) for (const name of row.breaks) counts.set(name, (counts.get(name) ?? 0) + 1);\n return [...counts.entries()]\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([name, count]) => ({ name, count, why: firstWhy.get(name) ?? \"\" }));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsDA,SAAgB,cAAc,OAA+B,cAAsC,SAA0C;CAC3I,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,aAA6B,CAAC;CACpC,MAAM,WAA+C,CAAC;CACtD,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,KAAK,IAAI,KAAK,OAAO,GAAG,MAAM,IAAI,WAAW,eAAe,KAAK,QAAQ,wBAAwB;EACrG,KAAK,IAAI,KAAK,OAAO;EACrB,MAAM,MAAM,KAAK,OAAO;EACxB,IAAI,EAAE,OAAO,cAAc,GAAG,KAAK,OAAO,IAAI,MAAM,IAAI,WAAW,0BAA0B,KAAK,QAAQ,MAAM,OAAO,GAAG,EAAE,0CAA0C;EACtK,MAAM,SAAS,QAAQ,aAAa,cAAc,KAAK,IAAI,GAAG,GAAG,OAAO;EACxE,IAAI,OAAO,IAAI,WAAW,KAAK;GAAE,S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,IAAI;EACZ;EACA,QAAQ,SAAS,IAAI,MAAM,QAAQ;EACnC;CACF;AACF;;AAGA,SAAS,SAAS,MAAgC,UAAmD;CACnG,MAAM,yBAAS,IAAI,IAAoB;CACvC,KAAK,MAAM,OAAO,MAAM,KAAK,MAAM,QAAQ,IAAI,QAAQ,OAAO,IAAI,OAAO,OAAO,IAAI,IAAI,KAAK,KAAK,CAAC;CACnG,OAAO,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,CACzB,MAAM,CAAC,IAAI,CAAC,OAAQ,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,CAAE,CAAC,CAChD,KAAK,CAAC,MAAM,YAAY;EAAE;EAAM;EAAO,KAAK,SAAS,IAAI,IAAI,KAAK;CAAG,EAAE;AAC5E"}
|
|
1
|
+
{"version":3,"file":"plan.js","names":[],"sources":["../src/order.ts","../src/plan.ts"],"sourcesContent":["import { valueIn } from \"@mark1russell7/quantity\";\nimport { greedy, type Goal, type GreedyStop, type Selection } from \"@mark1russell7/strategy-search\";\nimport { offersOfPart, priceOf, type Observation, type PartWant } from \"./offers.ts\";\nimport type { Condition } from \"./records.ts\";\n\n/*\n * This module calculates a buy order: the purchases that give the most value for each unit of money under a budget.\n * The candidates come from the offers. The order is a budgeted greedy choice of strategy-search, in stages, for\n * example a first target and then a second target. The module knows no topic: the caller gives the value of a choice.\n */\n\n/** One product that a buyer wants: its key, the part that the offers must match, and the largest count of its units. */\nexport interface ProductWant {\n readonly product: string;\n readonly want: PartWant;\n /** The largest count of units to buy. The default is 1. */\n readonly max?: number | undefined;\n}\n\n/** One candidate of a buy order: a product, the price of one unit, the largest count of units and the offer. */\nexport interface BuyCandidate {\n readonly product: string;\n /** The cost of one unit with its shipping, in the currency of the order. */\n readonly price: number;\n readonly max: number;\n /** The `id` of the offer of the price. */\n readonly quote: string;\n}\n\n/** The candidates of a buy order, and the products that have no usable offer. */\nexport interface BuyCandidates {\n readonly currency: string;\n readonly candidates: readonly BuyCandidate[];\n readonly unpriced: readonly { readonly product: string; readonly why: string }[];\n}\n\n/** The options of the candidates: the currency and the conditions that the buyer accepts. */\nexport interface CandidateOptions {\n /** The currency of the prices, a unit of money of `@mark1russell7/quantity`, for example `USD`. */\n readonly currency: string;\n /** The conditions that the buyer accepts. The default is `new` only. */\n readonly conditions?: readonly Condition[] | undefined;\n}\n\n/**\n * This function gives a candidate for each product with a usable offer. The price is the cost of one unit with its\n * shipping, from the in-stock offer with the lowest cost, as in `planBuys`. Each unit is one order, so the price is an\n * upper limit of the cost of more units.\n *\n * @param wants - The products, in the order of the result\n * @param observations - The observations of the offers\n * @param options - The currency and the conditions\n * @throws RangeError when the currency is not a unit of money, or when a product is twice in `wants`\n */\nexport function buyCandidates(wants: readonly ProductWant[], observations: readonly Observation[], options: CandidateOptions): BuyCandidates {\n const seen = new Set<string>();\n const candidates: BuyCandidate[] = [];\n const unpriced: { product: string; why: string }[] = [];\n for (const want of wants) {\n if (seen.has(want.product)) throw new RangeError(`The product ${want.product} is twice in the wants.`);\n seen.add(want.product);\n const max = want.max ?? 1;\n if (!(Number.isSafeInteger(max) && max >= 0)) throw new RangeError(`The max of the product ${want.product} is ${String(max)}. It must be a whole number of 0 or more.`);\n const priced = priceOf(offersOfPart(observations, want.want), 1, options);\n if (priced.ok) candidates.push({ product: want.product, price: valueIn(priced.cost, options.currency), max, quote: priced.offerId });\n else unpriced.push({ product: want.product, why: priced.why });\n }\n return { currency: options.currency, candidates, unpriced };\n}\n\n/** One stage of a buy order: its name and the value of a choice, the most important number first. */\nexport interface OrderStage {\n readonly name: string;\n /** The value of the units of each product. It is a pure function. */\n readonly value: (units: Selection) => readonly number[];\n}\n\n/** The options of a buy order. */\nexport interface OrderOptions {\n /** The money of the order, in the currency of the candidates. */\n readonly budget: number;\n /** The stages, in order. Each stage starts from the units of the stage before it, with the money that is left. */\n readonly stages: readonly OrderStage[];\n /** The goal of each number of a value. Use `min` for a shortfall. The default is `max`. */\n readonly goal?: Goal | undefined;\n /** The units that the buyer has before the order. Their cost is not in the budget. */\n readonly start?: Selection | undefined;\n /** With `false`, each step evaluates each product again. Use it when two products give more together than apart. */\n readonly lazy?: boolean | undefined;\n}\n\n/** One purchase of a buy order: one unit of a product, its offer and its cost, and its gain in its stage. */\nexport interface OrderBuy {\n readonly stage: string;\n readonly product: string;\n readonly quote: string;\n readonly cost: number;\n readonly gain: readonly number[];\n}\n\n/** The result of one stage: the value before and after it, the money that it spends and the reason that it stops. */\nexport interface OrderStageResult {\n readonly name: string;\n readonly method: \"greedy\" | \"single\";\n readonly before: readonly number[];\n readonly after: readonly number[];\n readonly spent: number;\n readonly stop: GreedyStop;\n readonly evaluations: number;\n}\n\n/** A buy order: the purchases in the order of the choice, the units of each product, and the result of each stage. */\nexport interface BuyOrder {\n readonly budget: number;\n readonly spent: number;\n readonly buys: readonly OrderBuy[];\n /** The units of each product after the order, with the units of `start`. */\n readonly units: Selection;\n readonly stages: readonly OrderStageResult[];\n}\n\n/**\n * This function calculates a buy order with a budgeted greedy choice in each stage. Each step buys one unit of the\n * product with the largest gain for each unit of money. The choice is `greedy` of `@mark1russell7/strategy-search`.\n *\n * - A stage starts from the units of the stage before it, and it spends only the money that is left.\n * - A stage can give the best single unit in place of its steps, when that unit has a better value (`method: \"single\"`).\n *\n * @param candidates - The candidates, from `buyCandidates`\n * @param options - The budget, the stages, the goal and the start\n * @returns The buy order\n * @throws RangeError when the options are bad, or when a value is not a list of finite numbers with one length\n */\nexport function orderBuys(candidates: readonly BuyCandidate[], options: OrderOptions): BuyOrder {\n if (options.stages.length === 0) throw new RangeError(\"The order has no stage.\");\n if (!(Number.isFinite(options.budget) && options.budget >= 0)) throw new RangeError(`The budget is ${String(options.budget)}. It must be a finite number of 0 or more.`);\n const byProduct = new Map(candidates.map((candidate) => [candidate.product, candidate]));\n const items = candidates.map((candidate) => ({ id: candidate.product, cost: candidate.price, max: candidate.max }));\n const start: Selection = options.start ?? {};\n let units: Selection = start;\n let left = options.budget;\n let spent = 0;\n const buys: OrderBuy[] = [];\n const stages: OrderStageResult[] = [];\n for (const stage of options.stages) {\n // The max of each item is what is left after the stages before.\n const open = items.map((item) => ({ ...item, max: item.max - ((units[item.id] ?? 0) - (start[item.id] ?? 0)) }));\n const run = greedy({\n items: open,\n budget: Math.max(0, left),\n value: stage.value,\n start: units,\n ...(options.goal === undefined ? {} : { goal: options.goal }),\n ...(options.lazy === undefined ? {} : { lazy: options.lazy }),\n });\n for (const pick of run.picks) buys.push({ stage: stage.name, product: pick.id, quote: byProduct.get(pick.id)?.quote ?? \"\", cost: pick.cost, gain: pick.gain });\n units = run.selection;\n left -= run.spent;\n spent += run.spent;\n stages.push({ name: stage.name, method: run.method, before: run.before, after: run.after, spent: run.spent, stop: run.stop, evaluations: run.evaluations });\n }\n return { budget: options.budget, spent, buys, units, stages };\n}\n","import { compare, sum, valueIn, type Quantity } from \"@mark1russell7/quantity\";\nimport { evolve, frontOf, sweep, type EvaluationRow, type Measure, type Objective, type SweepCounts } from \"@mark1russell7/strategy-search\";\nimport { spaceSize, STRATEGY_SPACE_SCHEMA, type SpaceParam, type StrategyConfig, type StrategySpace } from \"@mark1russell7/strategy-space\";\nimport { compile, isFieldName, parse, space, type AnyDomain, type Program } from \"@mark1russell7/vex\";\nimport { BoolDomain, NumDomain, TextDomain } from \"@mark1russell7/vex-domains\";\nimport { z } from \"zod\";\nimport { offersOfPart, priceOf, type Observation, type PartWant, type Priced } from \"./offers.ts\";\nimport { CONDITIONS, textSchema, type Condition } from \"./records.ts\";\n\n/*\n * This module calculates a buy plan. A need names the slots of a purchase, the parts that can fill each slot, and\n * the measures and the rules of a basket as Vex programs. The plan searches the baskets with strategy-search, and it\n * gives the front of the price against the measures. The module knows no part class: the facts of each part and the\n * programs come from the need. Each function of this module is a calculation with no effect.\n */\n\n/** The format name of a need record. */\nexport const NEED_FORMAT = \"buy-need/1\";\n\n/** The format name of a plan record. */\nexport const PLAN_FORMAT = \"buy-plan/1\";\n\n/** The key of the inputs of a need in the space of a basket. A slot cannot have this name. */\nexport const NEED_KEY = \"need\";\n\n/** The fields that the plan writes in the record of each slot. A fact of a part cannot have one of these names. */\nexport const SLOT_FIELDS = [\"slot\", \"part\", \"count\", \"cost\"] as const;\n\n/** The largest count of evaluations of a plan, when the options do not give a count. */\nexport const PLAN_EVALUATIONS = 2000;\n\n/** The domains of the programs of a need: numbers, booleans and texts. */\nconst DOMAINS: readonly AnyDomain[] = [NumDomain, BoolDomain, TextDomain];\n\n/** A fact of a part, or an input of a need: a number, a text or a boolean. */\nexport type Fact = number | string | boolean;\n\n/** One part that can fill a slot: its key in the slot, the part that the offers must match, and its facts. */\nexport interface NeedPart {\n readonly key: string;\n readonly want: PartWant;\n /** The facts of the part that the programs read, for example its watts. */\n readonly facts?: Readonly<Record<string, Fact>> | undefined;\n}\n\n/** The count of units of a slot. With `min` 0, a basket can leave the slot empty. */\nexport interface SlotCount {\n readonly min: number;\n readonly max: number;\n}\n\n/** One slot of a need: its name, the parts that can fill it, and the count of its units. The default count is 1. */\nexport interface NeedSlot {\n readonly name: string;\n readonly parts: readonly NeedPart[];\n readonly count?: SlotCount | undefined;\n}\n\n/**\n * One measure of a basket: a Vex program that gives a number. With `goal`, the measure is an objective of the search.\n * A value below `min` or above `max` breaks the basket.\n */\nexport interface NeedMeasure {\n readonly name: string;\n /** The program, as the JSON form of a Vex expression. */\n readonly program: unknown;\n readonly goal?: \"min\" | \"max\" | undefined;\n /** The unit of the values, as text for a reader. */\n readonly unit?: string | undefined;\n readonly min?: number | undefined;\n readonly max?: number | undefined;\n}\n\n/** One rule of a basket: a Vex program that gives `true` when the basket keeps the rule. */\nexport interface NeedRule {\n readonly name: string;\n /** The program, as the JSON form of a Vex expression. */\n readonly program: unknown;\n}\n\n/** This record is a need: the currency and the conditions of the offers, the inputs, the slots, the measures and the rules. */\nexport interface BuyNeed {\n readonly format: typeof NEED_FORMAT;\n readonly id: string;\n /** The currency of the prices, a unit of money of `@mark1russell7/quantity`, for example `USD`. */\n readonly currency: string;\n /** The conditions that the buyer accepts. The default is `new` only. */\n readonly conditions?: readonly Condition[] | undefined;\n /** The inputs that the programs read at the key `need`, for example the load in watts. */\n readonly inputs?: Readonly<Record<string, Fact>> | undefined;\n readonly slots: readonly NeedSlot[];\n readonly measures?: readonly NeedMeasure[] | undefined;\n readonly rules?: readonly NeedRule[] | undefined;\n}\n\nconst factSchema: z.ZodType<Fact> = z.union([z.number().refine(Number.isFinite, \"The number is not finite.\"), z.string(), z.boolean()]);\nconst factsSchema: z.ZodType<Readonly<Record<string, Fact>>> = z.record(textSchema, factSchema);\nconst wantSchema: z.ZodType<PartWant> = z.strictObject({ brands: z.array(textSchema).min(1), partNumbers: z.array(textSchema).min(1) });\nconst wholeSchema = z.number().int().nonnegative();\n\n/** This schema accepts the form of a need. `needProblems` examines the names, the counts and the programs. */\nexport const buyNeedSchema: z.ZodType<BuyNeed> = z.strictObject({\n format: z.literal(NEED_FORMAT),\n id: textSchema,\n currency: textSchema,\n conditions: z.array(z.enum(CONDITIONS)).min(1).optional(),\n inputs: factsSchema.optional(),\n slots: z\n .array(\n z.strictObject({\n name: textSchema,\n parts: z.array(z.strictObject({ key: textSchema, want: wantSchema, facts: factsSchema.optional() })).min(1),\n count: z.strictObject({ min: wholeSchema, max: wholeSchema }).optional(),\n }),\n )\n .min(1),\n measures: z\n .array(\n z.strictObject({\n name: textSchema,\n program: z.unknown(),\n goal: z.enum([\"min\", \"max\"]).optional(),\n unit: textSchema.optional(),\n min: z.number().optional(),\n max: z.number().optional(),\n }),\n )\n .optional(),\n rules: z.array(z.strictObject({ name: textSchema, program: z.unknown() })).optional(),\n});\n\n/** This function gives the count of a slot, with the default 1 to 1. */\nfunction countOf(slot: NeedSlot): SlotCount {\n return slot.count ?? { min: 1, max: 1 };\n}\n\n/** This function reads a program of a need. It gives the expression, or the reason that the program is not valid. */\nfunction readProgram(program: unknown): { readonly ok: true; readonly program: Program } | { readonly ok: false; readonly why: string } {\n const text = program === undefined ? undefined : JSON.stringify(program);\n if (text === undefined) return { ok: false, why: \"The program is missing.\" };\n const read = parse(text, DOMAINS);\n return read.ok ? { ok: true, program: compile(read.value, { domains: DOMAINS }) } : { ok: false, why: read.error.message };\n}\n\n/** This function compiles a program that `needProblems` accepts. */\nfunction programOf(program: unknown): Program {\n const read = readProgram(program);\n if (!read.ok) throw new RangeError(read.why);\n return read.program;\n}\n\n/**\n * This function gives the problems of a need. Two slots, parts, measures or rules with one name are a problem. A bad\n * count is a problem. The slot name `need` and the measure name `price` are problems. A fact with the name of a field\n * of a slot is a problem. A program that is not valid is a problem.\n */\nexport function needProblems(need: BuyNeed): string[] {\n const problems: string[] = [];\n const twice = (names: readonly string[], what: string): void => {\n const seen = new Set<string>();\n for (const name of names) {\n if (seen.has(name)) problems.push(`Two ${what} have the name ${name}.`);\n seen.add(name);\n }\n };\n twice(\n need.slots.map((slot) => slot.name),\n \"slots\",\n );\n for (const name of Object.keys(need.inputs ?? {})) if (!isFieldName(name)) problems.push(`The input ${name} is not a name of a field.`);\n for (const slot of need.slots) {\n if (slot.name === NEED_KEY) problems.push(`The slot ${NEED_KEY} has the name of the inputs.`);\n else if (!isFieldName(slot.name)) problems.push(`The slot ${slot.name} is not a name of a field.`);\n twice(\n slot.parts.map((part) => part.key),\n `parts of the slot ${slot.name}`,\n );\n const { min, max } = countOf(slot);\n if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) || min < 0 || max < 1 || min > max)\n problems.push(`The count of the slot ${slot.name} is ${String(min)} to ${String(max)}. It must be whole numbers, with a maximum of 1 or more and not below the minimum.`);\n for (const part of slot.parts) {\n for (const name of Object.keys(part.facts ?? {})) {\n if ((SLOT_FIELDS as readonly string[]).includes(name)) problems.push(`The part ${part.key} of the slot ${slot.name} has the fact ${name}, which is a field of the slot.`);\n else if (!isFieldName(name)) problems.push(`The fact ${name} of the part ${part.key} is not a name of a field.`);\n }\n }\n }\n const measures = need.measures ?? [];\n const rules = need.rules ?? [];\n twice(\n measures.map((measure) => measure.name),\n \"measures\",\n );\n twice(\n rules.map((rule) => rule.name),\n \"rules\",\n );\n for (const measure of measures) {\n if (measure.name === \"price\") problems.push(\"A measure has the name price, which is the objective of the cost.\");\n if (measure.min !== undefined && measure.max !== undefined && measure.min > measure.max) problems.push(`The measure ${measure.name} has a minimum above its maximum.`);\n const read = readProgram(measure.program);\n if (!read.ok) problems.push(`The program of the measure ${measure.name} is not valid: ${read.why}`);\n }\n for (const rule of rules) {\n const read = readProgram(rule.program);\n if (!read.ok) problems.push(`The program of the rule ${rule.name} is not valid: ${read.why}`);\n }\n return problems;\n}\n\n/** This record is one item of a basket: the slot, the part, the count, the offer to buy and the cost with the shipping. */\nexport interface BuyItem {\n readonly slot: string;\n readonly part: string;\n readonly count: number;\n readonly offerId: string;\n readonly cost: Quantity;\n}\n\n/** This record is one basket of the front: its config id, its price, the value of each measure and its items. */\nexport interface BuyChoice {\n readonly config: string;\n /** The sum of the cost of each item. Each item is one order, with its own shipping. */\n readonly price: Quantity;\n readonly values: Readonly<Record<string, number>>;\n readonly items: readonly BuyItem[];\n}\n\n/** This record counts the baskets that break one constraint, with the reason of the first such basket. */\nexport interface BuyBreak {\n /** The constraint: `price:<slot>`, `measure:<name>`, `limit:<name>` or `rule:<name>`. */\n readonly name: string;\n readonly count: number;\n readonly why: string;\n}\n\n/** This record is a part that no basket can have, because no offer of the part is usable at a count of its slot. */\nexport interface UnpricedPart {\n readonly slot: string;\n readonly part: string;\n readonly why: string;\n}\n\n/** This record is a buy plan: the method of the search, its counts, the front of the baskets and the reasons of the breaks. */\nexport interface BuyPlan {\n readonly format: typeof PLAN_FORMAT;\n /** The id of the need. */\n readonly need: string;\n readonly currency: string;\n /** `grid` evaluates each basket. `evolve` is a genetic search. `none` tells that a slot that must have a part has no part with an offer. */\n readonly method: \"grid\" | \"evolve\" | \"none\";\n /** The seed of a genetic search, or null. */\n readonly seed: number | null;\n /** The id of the run of strategy-search, or null for `none`. */\n readonly run: string | null;\n readonly objectives: readonly Objective[];\n readonly counts: SweepCounts;\n /** The baskets on the Pareto front, from the lowest price. Equal prices go in the order of the config id. */\n readonly front: readonly BuyChoice[];\n /** The constraints that the evaluated baskets break, in the order of their names. */\n readonly breaks: readonly BuyBreak[];\n /** The parts with no usable offer, in the order of the slots and of their parts. */\n readonly unpriced: readonly UnpricedPart[];\n}\n\nexport { buyCandidates, orderBuys, type BuyCandidate, type BuyCandidates, type BuyOrder, type CandidateOptions, type OrderBuy, type OrderOptions, type OrderStage, type OrderStageResult, type ProductWant } from \"./order.ts\";\n\n/** These options change the search of a plan. */\nexport interface PlanOptions {\n /** The largest count of evaluations. A space with no more baskets gets a grid of each basket. The default is `PLAN_EVALUATIONS`. */\n readonly evaluations?: number | undefined;\n /** The seed of a genetic search. The default is the id of the need. */\n readonly seed?: number | string | undefined;\n /** The count of the baskets of a generation of a genetic search. The default is the default of strategy-search. */\n readonly population?: number | undefined;\n}\n\n\n/** The breaks, the values and the items of one basket. */\ninterface Assessed {\n readonly breaks: readonly { readonly name: string; readonly why: string }[];\n readonly values: Readonly<Record<string, number>>;\n readonly price: Quantity | null;\n readonly items: readonly BuyItem[];\n}\n\n\n/**\n * This function makes a buy plan from a need and the observations of the offers. Each slot is a stage of a strategy\n * space. Each part with a usable offer is an option of its stage, with a param `count`. The price of a basket is the sum\n * of the cost of each item.\n *\n * Each measure and each rule is a Vex program that evaluates at the key `need` of a record space. The key `need` has\n * the inputs. The key of each slot has the facts of its part, `slot`, `part`, `count` and `cost`. A slot with no part\n * has only `slot`, the count 0 and the cost 0. Thus the axis `others` gives the slots.\n *\n * A space with no more baskets than `evaluations` gets a grid of each basket, and a larger space gets a genetic search.\n *\n * @throws RangeError when the need or its currency is not valid, or when `evaluations` is not a whole number of 1 or more.\n * The function also throws a RangeError when strategy-search refuses the options.\n */\nexport function planBuys(need: BuyNeed, observations: readonly Observation[], options: PlanOptions = {}): BuyPlan {\n const shape = buyNeedSchema.safeParse(need);\n if (!shape.success) throw new RangeError(`The need is not valid: ${shape.error.issues.map((issue) => `${issue.path.join(\".\")}: ${issue.message}`).join(\" \")}`);\n const problems = needProblems(need);\n if (problems.length > 0) throw new RangeError(`The need is not valid: ${problems.join(\" \")}`);\n const evaluations = options.evaluations ?? PLAN_EVALUATIONS;\n if (!Number.isSafeInteger(evaluations) || evaluations < 1) throw new RangeError(`The count of evaluations ${String(evaluations)} is not a whole number of 1 or more.`);\n\n const measures = (need.measures ?? []).map((measure) => ({ measure, program: programOf(measure.program) }));\n const rules = (need.rules ?? []).map((rule) => ({ rule, program: programOf(rule.program) }));\n const objectives: Objective[] = [\n { name: \"price\", goal: \"min\", unit: need.currency },\n ...measures.flatMap(({ measure }) => (measure.goal === undefined ? [] : [measure.unit === undefined ? { name: measure.name, goal: measure.goal } : { name: measure.name, goal: measure.goal, unit: measure.unit }])),\n ];\n\n // The price of each count of each part, once. A part with no usable offer at any count is not an option.\n const prices = new Map<string, Map<number, Priced>>();\n const unpriced: UnpricedPart[] = [];\n const stages: StrategySpace[\"stages\"][number][] = [];\n let blocked = false;\n for (const slot of need.slots) {\n const { min, max } = countOf(slot);\n const low = Math.max(1, min);\n const params: SpaceParam[] = max > low ? [{ name: \"count\", kind: \"int\", min: low, max, default: low }] : [];\n const usable: string[] = [];\n for (const part of slot.parts) {\n const offers = offersOfPart(observations, part.want);\n const byCount = new Map<number, Priced>();\n for (let count = low; count <= max; count++) byCount.set(count, priceOf(offers, count, need));\n prices.set(`${slot.name}\\u0000${part.key}`, byCount);\n const first = byCount.get(low);\n if ([...byCount.values()].some((priced) => priced.ok)) usable.push(part.key);\n else unpriced.push({ slot: slot.name, part: part.key, why: first === undefined || first.ok ? \"No offer is usable.\" : first.why });\n }\n if (usable.length > 0) stages.push({ name: slot.name, options: usable.map((id) => ({ id, params })), ...(min === 0 ? { optional: true } : {}) });\n else if (min > 0) blocked = true;\n }\n const none: BuyPlan = { format: PLAN_FORMAT, need: need.id, currency: need.currency, method: \"none\", seed: null, run: null, objectives, counts: { feasible: 0, breaks: 0, unread: 0, front: 0 }, front: [], breaks: [], unpriced };\n if (blocked || stages.length === 0) return none;\n\n const strategySpace: StrategySpace = { schema: STRATEGY_SPACE_SCHEMA, engine: \"buy-plan\", version: \"1\", stages };\n\n const assess = (config: StrategyConfig): Assessed => {\n const breaks: { name: string; why: string }[] = [];\n const items: BuyItem[] = [];\n const records: Record<string, Readonly<Record<string, Fact>>> = { [NEED_KEY]: need.inputs ?? {} };\n for (const slot of need.slots) {\n const choice = config.stages[slot.name] ?? null;\n if (choice === null) {\n records[slot.name] = { slot: slot.name, count: 0, cost: 0 };\n continue;\n }\n const part = slot.parts.find((each) => each.key === choice.option) as NeedPart;\n const count = Number(choice.params?.[\"count\"] ?? Math.max(1, countOf(slot).min));\n const priced = prices.get(`${slot.name}\\u0000${part.key}`)?.get(count) ?? { ok: false, why: `The count ${String(count)} is not a count of the slot.` };\n if (!priced.ok) {\n breaks.push({ name: `price:${slot.name}`, why: `The part ${part.key} of the slot ${slot.name}: ${priced.why}` });\n records[slot.name] = { ...part.facts, slot: slot.name, part: part.key, count, cost: 0 };\n continue;\n }\n items.push({ slot: slot.name, part: part.key, count, offerId: priced.offerId, cost: priced.cost });\n records[slot.name] = { ...part.facts, slot: slot.name, part: part.key, count, cost: valueIn(priced.cost, need.currency) };\n }\n const price = breaks.length > 0 ? null : sum(items.map((item) => item.cost), need.currency);\n const values: Record<string, number> = price === null ? {} : { price: valueIn(price, need.currency) };\n const basket = space.record(records);\n for (const { measure, program } of measures) {\n const result = program.run({ space: basket, origin: NEED_KEY });\n if (!result.ok) breaks.push({ name: `measure:${measure.name}`, why: result.error.message });\n else if (typeof result.value !== \"number\" || !Number.isFinite(result.value)) breaks.push({ name: `measure:${measure.name}`, why: `The value ${String(result.value)} is not a finite number.` });\n else {\n values[measure.name] = result.value;\n if (measure.min !== undefined && result.value < measure.min) breaks.push({ name: `limit:${measure.name}`, why: `The value ${String(result.value)} is below the minimum ${String(measure.min)}.` });\n if (measure.max !== undefined && result.value > measure.max) breaks.push({ name: `limit:${measure.name}`, why: `The value ${String(result.value)} is above the maximum ${String(measure.max)}.` });\n }\n }\n for (const { rule, program } of rules) {\n const result = program.run({ space: basket, origin: NEED_KEY });\n if (!result.ok) breaks.push({ name: `rule:${rule.name}`, why: result.error.message });\n else if (result.value !== true) breaks.push({ name: `rule:${rule.name}`, why: result.value === false ? \"The basket breaks the rule.\" : `The value ${String(result.value)} is not a boolean.` });\n }\n return { breaks, values, price, items };\n };\n\n // The reason of the first basket that breaks each constraint.\n const firstWhy = new Map<string, string>();\n const evaluate = (config: StrategyConfig): Measure => {\n const assessed = assess(config);\n for (const { name, why } of assessed.breaks) if (!firstWhy.has(name)) firstWhy.set(name, why);\n return { breaks: [...new Set(assessed.breaks.map((each) => each.name))], values: assessed.values };\n };\n\n const levels = Math.max(1, ...need.slots.map((slot) => countOf(slot).max - Math.max(1, countOf(slot).min) + 1));\n const grid = spaceSize(strategySpace, { levels }).base <= BigInt(evaluations);\n const evaluator = `buy-need:${need.id}`;\n const run = grid\n ? sweep(strategySpace, { objectives, evaluate, enumerate: { mode: \"grid\", levels, limit: evaluations }, evaluator })\n : evolve(strategySpace, {\n objectives,\n evaluate,\n seed: options.seed ?? need.id,\n evaluations,\n ...(options.population === undefined ? {} : { population: options.population }),\n evaluator,\n });\n\n const front = frontOf(run)\n .map(({ row, config }): BuyChoice => {\n const assessed = assess(config);\n const values = Object.fromEntries(Object.entries(assessed.values).filter(([name]) => name !== \"price\"));\n return { config: row.config, price: assessed.price as Quantity, values, items: assessed.items };\n })\n .sort((a, b) => compare(a.price, b.price) || (a.config < b.config ? -1 : a.config > b.config ? 1 : 0));\n return {\n ...none,\n method: grid ? \"grid\" : \"evolve\",\n seed: run.seed,\n run: run.run,\n counts: run.counts,\n front,\n breaks: breaksOf(run.rows, firstWhy),\n unpriced,\n };\n}\n\n/** This function counts the rows that break each constraint, in the order of the names. */\nfunction breaksOf(rows: readonly EvaluationRow[], firstWhy: ReadonlyMap<string, string>): BuyBreak[] {\n const counts = new Map<string, number>();\n for (const row of rows) for (const name of row.breaks) counts.set(name, (counts.get(name) ?? 0) + 1);\n return [...counts.entries()]\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([name, count]) => ({ name, count, why: firstWhy.get(name) ?? \"\" }));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsDA,SAAgB,cAAc,OAA+B,cAAsC,SAA0C;CAC3I,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,aAA6B,CAAC;CACpC,MAAM,WAA+C,CAAC;CACtD,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,KAAK,IAAI,KAAK,OAAO,GAAG,MAAM,IAAI,WAAW,eAAe,KAAK,QAAQ,wBAAwB;EACrG,KAAK,IAAI,KAAK,OAAO;EACrB,MAAM,MAAM,KAAK,OAAO;EACxB,IAAI,EAAE,OAAO,cAAc,GAAG,KAAK,OAAO,IAAI,MAAM,IAAI,WAAW,0BAA0B,KAAK,QAAQ,MAAM,OAAO,GAAG,EAAE,0CAA0C;EACtK,MAAM,SAAS,QAAQ,aAAa,cAAc,KAAK,IAAI,GAAG,GAAG,OAAO;EACxE,IAAI,OAAO,IAAI,WAAW,KAAK;GAAE,SAAS,KAAK;GAAS,OAAO,QAAQ,OAAO,MAAM,QAAQ,QAAQ;GAAG;GAAK,OAAO,OAAO;EAAQ,CAAC;OAC9H,SAAS,KAAK;GAAE,SAAS,KAAK;GAAS,KAAK,OAAO;EAAI,CAAC;CAC/D;CACA,OAAO;EAAE,UAAU,QAAQ;EAAU;EAAY;CAAS;AAC5D;;;;;;;;;;;;;AAiEA,SAAgB,UAAU,YAAqC,SAAiC;CAC9F,IAAI,QAAQ,OAAO,WAAW,GAAG,MAAM,IAAI,WAAW,yBAAyB;CAC/E,IAAI,EAAE,OAAO,SAAS,QAAQ,MAAM,KAAK,QAAQ,UAAU,IAAI,MAAM,IAAI,WAAW,iBAAiB,OAAO,QAAQ,MAAM,EAAE,2CAA2C;CACvK,MAAM,YAA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
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { quantitySchema } from "@mark1russell7/quantity/schema";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
// src/gtin.ts
|
|
4
|
+
/**
|
|
5
|
+
* This module reads the GTIN of a product: a GTIN-8, a UPC-A (12 digits), an EAN-13 or a GTIN-14.
|
|
6
|
+
* The last digit is a check digit. The sum of the other digits, with the weights 3 and 1 from the right, gives it.
|
|
7
|
+
*/
|
|
8
|
+
const LENGTHS = /* @__PURE__ */ new Set([
|
|
9
|
+
8,
|
|
10
|
+
12,
|
|
11
|
+
13,
|
|
12
|
+
14
|
|
13
|
+
]);
|
|
14
|
+
/**
|
|
15
|
+
* This function gives the check digit of the digits of a GTIN without its last digit.
|
|
16
|
+
*
|
|
17
|
+
* @throws RangeError when the text has a character that is not a digit, or no character.
|
|
18
|
+
*/
|
|
19
|
+
function gtinCheckDigit(body) {
|
|
20
|
+
if (!/^\d+$/.test(body)) throw new RangeError(`The text ${JSON.stringify(body)} is not a string of digits.`);
|
|
21
|
+
let total = 0;
|
|
22
|
+
for (let i = 0; i < body.length; i += 1) {
|
|
23
|
+
const digit = body.charCodeAt(body.length - 1 - i) - 48;
|
|
24
|
+
total += i % 2 === 0 ? digit * 3 : digit;
|
|
25
|
+
}
|
|
26
|
+
return (10 - total % 10) % 10;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* This function gives the GTIN-14 form of a GTIN, or null. It removes the spaces and the hyphens first.
|
|
30
|
+
* It refuses a length other than 8, 12, 13 or 14 digits, a wrong check digit, and a GTIN of zeros only.
|
|
31
|
+
*/
|
|
32
|
+
function parseGtin(text) {
|
|
33
|
+
const digits = text.replace(/[\s-]/g, "");
|
|
34
|
+
if (!/^\d+$/.test(digits) || !LENGTHS.has(digits.length) || /^0+$/.test(digits)) return null;
|
|
35
|
+
if (gtinCheckDigit(digits.slice(0, -1)) !== Number(digits.slice(-1))) return null;
|
|
36
|
+
return digits.padStart(14, "0");
|
|
37
|
+
}
|
|
38
|
+
// src/records.ts
|
|
39
|
+
/**
|
|
40
|
+
* The conditions of an offer. A source maps its own condition to one of them, and it keeps its own text in
|
|
41
|
+
* the field `grade` of the offer.
|
|
42
|
+
*/
|
|
43
|
+
const CONDITIONS = [
|
|
44
|
+
"new",
|
|
45
|
+
"open-box",
|
|
46
|
+
"refurbished",
|
|
47
|
+
"used",
|
|
48
|
+
"for-parts",
|
|
49
|
+
"unknown"
|
|
50
|
+
];
|
|
51
|
+
/** The states of the stock of an offer at the time of a reading. */
|
|
52
|
+
const AVAILABILITIES = [
|
|
53
|
+
"in-stock",
|
|
54
|
+
"low-stock",
|
|
55
|
+
"out-of-stock",
|
|
56
|
+
"preorder",
|
|
57
|
+
"unknown"
|
|
58
|
+
];
|
|
59
|
+
/** The buying formats of an offer. In an auction, the price of a reading is the current bid. */
|
|
60
|
+
const FORMATS = ["fixed-price", "auction"];
|
|
61
|
+
/** This schema accepts a text with a character that is not a space, and with no space at an end. */
|
|
62
|
+
const textSchema = z.string().refine((text) => text !== "" && text === text.trim(), "The text is empty, or it has a space at an end.");
|
|
63
|
+
/** This schema accepts the name of a source: small letters, digits and hyphens, with a letter first. */
|
|
64
|
+
const sourceSchema = z.string().regex(/^[a-z][a-z0-9-]*$/, "The name of a source has small letters, digits and hyphens, with a letter first.");
|
|
65
|
+
/** This schema accepts a GTIN in its GTIN-14 form, with a correct check digit. `parseGtin` gives this form. */
|
|
66
|
+
const gtinSchema = z.string().refine((text) => /^\d{14}$/.test(text) && parseGtin(text) === text, "The GTIN is not a GTIN-14 with a correct check digit.");
|
|
67
|
+
/** This schema accepts an amount of money of zero or more, for example `{ "value": 129.99, "unit": "USD" }`. */
|
|
68
|
+
const moneySchema = quantitySchema("money", { nonnegative: true });
|
|
69
|
+
/** This schema accepts an instant in UTC in the ISO 8601 form, for example `2026-11-12T18:00:00Z`. */
|
|
70
|
+
const instantSchema = z.iso.datetime();
|
|
71
|
+
/** This schema accepts a part number of a maker. */
|
|
72
|
+
const partNumberSchema = z.strictObject({
|
|
73
|
+
brand: textSchema,
|
|
74
|
+
partNumber: textSchema
|
|
75
|
+
});
|
|
76
|
+
/** This schema accepts one specification as text, for example `{ "name": "Capacity", "value": "1 TB" }`. */
|
|
77
|
+
const specSchema = z.strictObject({
|
|
78
|
+
name: textSchema,
|
|
79
|
+
value: textSchema
|
|
80
|
+
});
|
|
81
|
+
/** This schema accepts a seller. A rating is the percent of good feedback and the count of the feedback. */
|
|
82
|
+
const sellerSchema = z.strictObject({
|
|
83
|
+
id: textSchema.optional(),
|
|
84
|
+
name: textSchema.optional(),
|
|
85
|
+
rating: z.strictObject({
|
|
86
|
+
percent: z.number().min(0).max(100),
|
|
87
|
+
count: z.int().nonnegative()
|
|
88
|
+
}).optional()
|
|
89
|
+
});
|
|
90
|
+
/** This schema accepts a product: one thing that a person can buy, with its identifiers and its specifications. */
|
|
91
|
+
const productSchema = z.strictObject({
|
|
92
|
+
id: textSchema,
|
|
93
|
+
title: textSchema,
|
|
94
|
+
brand: textSchema.optional(),
|
|
95
|
+
category: z.array(textSchema).optional(),
|
|
96
|
+
gtins: z.array(gtinSchema),
|
|
97
|
+
partNumbers: z.array(partNumberSchema),
|
|
98
|
+
specs: z.array(specSchema)
|
|
99
|
+
});
|
|
100
|
+
/** This function gives the id of an offer: the name of its source, a colon, and the id at the source. */
|
|
101
|
+
function offerId(source, sourceId) {
|
|
102
|
+
return `${source}:${sourceId}`;
|
|
103
|
+
}
|
|
104
|
+
/** This function gives the name of the source of an offer id: the text before the first colon. */
|
|
105
|
+
function sourceOfOffer(id) {
|
|
106
|
+
const colon = id.indexOf(":");
|
|
107
|
+
if (colon <= 0) throw new RangeError(`The offer id ${JSON.stringify(id)} has no source.`);
|
|
108
|
+
return id.slice(0, colon);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* This schema accepts an offer: one product at one seller. The offer has the identifiers that the source gives.
|
|
112
|
+
* `productId` names the product of the catalog after a match.
|
|
113
|
+
*/
|
|
114
|
+
const offerSchema = z.strictObject({
|
|
115
|
+
id: textSchema,
|
|
116
|
+
source: sourceSchema,
|
|
117
|
+
sourceId: textSchema,
|
|
118
|
+
productId: textSchema.optional(),
|
|
119
|
+
title: textSchema,
|
|
120
|
+
url: z.url({ protocol: /^https$/ }).optional(),
|
|
121
|
+
seller: sellerSchema,
|
|
122
|
+
condition: z.enum(CONDITIONS),
|
|
123
|
+
grade: textSchema.optional(),
|
|
124
|
+
format: z.enum(FORMATS),
|
|
125
|
+
endsAt: instantSchema.optional(),
|
|
126
|
+
gtins: z.array(gtinSchema),
|
|
127
|
+
partNumbers: z.array(partNumberSchema),
|
|
128
|
+
specs: z.array(specSchema)
|
|
129
|
+
}).refine((offer) => offer.id === offerId(offer.source, offer.sourceId), {
|
|
130
|
+
message: "The id of an offer is its source and its source id, with a colon between them.",
|
|
131
|
+
path: ["id"]
|
|
132
|
+
});
|
|
133
|
+
/** This schema accepts the shipping of a reading. A calculated cost depends on the address of the buyer. */
|
|
134
|
+
const shippingSchema = z.discriminatedUnion("kind", [
|
|
135
|
+
z.strictObject({ kind: z.literal("free") }),
|
|
136
|
+
z.strictObject({
|
|
137
|
+
kind: z.literal("fixed"),
|
|
138
|
+
cost: moneySchema
|
|
139
|
+
}),
|
|
140
|
+
z.strictObject({ kind: z.literal("calculated") }),
|
|
141
|
+
z.strictObject({ kind: z.literal("unknown") })
|
|
142
|
+
]);
|
|
143
|
+
/** This schema accepts a price break: the unit price for an order of `quantity` units or more. */
|
|
144
|
+
const priceBreakSchema = z.strictObject({
|
|
145
|
+
quantity: z.int().min(2),
|
|
146
|
+
unitPrice: moneySchema
|
|
147
|
+
});
|
|
148
|
+
/**
|
|
149
|
+
* This schema accepts a price reading: the state of one offer at one instant. `price` is the unit price for an
|
|
150
|
+
* order of `minimumQuantity` units, or of one unit. The quantities of the breaks increase, and each is more
|
|
151
|
+
* than the minimum.
|
|
152
|
+
*/
|
|
153
|
+
const priceReadingSchema = z.strictObject({
|
|
154
|
+
offerId: textSchema,
|
|
155
|
+
at: instantSchema,
|
|
156
|
+
price: moneySchema,
|
|
157
|
+
listPrice: moneySchema.optional(),
|
|
158
|
+
shipping: shippingSchema,
|
|
159
|
+
availability: z.enum(AVAILABILITIES),
|
|
160
|
+
available: z.int().nonnegative().optional(),
|
|
161
|
+
minimumQuantity: z.int().min(1).optional(),
|
|
162
|
+
priceBreaks: z.array(priceBreakSchema).optional()
|
|
163
|
+
}).superRefine((reading, context) => {
|
|
164
|
+
let last = reading.minimumQuantity ?? 1;
|
|
165
|
+
for (const [index, entry] of (reading.priceBreaks ?? []).entries()) {
|
|
166
|
+
if (entry.quantity <= last) context.addIssue({
|
|
167
|
+
code: "custom",
|
|
168
|
+
message: `The break ${index} has the quantity ${entry.quantity}, which is not more than ${last}.`,
|
|
169
|
+
path: [
|
|
170
|
+
"priceBreaks",
|
|
171
|
+
index,
|
|
172
|
+
"quantity"
|
|
173
|
+
]
|
|
174
|
+
});
|
|
175
|
+
last = Math.max(last, entry.quantity);
|
|
176
|
+
}
|
|
177
|
+
const { availability, available } = reading;
|
|
178
|
+
if (available === void 0 || availability === "unknown" || availability === "preorder") return;
|
|
179
|
+
if (availability === "out-of-stock" !== (available === 0)) context.addIssue({
|
|
180
|
+
code: "custom",
|
|
181
|
+
message: `The availability ${availability} does not agree with the count ${available}.`,
|
|
182
|
+
path: ["available"]
|
|
183
|
+
});
|
|
184
|
+
});
|
|
185
|
+
export { specSchema as _, instantSchema as a, parseGtin as b, offerSchema as c, priceReadingSchema as d, productSchema as f, sourceSchema as g, sourceOfOffer as h, gtinSchema as i, partNumberSchema as l, shippingSchema as m, CONDITIONS as n, moneySchema as o, sellerSchema as p, FORMATS as r, offerId as s, AVAILABILITIES as t, priceBreakSchema as u, textSchema as v, gtinCheckDigit as y };
|
|
186
|
+
|
|
187
|
+
//# sourceMappingURL=records-W6sPyhTQ.js.map
|