@mark1russell7/market 0.1.5 → 0.1.7
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 +47 -0
- package/build/index.js +1 -1
- package/build/order-BAbk8QQA.d.ts +106 -0
- package/build/order-BAbk8QQA.d.ts.map +1 -0
- package/build/plan.d.ts +2 -0
- package/build/plan.d.ts.map +1 -1
- package/build/plan.js +109 -36
- package/build/plan.js.map +1 -1
- package/build/{records-hK1UCmpm.js → records-DU5uvTYJ.js} +35 -2
- package/build/records-DU5uvTYJ.js.map +1 -0
- package/build/supplies-entry.d.ts +135 -0
- package/build/supplies-entry.d.ts.map +1 -0
- package/build/supplies-entry.js +348 -0
- package/build/supplies-entry.js.map +1 -0
- package/package.json +8 -2
- package/build/records-hK1UCmpm.js.map +0 -1
package/README.md
CHANGED
|
@@ -112,6 +112,53 @@ const plan = planBuys(need, observations);
|
|
|
112
112
|
plan.front.map((choice) => [choice.price.value, choice.values["minutes"]]); // [[120, 20], [200, 50], [280, 80], [420, 100]]
|
|
113
113
|
```
|
|
114
114
|
|
|
115
|
+
## A buy order under a budget
|
|
116
|
+
|
|
117
|
+
A buy order chooses units of products, one unit at a time, under a budget. Each step buys the unit with the largest gain for each unit of money. The choice is `greedy` of `@mark1russell7/strategy-search`. The module knows no topic: the caller gives the value of a choice as a function.
|
|
118
|
+
|
|
119
|
+
- `buyCandidates(wants, observations, { currency, conditions })` gives a candidate for each product with a usable offer. The price is the cost of one unit with its shipping, from the in-stock offer with the lowest cost. Each unit is one order, so the price is an upper limit of the cost of more units. `unpriced` names each product with no usable offer.
|
|
120
|
+
- `orderBuys(candidates, { budget, stages, goal, start })` gives the order. Each stage has a name and a value function. A stage starts from the units of the stage before it, with the money that is left.
|
|
121
|
+
- **The value.** A value is a list of numbers, the most important number first. Thus a gain on the first number comes before each gain on the second number. With `goal: "min"`, a smaller value is better, as for a shortfall.
|
|
122
|
+
- **The stops.** A stage stops at `budget` when no unit fits the money that is left. It stops at `units` when each product is at its `max`. It stops at `no-gain` when no unit has a gain.
|
|
123
|
+
- **The bound.** With gains that do not increase as the order grows, the order holds at least `(1 - 1/e) / 2` of the best value. When two products give more together than apart, set `lazy` to `false`.
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
import { orderBuys, type BuyCandidate } from "@mark1russell7/market/plan";
|
|
127
|
+
|
|
128
|
+
const candidates: BuyCandidate[] = [
|
|
129
|
+
{ product: "JUG", price: 4, max: 10, quote: "a:1" },
|
|
130
|
+
{ product: "CAN", price: 1, max: 10, quote: "a:2" },
|
|
131
|
+
];
|
|
132
|
+
// The days short of a target: water first, then food. A jug gives 4/3 days, and a can gives 1 day.
|
|
133
|
+
const short = (target: number) => (units: Readonly<Record<string, number>>) => [Math.max(0, target - ((units["JUG"] ?? 0) * 4) / 3), Math.max(0, target - (units["CAN"] ?? 0))];
|
|
134
|
+
const order = orderBuys(candidates, { budget: 15, goal: "min", stages: [{ name: "2 days", value: short(2) }, { name: "5 days", value: short(5) }] });
|
|
135
|
+
order.units; // { JUG: 3, CAN: 3 }
|
|
136
|
+
order.stages.map((stage) => stage.spent); // [10, 5]
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## A catalog of supplies
|
|
140
|
+
|
|
141
|
+
The entry `@mark1russell7/market/supplies` has the format and the gate of a catalog of supplies: the products that a household keeps for an emergency. It is an add-on: the core of the package names no supply.
|
|
142
|
+
|
|
143
|
+
- A product has a kind (`water`, `food`, `power`, `light`, `heat`, `first-aid` or `communication`), the resources that one unit gives, its shelf life and, as an option, a part for the offers.
|
|
144
|
+
- Each amount has a cited fact, the definition of the product, or a no read with its reason. A no read is not 0.
|
|
145
|
+
- The facts and their sources are the records of [`@mark1russell7/guidebook`](https://www.npmjs.com/package/@mark1russell7/guidebook). Its gate examines each license and each address.
|
|
146
|
+
- The shelf life of a food is the id of a product of the FoodKeeper data of USDA FSIS. The entry `/foodkeeper` of `@mark1russell7/stock` gives its due rule.
|
|
147
|
+
- The resource codes are the codes of a store of `@mark1russell7/stack-endurance`, for example `water.stored` in `L`.
|
|
148
|
+
- The gate does not examine the joins to other packages. It does not find a FoodKeeper id that is not in `@mark1russell7/stock`, or a resource code that a layer of stores does not have. The code that joins the catalog to stock or to a layer of stores gives those gates. market depends on neither package.
|
|
149
|
+
|
|
150
|
+
| Function | What it does |
|
|
151
|
+
| --- | --- |
|
|
152
|
+
| `checkSupplies(catalog, options)` | It gives the findings of the catalog: the errors of the gate, and a warning for each no read and for each fact or source that no product uses. |
|
|
153
|
+
| `supplyWants(catalog, max)` | It gives the wants of the products with a part, for `buyCandidates`. A product with no part has no offer, so it has no price. |
|
|
154
|
+
| `giftsOf(catalog, id, units)` | It gives the resources of a count of units, each in the unit of its resource. A unit converts exactly, so 1 gal gives 3.785411784 L. |
|
|
155
|
+
|
|
156
|
+
`SUPPLY_CATALOG` is the reference catalog. Its facts come from Ready.gov (FEMA, a US federal work) and from FoodData Central (USDA, CC0 1.0). It has gaps:
|
|
157
|
+
|
|
158
|
+
- The energy of the power bank is no read. The page of the maker gives 24,000 mAh and no Wh, and a charge does not convert to energy without its voltage.
|
|
159
|
+
- The kinds `light`, `heat`, `first-aid` and `communication` have no product yet.
|
|
160
|
+
- The shelf life of commercially bottled water is no read. The source gives no time, so the date on the label applies.
|
|
161
|
+
|
|
115
162
|
## Metered prices
|
|
116
163
|
|
|
117
164
|
A cloud resource has a metered price: a price for each unit of an amount that the provider meters. A metered amount is a `time` (the hours of a machine), a `data-time` (stored data in GiB-months), a `data` (a transfer) or a `count` (requests).
|
package/build/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { D as matchKeys, E as foldCode, O as gtinCheckDigit, S as offersPart, T as unitPriceFor, _ as specSchema, a as instantSchema, b as latestObservations, c as offerSchema, d as priceReadingSchema, f as productSchema, g as sourceSchema, h as sourceOfOffer, i as gtinSchema, k as parseGtin, l as partNumberSchema, m as shippingSchema, n as CONDITIONS, o as moneySchema, p as sellerSchema, r as FORMATS, s as offerId, t as AVAILABILITIES, u as priceBreakSchema, v as textSchema, w as costOf, x as offersOfPart, y as bestOffer } from "./records-DU5uvTYJ.js";
|
|
2
2
|
import { UnitError, canonicalUnit, convertExact, convertible, parseUnit, quantity, rationals, valueIn } from "@mark1russell7/quantity";
|
|
3
3
|
import { quantitySchema } from "@mark1russell7/quantity/schema";
|
|
4
4
|
import { z } from "zod";
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { a as PartWant, p as Condition, r as Observation } from "./offers-CVUAcRHs.js";
|
|
2
|
+
import { Goal, GreedyStop, Selection } from "@mark1russell7/strategy-search";
|
|
3
|
+
/** One product that a buyer wants: its key, the part that the offers must match, and the largest count of its units. */
|
|
4
|
+
interface ProductWant {
|
|
5
|
+
readonly product: string;
|
|
6
|
+
readonly want: PartWant;
|
|
7
|
+
/** The largest count of units to buy. The default is 1. */
|
|
8
|
+
readonly max?: number | undefined;
|
|
9
|
+
}
|
|
10
|
+
/** One candidate of a buy order: a product, the price of one unit, the largest count of units and the offer. */
|
|
11
|
+
interface BuyCandidate {
|
|
12
|
+
readonly product: string;
|
|
13
|
+
/** The cost of one unit with its shipping, in the currency of the order. */
|
|
14
|
+
readonly price: number;
|
|
15
|
+
readonly max: number;
|
|
16
|
+
/** The `id` of the offer of the price. */
|
|
17
|
+
readonly quote: string;
|
|
18
|
+
}
|
|
19
|
+
/** The candidates of a buy order, and the products that have no usable offer. */
|
|
20
|
+
interface BuyCandidates {
|
|
21
|
+
readonly currency: string;
|
|
22
|
+
readonly candidates: readonly BuyCandidate[];
|
|
23
|
+
readonly unpriced: readonly {
|
|
24
|
+
readonly product: string;
|
|
25
|
+
readonly why: string;
|
|
26
|
+
}[];
|
|
27
|
+
}
|
|
28
|
+
/** The options of the candidates: the currency and the conditions that the buyer accepts. */
|
|
29
|
+
interface CandidateOptions {
|
|
30
|
+
/** The currency of the prices, a unit of money of `@mark1russell7/quantity`, for example `USD`. */
|
|
31
|
+
readonly currency: string;
|
|
32
|
+
/** The conditions that the buyer accepts. The default is `new` only. */
|
|
33
|
+
readonly conditions?: readonly Condition[] | undefined;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* This function gives a candidate for each product with a usable offer. The price is the cost of one unit with its
|
|
37
|
+
* shipping, from the in-stock offer with the lowest cost, as in `planBuys`. Each unit is one order, so the price is an
|
|
38
|
+
* upper limit of the cost of more units.
|
|
39
|
+
*
|
|
40
|
+
* @param wants - The products, in the order of the result
|
|
41
|
+
* @param observations - The observations of the offers
|
|
42
|
+
* @param options - The currency and the conditions
|
|
43
|
+
* @throws RangeError when the currency is not a unit of money, or when a product is twice in `wants`
|
|
44
|
+
*/
|
|
45
|
+
declare function buyCandidates(wants: readonly ProductWant[], observations: readonly Observation[], options: CandidateOptions): BuyCandidates;
|
|
46
|
+
/** One stage of a buy order: its name and the value of a choice, the most important number first. */
|
|
47
|
+
interface OrderStage {
|
|
48
|
+
readonly name: string;
|
|
49
|
+
/** The value of the units of each product. It is a pure function. */
|
|
50
|
+
readonly value: (units: Selection) => readonly number[];
|
|
51
|
+
}
|
|
52
|
+
/** The options of a buy order. */
|
|
53
|
+
interface OrderOptions {
|
|
54
|
+
/** The money of the order, in the currency of the candidates. */
|
|
55
|
+
readonly budget: number;
|
|
56
|
+
/** The stages, in order. Each stage starts from the units of the stage before it, with the money that is left. */
|
|
57
|
+
readonly stages: readonly OrderStage[];
|
|
58
|
+
/** The goal of each number of a value. Use `min` for a shortfall. The default is `max`. */
|
|
59
|
+
readonly goal?: Goal | undefined;
|
|
60
|
+
/** The units that the buyer has before the order. Their cost is not in the budget. */
|
|
61
|
+
readonly start?: Selection | undefined;
|
|
62
|
+
/** With `false`, each step evaluates each product again. Use it when two products give more together than apart. */
|
|
63
|
+
readonly lazy?: boolean | undefined;
|
|
64
|
+
}
|
|
65
|
+
/** One purchase of a buy order: one unit of a product, its offer and its cost, and its gain in its stage. */
|
|
66
|
+
interface OrderBuy {
|
|
67
|
+
readonly stage: string;
|
|
68
|
+
readonly product: string;
|
|
69
|
+
readonly quote: string;
|
|
70
|
+
readonly cost: number;
|
|
71
|
+
readonly gain: readonly number[];
|
|
72
|
+
}
|
|
73
|
+
/** The result of one stage: the value before and after it, the money that it spends and the reason that it stops. */
|
|
74
|
+
interface OrderStageResult {
|
|
75
|
+
readonly name: string;
|
|
76
|
+
readonly method: "greedy" | "single";
|
|
77
|
+
readonly before: readonly number[];
|
|
78
|
+
readonly after: readonly number[];
|
|
79
|
+
readonly spent: number;
|
|
80
|
+
readonly stop: GreedyStop;
|
|
81
|
+
readonly evaluations: number;
|
|
82
|
+
}
|
|
83
|
+
/** A buy order: the purchases in the order of the choice, the units of each product, and the result of each stage. */
|
|
84
|
+
interface BuyOrder {
|
|
85
|
+
readonly budget: number;
|
|
86
|
+
readonly spent: number;
|
|
87
|
+
readonly buys: readonly OrderBuy[];
|
|
88
|
+
/** The units of each product after the order, with the units of `start`. */
|
|
89
|
+
readonly units: Selection;
|
|
90
|
+
readonly stages: readonly OrderStageResult[];
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* This function calculates a buy order with a budgeted greedy choice in each stage. Each step buys one unit of the
|
|
94
|
+
* product with the largest gain for each unit of money. The choice is `greedy` of `@mark1russell7/strategy-search`.
|
|
95
|
+
*
|
|
96
|
+
* - A stage starts from the units of the stage before it, and it spends only the money that is left.
|
|
97
|
+
* - A stage can give the best single unit in place of its steps, when that unit has a better value (`method: "single"`).
|
|
98
|
+
*
|
|
99
|
+
* @param candidates - The candidates, from `buyCandidates`
|
|
100
|
+
* @param options - The budget, the stages, the goal and the start
|
|
101
|
+
* @returns The buy order
|
|
102
|
+
* @throws RangeError when the options are bad, or when a value is not a list of finite numbers with one length
|
|
103
|
+
*/
|
|
104
|
+
declare function orderBuys(candidates: readonly BuyCandidate[], options: OrderOptions): BuyOrder;
|
|
105
|
+
export { OrderBuy as a, OrderStageResult as c, orderBuys as d, CandidateOptions as i, ProductWant as l, BuyCandidates as n, OrderOptions as o, BuyOrder as r, OrderStage as s, BuyCandidate as t, buyCandidates as u };
|
|
106
|
+
//# sourceMappingURL=order-BAbk8QQA.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"order-BAbk8QQA.d.ts","names":[],"sources":["../src/order.ts"],"mappings":";;;UAYiB;WACN;WACA,MAAM;;WAEN;;;UAIM;WACN;;WAEA;WACA;;WAEA;;;UAIM;WACN;WACA,qBAAqB;WACrB;aAA8B;aAA0B;;;;UAIlD;;WAEN;;WAEA,sBAAsB;;;;;;;;;;;;iBAajB,cAAc,gBAAgB,eAAe,uBAAuB,eAAe,SAAS,mBAAmB;;UAiB9G;WACN;;WAEA,QAAQ,OAAO;;;UAIT;;WAEN;;WAEA,iBAAiB;;WAEjB,OAAO;;WAEP,QAAQ;;WAER;;;UAIM;WACN;WACA;WACA;WACA;WACA;;;UAIM;WACN;WACA;WACA;WACA;WACA;WACA,MAAM;WACN;;;UAIM;WACN;WACA;WACA,eAAe;;WAEf,OAAO;WACP,iBAAiB;;;;;;;;;;;;;;iBAeZ,UAAU,qBAAqB,gBAAgB,SAAS,eAAe"}
|
package/build/plan.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { a as PartWant, p as Condition, r as Observation } from "./offers-CVUAcRHs.js";
|
|
2
|
+
import { a as OrderBuy, c as OrderStageResult, d as orderBuys, i as CandidateOptions, l as ProductWant, n as BuyCandidates, o as OrderOptions, r as BuyOrder, s as OrderStage, t as BuyCandidate, u as buyCandidates } from "./order-BAbk8QQA.js";
|
|
2
3
|
import { Quantity } from "@mark1russell7/quantity";
|
|
3
4
|
import { z } from "zod";
|
|
4
5
|
import { Objective, SweepCounts } from "@mark1russell7/strategy-search";
|
|
@@ -148,4 +149,5 @@ export interface PlanOptions {
|
|
|
148
149
|
* The function also throws a RangeError when strategy-search refuses the options.
|
|
149
150
|
*/
|
|
150
151
|
export declare function planBuys(need: BuyNeed, observations: readonly Observation[], options?: PlanOptions): BuyPlan;
|
|
152
|
+
export { type BuyCandidate, type BuyCandidates, type BuyOrder, type CandidateOptions, type OrderBuy, type OrderOptions, type OrderStage, type OrderStageResult, type ProductWant, buyCandidates, orderBuys };
|
|
151
153
|
//# sourceMappingURL=plan.d.ts.map
|
package/build/plan.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plan.d.ts","names":[],"sources":["../src/plan.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"plan.d.ts","names":[],"sources":["../src/plan.ts"],"mappings":";;;;;;qBAiBa;;qBAGA;;qBAGA;;qBAGA;;qBAGA;;YAMD;;iBAGK;WACN;WACA,MAAM;;WAEN,QAAQ,SAAS,eAAe;;;iBAI1B;WACN;WACA;;;iBAIM;WACN;WACA,gBAAgB;WAChB,QAAQ;;;;;;iBAOF;WACN;;WAEA;WACA;;WAEA;WACA;WACA;;;iBAIM;WACN;;WAEA;;;iBAIM;WACN,eAAe;WACf;;WAEA;;WAEA,sBAAsB;;WAEtB,SAAS,SAAS,eAAe;WACjC,gBAAgB;WAChB,oBAAoB;WACpB,iBAAiB;;;qBASf,eAAe,EAAE,QAAQ;;;;;;wBAuDtB,aAAa,MAAM;;iBAuDlB;WACN;WACA;WACA;WACA;WACA,MAAM;;;iBAIA;WACN;;WAEA,OAAO;WACP,QAAQ,SAAS;WACjB,gBAAgB;;;iBAIV;;WAEN;WACA;WACA;;;iBAIM;WACN;WACA;WACA;;;iBAIM;WACN,eAAe;;WAEf;WACA;;WAEA;;WAEA;;WAEA;WACA,qBAAqB;WACrB,QAAQ;;WAER,gBAAgB;;WAEhB,iBAAiB;;WAEjB,mBAAmB;;;iBAMb;;WAEN;;WAEA;;WAEA;;;;;;;;;;;;;;;;wBA2BK,SAAS,MAAM,SAAS,uBAAuB,eAAe,UAAS,cAAmB"}
|
package/build/plan.js
CHANGED
|
@@ -1,10 +1,116 @@
|
|
|
1
|
-
import { n as CONDITIONS, v as textSchema, x as offersOfPart
|
|
1
|
+
import { C as priceOf, n as CONDITIONS, v as textSchema, x as offersOfPart } from "./records-DU5uvTYJ.js";
|
|
2
2
|
import { compare, sum, valueIn } from "@mark1russell7/quantity";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
-
import { evolve, frontOf, sweep } from "@mark1russell7/strategy-search";
|
|
4
|
+
import { evolve, frontOf, greedy, sweep } from "@mark1russell7/strategy-search";
|
|
5
5
|
import { STRATEGY_SPACE_SCHEMA, spaceSize } from "@mark1russell7/strategy-space";
|
|
6
6
|
import { compile, isFieldName, parse, space } from "@mark1russell7/vex";
|
|
7
7
|
import { BoolDomain, NumDomain, TextDomain } from "@mark1russell7/vex-domains";
|
|
8
|
+
// src/order.ts
|
|
9
|
+
/**
|
|
10
|
+
* This function gives a candidate for each product with a usable offer. The price is the cost of one unit with its
|
|
11
|
+
* shipping, from the in-stock offer with the lowest cost, as in `planBuys`. Each unit is one order, so the price is an
|
|
12
|
+
* upper limit of the cost of more units.
|
|
13
|
+
*
|
|
14
|
+
* @param wants - The products, in the order of the result
|
|
15
|
+
* @param observations - The observations of the offers
|
|
16
|
+
* @param options - The currency and the conditions
|
|
17
|
+
* @throws RangeError when the currency is not a unit of money, or when a product is twice in `wants`
|
|
18
|
+
*/
|
|
19
|
+
function buyCandidates(wants, observations, options) {
|
|
20
|
+
const seen = /* @__PURE__ */ new Set();
|
|
21
|
+
const candidates = [];
|
|
22
|
+
const unpriced = [];
|
|
23
|
+
for (const want of wants) {
|
|
24
|
+
if (seen.has(want.product)) throw new RangeError(`The product ${want.product} is twice in the wants.`);
|
|
25
|
+
seen.add(want.product);
|
|
26
|
+
const max = want.max ?? 1;
|
|
27
|
+
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.`);
|
|
28
|
+
const priced = priceOf(offersOfPart(observations, want.want), 1, options);
|
|
29
|
+
if (priced.ok) candidates.push({
|
|
30
|
+
product: want.product,
|
|
31
|
+
price: valueIn(priced.cost, options.currency),
|
|
32
|
+
max,
|
|
33
|
+
quote: priced.offerId
|
|
34
|
+
});
|
|
35
|
+
else unpriced.push({
|
|
36
|
+
product: want.product,
|
|
37
|
+
why: priced.why
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
currency: options.currency,
|
|
42
|
+
candidates,
|
|
43
|
+
unpriced
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* This function calculates a buy order with a budgeted greedy choice in each stage. Each step buys one unit of the
|
|
48
|
+
* product with the largest gain for each unit of money. The choice is `greedy` of `@mark1russell7/strategy-search`.
|
|
49
|
+
*
|
|
50
|
+
* - A stage starts from the units of the stage before it, and it spends only the money that is left.
|
|
51
|
+
* - A stage can give the best single unit in place of its steps, when that unit has a better value (`method: "single"`).
|
|
52
|
+
*
|
|
53
|
+
* @param candidates - The candidates, from `buyCandidates`
|
|
54
|
+
* @param options - The budget, the stages, the goal and the start
|
|
55
|
+
* @returns The buy order
|
|
56
|
+
* @throws RangeError when the options are bad, or when a value is not a list of finite numbers with one length
|
|
57
|
+
*/
|
|
58
|
+
function orderBuys(candidates, options) {
|
|
59
|
+
if (options.stages.length === 0) throw new RangeError("The order has no stage.");
|
|
60
|
+
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.`);
|
|
61
|
+
const byProduct = new Map(candidates.map((candidate) => [candidate.product, candidate]));
|
|
62
|
+
const items = candidates.map((candidate) => ({
|
|
63
|
+
id: candidate.product,
|
|
64
|
+
cost: candidate.price,
|
|
65
|
+
max: candidate.max
|
|
66
|
+
}));
|
|
67
|
+
const start = options.start ?? {};
|
|
68
|
+
let units = start;
|
|
69
|
+
let left = options.budget;
|
|
70
|
+
let spent = 0;
|
|
71
|
+
const buys = [];
|
|
72
|
+
const stages = [];
|
|
73
|
+
for (const stage of options.stages) {
|
|
74
|
+
const open = items.map((item) => ({
|
|
75
|
+
...item,
|
|
76
|
+
max: item.max - ((units[item.id] ?? 0) - (start[item.id] ?? 0))
|
|
77
|
+
}));
|
|
78
|
+
const run = greedy({
|
|
79
|
+
items: open,
|
|
80
|
+
budget: Math.max(0, left),
|
|
81
|
+
value: stage.value,
|
|
82
|
+
start: units,
|
|
83
|
+
...options.goal === void 0 ? {} : { goal: options.goal },
|
|
84
|
+
...options.lazy === void 0 ? {} : { lazy: options.lazy }
|
|
85
|
+
});
|
|
86
|
+
for (const pick of run.picks) buys.push({
|
|
87
|
+
stage: stage.name,
|
|
88
|
+
product: pick.id,
|
|
89
|
+
quote: byProduct.get(pick.id)?.quote ?? "",
|
|
90
|
+
cost: pick.cost,
|
|
91
|
+
gain: pick.gain
|
|
92
|
+
});
|
|
93
|
+
units = run.selection;
|
|
94
|
+
left -= run.spent;
|
|
95
|
+
spent += run.spent;
|
|
96
|
+
stages.push({
|
|
97
|
+
name: stage.name,
|
|
98
|
+
method: run.method,
|
|
99
|
+
before: run.before,
|
|
100
|
+
after: run.after,
|
|
101
|
+
spent: run.spent,
|
|
102
|
+
stop: run.stop,
|
|
103
|
+
evaluations: run.evaluations
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
budget: options.budget,
|
|
108
|
+
spent,
|
|
109
|
+
buys,
|
|
110
|
+
units,
|
|
111
|
+
stages
|
|
112
|
+
};
|
|
113
|
+
}
|
|
8
114
|
// src/plan.ts
|
|
9
115
|
/** The format name of a need record. */
|
|
10
116
|
const NEED_FORMAT = "buy-need/1";
|
|
@@ -141,39 +247,6 @@ function needProblems(need) {
|
|
|
141
247
|
return problems;
|
|
142
248
|
}
|
|
143
249
|
/**
|
|
144
|
-
* This function chooses the offer to buy for a count of a part: the in-stock offer with the lowest cost, with the
|
|
145
|
-
* shipping. An offer with a cost that is not known is not usable. Equal costs keep the order of `bestOffer`.
|
|
146
|
-
*/
|
|
147
|
-
function priceOf(observations, count, need) {
|
|
148
|
-
const choice = bestOffer(observations, {
|
|
149
|
-
currency: need.currency,
|
|
150
|
-
count,
|
|
151
|
-
...need.conditions === void 0 ? {} : { conditions: need.conditions }
|
|
152
|
-
});
|
|
153
|
-
let pick;
|
|
154
|
-
for (const offer of choice.offers) {
|
|
155
|
-
const cost = offer.cost;
|
|
156
|
-
if (offer.inStock && cost !== null && (pick === void 0 || compare(cost, pick.cost) < 0)) pick = {
|
|
157
|
-
...offer,
|
|
158
|
-
cost
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
if (pick !== void 0) return {
|
|
162
|
-
ok: true,
|
|
163
|
-
offerId: pick.observation.offer.id,
|
|
164
|
-
cost: pick.cost
|
|
165
|
-
};
|
|
166
|
-
if (choice.offers.length > 0) return {
|
|
167
|
-
ok: false,
|
|
168
|
-
why: `No offer of ${String(count)} units is in stock with a known cost.`
|
|
169
|
-
};
|
|
170
|
-
const first = choice.skipped[0];
|
|
171
|
-
return {
|
|
172
|
-
ok: false,
|
|
173
|
-
why: first === void 0 ? "No offer matches the part." : `No offer is usable. The first offer that the choice skipped: ${first.why}`
|
|
174
|
-
};
|
|
175
|
-
}
|
|
176
|
-
/**
|
|
177
250
|
* This function makes a buy plan from a need and the observations of the offers. Each slot is a stage of a strategy
|
|
178
251
|
* 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
|
|
179
252
|
* of the cost of each item.
|
|
@@ -435,6 +508,6 @@ function breaksOf(rows, firstWhy) {
|
|
|
435
508
|
why: firstWhy.get(name) ?? ""
|
|
436
509
|
}));
|
|
437
510
|
}
|
|
438
|
-
export { NEED_FORMAT, NEED_KEY, PLAN_EVALUATIONS, PLAN_FORMAT, SLOT_FIELDS, buyNeedSchema, needProblems, planBuys };
|
|
511
|
+
export { NEED_FORMAT, NEED_KEY, PLAN_EVALUATIONS, PLAN_FORMAT, SLOT_FIELDS, buyCandidates, buyNeedSchema, needProblems, orderBuys, planBuys };
|
|
439
512
|
|
|
440
513
|
//# sourceMappingURL=plan.js.map
|
package/build/plan.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plan.js","names":[],"sources":["../src/plan.ts"],"sourcesContent":["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 { bestOffer, offersOfPart, type Observation, type OfferChoice, type PartWant } 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\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/** The offer to buy for one count of a part, or the reason that no offer is usable. */\ntype Priced = { readonly ok: true; readonly offerId: string; readonly cost: Quantity } | { readonly ok: false; readonly why: string };\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 * 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 */\nfunction priceOf(observations: readonly Observation[], count: number, need: BuyNeed): 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\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":";;;;;;;;;AAiBA,MAAa,cAAc;;AAG3B,MAAa,cAAc;;AAG3B,MAAa,WAAW;;AAGxB,MAAa,cAAc;CAAC;CAAQ;CAAQ;CAAS;AAAM;;AAG3D,MAAa,mBAAmB;;AAGhC,MAAM,UAAgC;CAAC;CAAW;CAAY;AAAU;AA+DxE,MAAM,aAA8B,EAAE,MAAM;CAAC,EAAE,OAAO,CAAC,CAAC,OAAO,OAAO,UAAU,2BAA2B;CAAG,EAAE,OAAO;CAAG,EAAE,QAAQ;AAAC,CAAC;AACtI,MAAM,cAAyD,EAAE,OAAO,YAAY,UAAU;AAC9F,MAAM,aAAkC,EAAE,aAAa;CAAE,QAAQ,EAAE,MAAM,UAAU,CAAC,CAAC,IAAI,CAAC;CAAG,aAAa,EAAE,MAAM,UAAU,CAAC,CAAC,IAAI,CAAC;AAAE,CAAC;AACtI,MAAM,cAAc,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,YAAY;;AAGjD,MAAa,gBAAoC,EAAE,aAAa;CAC9D,QAAQ,EAAE,QAAQ,WAAW;CAC7B,IAAI;CACJ,UAAU;CACV,YAAY,EAAE,MAAM,EAAE,KAAK,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;CACxD,QAAQ,YAAY,SAAS;CAC7B,OAAO,EACJ,MACC,EAAE,aAAa;EACb,MAAM;EACN,OAAO,EAAE,MAAM,EAAE,aAAa;GAA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AAI,EAAE,YAAY,QAAQ,WAAW;EAC7E;CACF,CAAC;CAEL,MAAM,QAAQ,QAAQ,GAAG,CAAC,CACvB,KAAK,EAAE,KAAK,aAAwB;EACnC,MAAM,WAAW,OAAO,MAAM;EAC9B,MAAM,SAAS,OAAO,YAAY,OAAO,QAAQ,SAAS,MAAM,CAAC,CAAC,QAAQ,CAAC,UAAU,SAAS,OAAO,CAAC;EACtG,OAAO;GAAE,QAAQ,IAAI;GAAQ,OAAO,SAAS;GAAmB;GAAQ,OAAO,SAAS;EAAM;CAChG,CAAC,CAAC,CACD,MAAM,GAAG,MAAM,QAAQ,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,SAAS,EAAE,SAAS,KAAK,EAAE,SAAS,EAAE,SAAS,IAAI,EAAE;CACvG,OAAO;EACL,GAAG;EACH,QAAQ,OAAO,SAAS;EACxB,MAAM,IAAI;EACV,KAAK,IAAI;EACT,QAAQ,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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G,OAAO;EACL,GAAG;EACH,QAAQ,OAAO,SAAS;EACxB,MAAM,IAAI;EACV,KAAK,IAAI;EACT,QAAQ,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"}
|
|
@@ -194,6 +194,39 @@ function byCost(a, b) {
|
|
|
194
194
|
function order(a, b) {
|
|
195
195
|
return a < b ? -1 : a > b ? 1 : 0;
|
|
196
196
|
}
|
|
197
|
+
/**
|
|
198
|
+
* This function chooses the offer to buy for a count of a part: the in-stock offer with the lowest cost, with the
|
|
199
|
+
* shipping. An offer with a cost that is not known is not usable. Equal costs keep the order of `bestOffer`.
|
|
200
|
+
*/
|
|
201
|
+
function priceOf(observations, count, need) {
|
|
202
|
+
const choice = bestOffer(observations, {
|
|
203
|
+
currency: need.currency,
|
|
204
|
+
count,
|
|
205
|
+
...need.conditions === void 0 ? {} : { conditions: need.conditions }
|
|
206
|
+
});
|
|
207
|
+
let pick;
|
|
208
|
+
for (const offer of choice.offers) {
|
|
209
|
+
const cost = offer.cost;
|
|
210
|
+
if (offer.inStock && cost !== null && (pick === void 0 || compare(cost, pick.cost) < 0)) pick = {
|
|
211
|
+
...offer,
|
|
212
|
+
cost
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
if (pick !== void 0) return {
|
|
216
|
+
ok: true,
|
|
217
|
+
offerId: pick.observation.offer.id,
|
|
218
|
+
cost: pick.cost
|
|
219
|
+
};
|
|
220
|
+
if (choice.offers.length > 0) return {
|
|
221
|
+
ok: false,
|
|
222
|
+
why: `No offer of ${String(count)} units is in stock with a known cost.`
|
|
223
|
+
};
|
|
224
|
+
const first = choice.skipped[0];
|
|
225
|
+
return {
|
|
226
|
+
ok: false,
|
|
227
|
+
why: first === void 0 ? "No offer matches the part." : `No offer is usable. The first offer that the choice skipped: ${first.why}`
|
|
228
|
+
};
|
|
229
|
+
}
|
|
197
230
|
// src/records.ts
|
|
198
231
|
/**
|
|
199
232
|
* The conditions of an offer. A source maps its own condition to one of them, and it keeps its own text in
|
|
@@ -341,6 +374,6 @@ const priceReadingSchema = z.strictObject({
|
|
|
341
374
|
path: ["available"]
|
|
342
375
|
});
|
|
343
376
|
});
|
|
344
|
-
export {
|
|
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 };
|
|
345
378
|
|
|
346
|
-
//# sourceMappingURL=records-
|
|
379
|
+
//# sourceMappingURL=records-DU5uvTYJ.js.map
|