@aglyn/plugins-commerce 1.26.5 → 1.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +13 -13
- package/src/lib/components/console/product-editor-dialog.component.js +4 -43
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/contracts.d.ts +7 -0
- package/src/lib/contracts.js.map +1 -1
- package/src/lib/model/product-write.d.ts +29 -8
- package/src/lib/model/product-write.js +64 -2
- package/src/lib/model/product-write.js.map +1 -1
- package/src/lib/native-nav.js +12 -1
- package/src/lib/native-nav.js.map +1 -1
- package/src/lib/server/api-v1/openapi.d.ts +6 -6
- package/src/lib/server/api-v1/openapi.js +203 -16
- package/src/lib/server/api-v1/openapi.js.map +1 -1
- package/src/lib/server/api-v1/order-view.d.ts +8 -0
- package/src/lib/server/api-v1/order-view.js +21 -4
- package/src/lib/server/api-v1/order-view.js.map +1 -1
- package/src/lib/server/api-v1/orders-and-products.js +46 -59
- package/src/lib/server/api-v1/orders-and-products.js.map +1 -1
- package/src/lib/server/api-v1/product-view.d.ts +76 -0
- package/src/lib/server/api-v1/product-view.js +86 -0
- package/src/lib/server/api-v1/product-view.js.map +1 -0
- package/src/lib/server/api-v1/product-writes.d.ts +149 -0
- package/src/lib/server/api-v1/product-writes.js +673 -0
- package/src/lib/server/api-v1/product-writes.js.map +1 -0
- package/src/lib/server/products-write.d.ts +94 -2
- package/src/lib/server/products-write.js +171 -112
- package/src/lib/server/products-write.js.map +1 -1
|
@@ -0,0 +1,673 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
/**
|
|
3
|
+
* @license
|
|
4
|
+
* Copyright 2026 Aglyn LLC
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/ import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
|
|
18
|
+
import { SCREEN_SEO_TEXT_GUIDANCE } from "@aglyn/aglyn/app-utils/screen-seo-fields";
|
|
19
|
+
import { dropPluginSiteCache } from "@aglyn/aglyn/plugin-manager/plugin-site-cache";
|
|
20
|
+
import { ApiErrors, apiJson } from "@aglyn/tenant-data-admin";
|
|
21
|
+
import { apiActorFields, claimWrite, readJsonBody } from "@aglyn/tenant-data-admin/server/api-v1-kit";
|
|
22
|
+
import { COMMERCE_MAX_OPTIONS, COMMERCE_SLUG_MAX_LENGTH, commerceSlug, liftLegacyProduct, renameProductOptions, stockTrackingApplies, variantMatrixProblem } from "../../model/commerce.js";
|
|
23
|
+
import { blankProductDraft, PRODUCT_NAME_MAX_LENGTH, variantComboKey, variantsForOptions } from "../../model/product-write.js";
|
|
24
|
+
import { claimProductSlug, deleteProduct, saveProduct } from "../products-write.js";
|
|
25
|
+
import { productView } from "./product-view.js";
|
|
26
|
+
/*
|
|
27
|
+
* A site's products, written over the customer REST API (AGL-4235):
|
|
28
|
+
* `POST /v1/sites/{siteId}/products`, `PATCH` and `DELETE` on one product,
|
|
29
|
+
* and `PATCH` on one of its variants.
|
|
30
|
+
*
|
|
31
|
+
* Every write here is the console editor's own, through `saveProduct` and
|
|
32
|
+
* `deleteProduct` — the functions the native apps' routes call — so a product
|
|
33
|
+
* saved by an integration carries exactly the search keys, stock verdict,
|
|
34
|
+
* price, image, smart-collection membership and cache drop the editor's
|
|
35
|
+
* save would have written, and meets the same checks.
|
|
36
|
+
*
|
|
37
|
+
* What a person can do in the editor is the boundary. Variants are the grid
|
|
38
|
+
* of a product's option values, rebuilt from the options as the editor
|
|
39
|
+
* rebuilds it (`variantsForOptions`); a person cannot add or remove one
|
|
40
|
+
* variant by itself, so neither can a caller. Stock is typed into the grid
|
|
41
|
+
* and written by the save, `null` for untracked and `0` for sold out.
|
|
42
|
+
*
|
|
43
|
+
* Every function here is pre-authorized: `handleProducts` asks the scope,
|
|
44
|
+
* the plan, the plugin's switch for the site and the person's permission
|
|
45
|
+
* before it calls one.
|
|
46
|
+
*/ /** The members a product write may carry, in the order the description lists them. */ export const PRODUCT_WRITABLE_KEYS = [
|
|
47
|
+
'name',
|
|
48
|
+
'description',
|
|
49
|
+
'status',
|
|
50
|
+
'type',
|
|
51
|
+
'slug',
|
|
52
|
+
'tags',
|
|
53
|
+
'categoryIds',
|
|
54
|
+
'mediaUrls',
|
|
55
|
+
'options',
|
|
56
|
+
'variants',
|
|
57
|
+
'seo'
|
|
58
|
+
];
|
|
59
|
+
/** The members a variant write may carry. */ export const VARIANT_WRITABLE_KEYS = [
|
|
60
|
+
'priceUsd',
|
|
61
|
+
'compareAtPriceUsd',
|
|
62
|
+
'sku',
|
|
63
|
+
'barcode',
|
|
64
|
+
'weightGrams',
|
|
65
|
+
'inventory'
|
|
66
|
+
];
|
|
67
|
+
/** What names the variant one entry of a product write's `variants` changes. */ const VARIANT_TARGET_KEYS = [
|
|
68
|
+
'id',
|
|
69
|
+
'options'
|
|
70
|
+
];
|
|
71
|
+
/** The search listing members a write may set. */ const SEO_WRITABLE_KEYS = [
|
|
72
|
+
'title',
|
|
73
|
+
'description'
|
|
74
|
+
];
|
|
75
|
+
/**
|
|
76
|
+
* The kinds of product a caller may make. A digital product delivers files a
|
|
77
|
+
* person uploads in the editor, so it is made there.
|
|
78
|
+
*/ export const PRODUCT_API_TYPES = [
|
|
79
|
+
'physical',
|
|
80
|
+
'service'
|
|
81
|
+
];
|
|
82
|
+
export const PRODUCT_DIGITAL_REFUSAL = 'A digital product delivers files uploaded in the console, so it is created and changed to digital there.';
|
|
83
|
+
export const PRODUCT_STATUSES = [
|
|
84
|
+
'draft',
|
|
85
|
+
'active',
|
|
86
|
+
'archived'
|
|
87
|
+
];
|
|
88
|
+
/** The stock a digital or service subscription cannot keep (AGL-1744), as the editor says it. */ export const PRODUCT_STOCK_NOT_TRACKED = 'Stock is not tracked on a digital or service subscription. Send `null` to clear it.';
|
|
89
|
+
const isPlainObject = (value)=>Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
90
|
+
/** Each key of `body` not in `allowed`, named for the 400. */ function unknownKeys(body, allowed, prefix = '') {
|
|
91
|
+
return Object.fromEntries(Object.keys(body).filter((key)=>!allowed.includes(key)).map((key)=>[
|
|
92
|
+
`${prefix}${key}`,
|
|
93
|
+
'Not writable here'
|
|
94
|
+
]));
|
|
95
|
+
}
|
|
96
|
+
/** A list of non-empty trimmed strings, or why not. */ function stringList(value) {
|
|
97
|
+
if (!Array.isArray(value)) return 'Must be an array of strings';
|
|
98
|
+
if (value.some((entry)=>typeof entry !== 'string')) return 'Must be an array of strings';
|
|
99
|
+
return value.map((entry)=>entry.trim()).filter(Boolean);
|
|
100
|
+
}
|
|
101
|
+
/** A number the field may hold, `null` to clear it, or why not. */ function amount(value, what) {
|
|
102
|
+
if (value === null) return null;
|
|
103
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return `${what} must be a number, zero or more, or null`;
|
|
104
|
+
return value;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* One variant's writable fields from a body (`VariantWrite`). With `target`,
|
|
108
|
+
* also the `id` or `options` that name which variant it is — an entry of a
|
|
109
|
+
* product write's `variants`.
|
|
110
|
+
*/ export function readVariantWrite(body, options = {}) {
|
|
111
|
+
var _options_prefix;
|
|
112
|
+
const prefix = (_options_prefix = options.prefix) != null ? _options_prefix : '';
|
|
113
|
+
if (!isPlainObject(body)) return {
|
|
114
|
+
errors: {
|
|
115
|
+
[prefix || 'body']: 'Must be an object'
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
const allowed = options.target ? [
|
|
119
|
+
...VARIANT_WRITABLE_KEYS,
|
|
120
|
+
...VARIANT_TARGET_KEYS
|
|
121
|
+
] : VARIANT_WRITABLE_KEYS;
|
|
122
|
+
const errors = unknownKeys(body, allowed, prefix);
|
|
123
|
+
const values = {};
|
|
124
|
+
for (const field of [
|
|
125
|
+
'priceUsd',
|
|
126
|
+
'compareAtPriceUsd',
|
|
127
|
+
'weightGrams'
|
|
128
|
+
]){
|
|
129
|
+
if (!(field in body)) continue;
|
|
130
|
+
const parsed = amount(body[field], field === 'weightGrams' ? 'A weight' : 'A price');
|
|
131
|
+
if (typeof parsed === 'string') errors[`${prefix}${field}`] = parsed;
|
|
132
|
+
else values[field] = parsed;
|
|
133
|
+
}
|
|
134
|
+
for (const field of [
|
|
135
|
+
'sku',
|
|
136
|
+
'barcode'
|
|
137
|
+
]){
|
|
138
|
+
if (!(field in body)) continue;
|
|
139
|
+
const raw = body[field];
|
|
140
|
+
if (raw !== null && typeof raw !== 'string') errors[`${prefix}${field}`] = 'Must be a string, or null';
|
|
141
|
+
else values[field] = typeof raw === 'string' ? raw.trim() : null;
|
|
142
|
+
}
|
|
143
|
+
if ('inventory' in body) {
|
|
144
|
+
const raw = body['inventory'];
|
|
145
|
+
if (raw !== null && !(typeof raw === 'number' && Number.isInteger(raw) && raw >= 0)) {
|
|
146
|
+
errors[`${prefix}inventory`] = 'Must be a whole number, zero or more (0 is sold out), or null (stock not tracked)';
|
|
147
|
+
} else values.inventory = raw;
|
|
148
|
+
}
|
|
149
|
+
if (options.target) {
|
|
150
|
+
if ('id' in body) {
|
|
151
|
+
if (typeof body['id'] !== 'string' || !body['id']) errors[`${prefix}id`] = 'Must be a variant id';
|
|
152
|
+
else values.id = body['id'];
|
|
153
|
+
}
|
|
154
|
+
if ('options' in body) {
|
|
155
|
+
const raw = body['options'];
|
|
156
|
+
if (!isPlainObject(raw) || Object.values(raw).some((value)=>typeof value !== 'string')) {
|
|
157
|
+
errors[`${prefix}options`] = 'Must map each option name to one of its values';
|
|
158
|
+
} else values.options = raw;
|
|
159
|
+
}
|
|
160
|
+
if (!('id' in body) && !('options' in body)) {
|
|
161
|
+
errors[prefix || 'variant'] = 'Name the variant by its `id` or by its `options`';
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return Object.keys(errors).length ? {
|
|
165
|
+
errors
|
|
166
|
+
} : {
|
|
167
|
+
values
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* A product write's body (`ProductWrite`): the members the editor lets a
|
|
172
|
+
* person set without a further plan feature. Every member it does not name
|
|
173
|
+
* is a 400 that names it. `create` requires `name`.
|
|
174
|
+
*/ export function readProductWrite(body, options) {
|
|
175
|
+
const errors = unknownKeys(body, PRODUCT_WRITABLE_KEYS);
|
|
176
|
+
const values = {};
|
|
177
|
+
if ('name' in body || options.create) {
|
|
178
|
+
const name = body['name'];
|
|
179
|
+
if (typeof name !== 'string' || !name.trim()) errors['name'] = 'Required, and not blank';
|
|
180
|
+
else if (name.trim().length > PRODUCT_NAME_MAX_LENGTH) errors['name'] = `At most ${PRODUCT_NAME_MAX_LENGTH} characters`;
|
|
181
|
+
else values.name = name.trim();
|
|
182
|
+
}
|
|
183
|
+
if ('description' in body) {
|
|
184
|
+
const description = body['description'];
|
|
185
|
+
if (description !== null && typeof description !== 'string') errors['description'] = 'Must be a string, or null';
|
|
186
|
+
else values.description = typeof description === 'string' ? description : '';
|
|
187
|
+
}
|
|
188
|
+
if ('status' in body) {
|
|
189
|
+
if (!PRODUCT_STATUSES.includes(body['status'])) errors['status'] = `Must be one of: ${PRODUCT_STATUSES.join(', ')}`;
|
|
190
|
+
else values.status = body['status'];
|
|
191
|
+
}
|
|
192
|
+
if ('type' in body) {
|
|
193
|
+
const type = body['type'];
|
|
194
|
+
if (type === 'digital') errors['type'] = PRODUCT_DIGITAL_REFUSAL;
|
|
195
|
+
else if (!PRODUCT_API_TYPES.includes(type)) errors['type'] = `Must be one of: ${PRODUCT_API_TYPES.join(', ')}`;
|
|
196
|
+
else values.type = type;
|
|
197
|
+
}
|
|
198
|
+
if ('slug' in body) {
|
|
199
|
+
const slug = body['slug'];
|
|
200
|
+
if (typeof slug !== 'string' || !slug || slug !== commerceSlug(slug)) {
|
|
201
|
+
errors['slug'] = `Lowercase letters, numbers and dashes, at most ${COMMERCE_SLUG_MAX_LENGTH} characters`;
|
|
202
|
+
} else values.slug = slug;
|
|
203
|
+
}
|
|
204
|
+
for (const field of [
|
|
205
|
+
'tags',
|
|
206
|
+
'categoryIds',
|
|
207
|
+
'mediaUrls'
|
|
208
|
+
]){
|
|
209
|
+
if (!(field in body)) continue;
|
|
210
|
+
const list = stringList(body[field]);
|
|
211
|
+
if (typeof list === 'string') errors[field] = list;
|
|
212
|
+
else if (field === 'mediaUrls' && list.some((url)=>!/^https?:\/\/\S+$/.test(url))) errors[field] = 'Each must be an http or https URL';
|
|
213
|
+
else values[field] = field === 'tags' ? list : [
|
|
214
|
+
...new Set(list)
|
|
215
|
+
];
|
|
216
|
+
}
|
|
217
|
+
if ('options' in body) {
|
|
218
|
+
const raw = body['options'];
|
|
219
|
+
if (!Array.isArray(raw)) errors['options'] = 'Must be an array of { name, values }';
|
|
220
|
+
else if (raw.length > COMMERCE_MAX_OPTIONS) errors['options'] = `At most ${COMMERCE_MAX_OPTIONS} options per product`;
|
|
221
|
+
else {
|
|
222
|
+
const parsed = [];
|
|
223
|
+
raw.forEach((option, index)=>{
|
|
224
|
+
const optionValues = isPlainObject(option) ? stringList(option['values']) : 'Must be { name, values }';
|
|
225
|
+
if (!isPlainObject(option)) errors[`options[${index}]`] = 'Must be { name, values }';
|
|
226
|
+
else if (Object.keys(unknownKeys(option, [
|
|
227
|
+
'name',
|
|
228
|
+
'values'
|
|
229
|
+
])).length) errors[`options[${index}]`] = 'Only `name` and `values`';
|
|
230
|
+
else if (typeof option['name'] !== 'string' || !option['name'].trim()) errors[`options[${index}].name`] = 'Required, and not blank';
|
|
231
|
+
else if (typeof optionValues === 'string') errors[`options[${index}].values`] = optionValues;
|
|
232
|
+
else parsed.push({
|
|
233
|
+
name: option['name'].trim(),
|
|
234
|
+
values: optionValues
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
values.options = parsed;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
if ('variants' in body) {
|
|
241
|
+
const raw = body['variants'];
|
|
242
|
+
if (!Array.isArray(raw)) errors['variants'] = 'Must be an array of variant changes';
|
|
243
|
+
else {
|
|
244
|
+
const parsed = [];
|
|
245
|
+
raw.forEach((entry, index)=>{
|
|
246
|
+
const read = readVariantWrite(entry, {
|
|
247
|
+
target: true,
|
|
248
|
+
prefix: `variants[${index}].`
|
|
249
|
+
});
|
|
250
|
+
if ('errors' in read) Object.assign(errors, read.errors);
|
|
251
|
+
else parsed.push(read.values);
|
|
252
|
+
});
|
|
253
|
+
values.variants = parsed;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if ('seo' in body) {
|
|
257
|
+
const raw = body['seo'];
|
|
258
|
+
if (!isPlainObject(raw)) errors['seo'] = 'Must be { title, description }';
|
|
259
|
+
else {
|
|
260
|
+
Object.assign(errors, unknownKeys(raw, SEO_WRITABLE_KEYS, 'seo.'));
|
|
261
|
+
const seo = {};
|
|
262
|
+
for (const field of SEO_WRITABLE_KEYS){
|
|
263
|
+
if (!(field in raw)) continue;
|
|
264
|
+
const text = raw[field];
|
|
265
|
+
const limit = SCREEN_SEO_TEXT_GUIDANCE[field];
|
|
266
|
+
if (text !== null && typeof text !== 'string') errors[`seo.${field}`] = 'Must be a string, or null';
|
|
267
|
+
else if (typeof text === 'string' && text.trim().length > limit) errors[`seo.${field}`] = `At most ${limit} characters`;
|
|
268
|
+
else seo[field] = typeof text === 'string' ? text.trim() : null;
|
|
269
|
+
}
|
|
270
|
+
values.seo = seo;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return Object.keys(errors).length ? {
|
|
274
|
+
errors
|
|
275
|
+
} : {
|
|
276
|
+
values
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
/** A variant with a variant write applied, as the editor's grid applies a typed cell. */ export function applyVariantWrite(variant, write) {
|
|
280
|
+
var _write_inventory;
|
|
281
|
+
const next = _extends({}, variant);
|
|
282
|
+
for (const field of [
|
|
283
|
+
'priceUsd',
|
|
284
|
+
'compareAtPriceUsd',
|
|
285
|
+
'weightGrams'
|
|
286
|
+
]){
|
|
287
|
+
if (!(field in write)) continue;
|
|
288
|
+
// A cleared number is no number (AGL-3676): the key goes.
|
|
289
|
+
if (write[field] === null) delete next[field];
|
|
290
|
+
else next[field] = write[field];
|
|
291
|
+
}
|
|
292
|
+
for (const field of [
|
|
293
|
+
'sku',
|
|
294
|
+
'barcode'
|
|
295
|
+
]){
|
|
296
|
+
if (!(field in write)) continue;
|
|
297
|
+
if (!write[field]) delete next[field];
|
|
298
|
+
else next[field] = write[field];
|
|
299
|
+
}
|
|
300
|
+
// `null` untracked, a number counted: the grid's Stock cell.
|
|
301
|
+
if ('inventory' in write) next['inventory'] = (_write_inventory = write.inventory) != null ? _write_inventory : null;
|
|
302
|
+
return next;
|
|
303
|
+
}
|
|
304
|
+
const buildRefusal = (status, error, detail)=>({
|
|
305
|
+
refusal: _extends({
|
|
306
|
+
status,
|
|
307
|
+
error
|
|
308
|
+
}, detail ? {
|
|
309
|
+
detail
|
|
310
|
+
} : {})
|
|
311
|
+
});
|
|
312
|
+
/** Whether a stock number is asked of a product that cannot keep one. */ function stockRefusal(product, writes, field) {
|
|
313
|
+
if (stockTrackingApplies(product)) return null;
|
|
314
|
+
const index = writes.findIndex((write)=>typeof write.inventory === 'number');
|
|
315
|
+
return index === -1 ? null : buildRefusal(400, 'Product failed validation', {
|
|
316
|
+
[field(index)]: PRODUCT_STOCK_NOT_TRACKED
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* The product a write makes of `base`: only the members it carries change,
|
|
321
|
+
* so every field it does not name — the ones this API does not expose
|
|
322
|
+
* included — stays as stored.
|
|
323
|
+
*/ export function mergeProductWrite(base, values, nowMs) {
|
|
324
|
+
var _values_variants;
|
|
325
|
+
let next = _extends({}, base);
|
|
326
|
+
for (const field of [
|
|
327
|
+
'name',
|
|
328
|
+
'description',
|
|
329
|
+
'status',
|
|
330
|
+
'type',
|
|
331
|
+
'slug',
|
|
332
|
+
'tags',
|
|
333
|
+
'categoryIds',
|
|
334
|
+
'mediaUrls'
|
|
335
|
+
]){
|
|
336
|
+
if (values[field] !== undefined) next[field] = values[field];
|
|
337
|
+
}
|
|
338
|
+
if (values.seo) {
|
|
339
|
+
var _base_seo;
|
|
340
|
+
const seo = _extends({}, (_base_seo = base.seo) != null ? _base_seo : {});
|
|
341
|
+
for (const [field, text] of Object.entries(values.seo)){
|
|
342
|
+
if (text) seo[field] = text;
|
|
343
|
+
else delete seo[field];
|
|
344
|
+
}
|
|
345
|
+
if (Object.keys(seo).length) next.seo = seo;
|
|
346
|
+
else delete next.seo;
|
|
347
|
+
}
|
|
348
|
+
if (values.options) {
|
|
349
|
+
var _next_options;
|
|
350
|
+
const options = values.options;
|
|
351
|
+
// A rename moves each variant's selections to the new name (AGL-3066),
|
|
352
|
+
// as the editor's rename does; then the grid is rebuilt from the values,
|
|
353
|
+
// as the editor's value change does. Past the ceiling the variants are
|
|
354
|
+
// left as they are and the save refuses (AGL-4100).
|
|
355
|
+
if (((_next_options = next.options) != null ? _next_options : []).length === options.length) {
|
|
356
|
+
next = _extends({}, next, renameProductOptions(next, options.map((option)=>option.name)));
|
|
357
|
+
}
|
|
358
|
+
if (!variantMatrixProblem(options)) next.variants = variantsForOptions(next, options, nowMs);
|
|
359
|
+
next.options = options;
|
|
360
|
+
}
|
|
361
|
+
if ((_values_variants = values.variants) == null ? void 0 : _values_variants.length) {
|
|
362
|
+
const variants = [
|
|
363
|
+
...next.variants
|
|
364
|
+
];
|
|
365
|
+
const seen = new Set();
|
|
366
|
+
for (const [index, write] of values.variants.entries()){
|
|
367
|
+
const at = write.id ? variants.findIndex((variant)=>variant.id === write.id) : variants.findIndex((variant)=>variantComboKey(variant.options) === variantComboKey(write.options));
|
|
368
|
+
if (at === -1) {
|
|
369
|
+
return buildRefusal(400, 'Product failed validation', {
|
|
370
|
+
[`variants[${index}]`]: write.id ? 'No variant of this product has this id' : 'No variant of this product has these options; a product’s variants are every combination of its options'
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
if (seen.has(at)) return buildRefusal(400, 'Product failed validation', {
|
|
374
|
+
[`variants[${index}]`]: 'Names a variant another entry already changes'
|
|
375
|
+
});
|
|
376
|
+
seen.add(at);
|
|
377
|
+
// Only the variant fields apply; `id` and `options` named the variant.
|
|
378
|
+
variants[at] = applyVariantWrite(variants[at], write);
|
|
379
|
+
}
|
|
380
|
+
next.variants = variants;
|
|
381
|
+
const refused = stockRefusal(next, values.variants, (index)=>`variants[${index}].inventory`);
|
|
382
|
+
if (refused) return refused;
|
|
383
|
+
}
|
|
384
|
+
return next;
|
|
385
|
+
}
|
|
386
|
+
/** A product write's refusal, in the API's envelope. */ function refusalResponse(ctx, refusal) {
|
|
387
|
+
switch(refusal.code){
|
|
388
|
+
case 'invalid':
|
|
389
|
+
return ApiErrors.badRequest({
|
|
390
|
+
message: refusal.error,
|
|
391
|
+
code: 'validation_failed',
|
|
392
|
+
headers: ctx.headers
|
|
393
|
+
});
|
|
394
|
+
case 'plan':
|
|
395
|
+
return ApiErrors.planRequired({
|
|
396
|
+
message: refusal.error,
|
|
397
|
+
code: 'commerce',
|
|
398
|
+
headers: ctx.headers
|
|
399
|
+
});
|
|
400
|
+
case 'quota':
|
|
401
|
+
return ApiErrors.planRequired({
|
|
402
|
+
message: refusal.error,
|
|
403
|
+
code: 'product_quota',
|
|
404
|
+
headers: ctx.headers
|
|
405
|
+
});
|
|
406
|
+
case 'slug_taken':
|
|
407
|
+
return ApiErrors.conflict({
|
|
408
|
+
message: refusal.error,
|
|
409
|
+
code: 'slug_taken',
|
|
410
|
+
headers: ctx.headers
|
|
411
|
+
});
|
|
412
|
+
case 'missing':
|
|
413
|
+
return ApiErrors.notFound({
|
|
414
|
+
message: 'No such product',
|
|
415
|
+
headers: ctx.headers
|
|
416
|
+
});
|
|
417
|
+
case 'refused':
|
|
418
|
+
return refusal.status === 404 ? ApiErrors.notFound({
|
|
419
|
+
message: refusal.error,
|
|
420
|
+
headers: ctx.headers
|
|
421
|
+
}) : ApiErrors.badRequest(_extends({
|
|
422
|
+
message: refusal.error,
|
|
423
|
+
code: 'validation_failed'
|
|
424
|
+
}, refusal.detail ? {
|
|
425
|
+
fields: refusal.detail
|
|
426
|
+
} : {}, {
|
|
427
|
+
headers: ctx.headers
|
|
428
|
+
}));
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
const validationFailed = (ctx, fields, message = 'Product failed validation')=>ApiErrors.badRequest({
|
|
432
|
+
message,
|
|
433
|
+
code: 'validation_failed',
|
|
434
|
+
fields,
|
|
435
|
+
headers: ctx.headers
|
|
436
|
+
});
|
|
437
|
+
function productsOf(ctx, hostId) {
|
|
438
|
+
return ctx.firestore.collection('hosts').doc(hostId).collection('products');
|
|
439
|
+
}
|
|
440
|
+
/** The categories a write names that the site does not have. */ async function danglingCategories(ctx, hostId, ids) {
|
|
441
|
+
if (!(ids == null ? void 0 : ids.length)) return null;
|
|
442
|
+
const categories = ctx.firestore.collection('hosts').doc(hostId).collection('productCategories');
|
|
443
|
+
const missing = [];
|
|
444
|
+
for (const id of ids){
|
|
445
|
+
if (!/^[A-Za-z0-9_-]{1,128}$/.test(id) || !(await categories.doc(id).get()).exists) missing.push(id);
|
|
446
|
+
}
|
|
447
|
+
return missing.length ? {
|
|
448
|
+
categoryIds: `No such category on this site: ${missing.join(', ')}`
|
|
449
|
+
} : null;
|
|
450
|
+
}
|
|
451
|
+
/** What every save from here hands `saveProduct` beside the product. */ function saveContext(ctx, hostId, deps) {
|
|
452
|
+
var _deps_now, _deps_dropCache;
|
|
453
|
+
return {
|
|
454
|
+
firestore: ctx.firestore,
|
|
455
|
+
hostId,
|
|
456
|
+
org: ctx.org,
|
|
457
|
+
nowMs: ((_deps_now = deps.now) != null ? _deps_now : Date.now)(),
|
|
458
|
+
dropCache: (_deps_dropCache = deps.dropCache) != null ? _deps_dropCache : dropPluginSiteCache
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* The product a create starts from: the editor's blank draft, unpriced.
|
|
463
|
+
*
|
|
464
|
+
* The editor opens a new product at its default price for the person looking
|
|
465
|
+
* at it to change or clear. A caller sees no such field: one that sent no
|
|
466
|
+
* price asked for none, so its variant is saved unpriced — "Price coming
|
|
467
|
+
* soon", not for sale (`variantHasPrice`) — rather than at a price nobody
|
|
468
|
+
* chose. A grid rebuilt from options takes the first variant's values, as the
|
|
469
|
+
* editor's does, so its new combinations are unpriced too until a variant
|
|
470
|
+
* write prices them.
|
|
471
|
+
*/ export function unpricedProductDraft() {
|
|
472
|
+
const draft = blankProductDraft();
|
|
473
|
+
return _extends({}, draft, {
|
|
474
|
+
variants: draft.variants.map((variant)=>{
|
|
475
|
+
const unpriced = _extends({}, variant);
|
|
476
|
+
delete unpriced.priceUsd;
|
|
477
|
+
return unpriced;
|
|
478
|
+
})
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
/**
|
|
482
|
+
* `POST /v1/sites/{siteId}/products` — the editor's Add product.
|
|
483
|
+
*
|
|
484
|
+
* A draft unless `status` says otherwise, as the editor starts one, so a new
|
|
485
|
+
* product is not on sale until someone means it to be. The id is minted
|
|
486
|
+
* here. The slug is claimed from the name when none is sent, as Duplicate
|
|
487
|
+
* claims one (`claimProductSlug`), and a sent slug another product holds —
|
|
488
|
+
* a deleted one's included, because a deleted product still answers its
|
|
489
|
+
* slug on the storefront — is a 409.
|
|
490
|
+
*
|
|
491
|
+
* Replay-safe on an `Idempotency-Key`, as `createContact` is and for its
|
|
492
|
+
* reasons: validation above the claim, every refusal after it releasing the
|
|
493
|
+
* key, the plan and the allowance counted inside the save's transaction.
|
|
494
|
+
*/ export async function createProduct(request, ctx, hostId, deps = {}) {
|
|
495
|
+
var _deps_now;
|
|
496
|
+
const parsed = readProductWrite(await readJsonBody(request), {
|
|
497
|
+
create: true
|
|
498
|
+
});
|
|
499
|
+
if ('errors' in parsed) return validationFailed(ctx, parsed.errors);
|
|
500
|
+
const values = parsed.values;
|
|
501
|
+
const dangling = await danglingCategories(ctx, hostId, values.categoryIds);
|
|
502
|
+
if (dangling) return validationFailed(ctx, dangling);
|
|
503
|
+
const draft = mergeProductWrite(unpricedProductDraft(), values, ((_deps_now = deps.now) != null ? _deps_now : Date.now)());
|
|
504
|
+
if ('refusal' in draft) return refusalResponse(ctx, _extends({
|
|
505
|
+
ok: false,
|
|
506
|
+
code: 'refused'
|
|
507
|
+
}, draft.refusal));
|
|
508
|
+
const claimed = await claimWrite(ctx, hostId, request.headers.get('Idempotency-Key'), 'product-creates');
|
|
509
|
+
if ('replay' in claimed) return claimed.replay;
|
|
510
|
+
const { claim } = claimed;
|
|
511
|
+
try {
|
|
512
|
+
var _values_slug, _ctx_uid;
|
|
513
|
+
const products = productsOf(ctx, hostId);
|
|
514
|
+
const productId = createResourceUid();
|
|
515
|
+
const base = commerceSlug(draft.name);
|
|
516
|
+
const slug = (_values_slug = values.slug) != null ? _values_slug : base ? await claimProductSlug(products, base) : '';
|
|
517
|
+
const saved = await saveProduct(_extends({}, saveContext(ctx, hostId, deps), {
|
|
518
|
+
productId,
|
|
519
|
+
create: true,
|
|
520
|
+
product: _extends({}, draft, {
|
|
521
|
+
slug
|
|
522
|
+
}),
|
|
523
|
+
uniqueSlug: true,
|
|
524
|
+
// The person a connected app acts for, where the app's routes stamp the
|
|
525
|
+
// member; an API key is no person, and its name says who made it.
|
|
526
|
+
createdBy: (_ctx_uid = ctx.uid) != null ? _ctx_uid : null,
|
|
527
|
+
createStamps: apiActorFields(ctx),
|
|
528
|
+
cacheReason: 'product created over the API'
|
|
529
|
+
}));
|
|
530
|
+
if (saved.ok === false) {
|
|
531
|
+
await claim.release();
|
|
532
|
+
return refusalResponse(ctx, saved);
|
|
533
|
+
}
|
|
534
|
+
const view = productView(await products.doc(productId).get());
|
|
535
|
+
// Stored as 200 so a replay is distinguishable from the fresh 201.
|
|
536
|
+
await claim.record(200, view);
|
|
537
|
+
return apiJson(view, {
|
|
538
|
+
status: 201,
|
|
539
|
+
headers: ctx.headers
|
|
540
|
+
});
|
|
541
|
+
} catch (error) {
|
|
542
|
+
await claim.release();
|
|
543
|
+
throw error;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
/** The stored product a write starts from, read in the save's own transaction. */ function storedProduct(stored) {
|
|
547
|
+
var _stored_data;
|
|
548
|
+
if (!stored.exists || stored.get('deletedAt')) return buildRefusal(404, 'No such product');
|
|
549
|
+
return liftLegacyProduct((_stored_data = stored.data()) != null ? _stored_data : {});
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* `PATCH /v1/sites/{siteId}/products/{productId}` — the editor's save, for
|
|
553
|
+
* the fields sent. The editor's save is a full replace, so the stored product
|
|
554
|
+
* is read in the save's transaction and only the members sent change on it:
|
|
555
|
+
* subscription terms, add-ons, stock holds, stored timestamps and every other
|
|
556
|
+
* field this API does not expose stay as stored. A slug another product
|
|
557
|
+
* holds is a 409. An empty body changes nothing and answers the product.
|
|
558
|
+
*/ export async function updateProduct(request, ctx, hostId, productId, deps = {}) {
|
|
559
|
+
const body = await readJsonBody(request);
|
|
560
|
+
const parsed = readProductWrite(body, {
|
|
561
|
+
create: false
|
|
562
|
+
});
|
|
563
|
+
if ('errors' in parsed) return validationFailed(ctx, parsed.errors);
|
|
564
|
+
const values = parsed.values;
|
|
565
|
+
const products = productsOf(ctx, hostId);
|
|
566
|
+
if (Object.keys(body).length > 0) {
|
|
567
|
+
const dangling = await danglingCategories(ctx, hostId, values.categoryIds);
|
|
568
|
+
if (dangling) return validationFailed(ctx, dangling);
|
|
569
|
+
const context = saveContext(ctx, hostId, deps);
|
|
570
|
+
const saved = await saveProduct(_extends({}, context, {
|
|
571
|
+
productId,
|
|
572
|
+
create: false,
|
|
573
|
+
product: (stored)=>{
|
|
574
|
+
const base = storedProduct(stored);
|
|
575
|
+
return 'refusal' in base ? base : mergeProductWrite(base, values, context.nowMs);
|
|
576
|
+
},
|
|
577
|
+
uniqueSlug: values.slug !== undefined,
|
|
578
|
+
createdBy: null,
|
|
579
|
+
cacheReason: 'product updated over the API'
|
|
580
|
+
}));
|
|
581
|
+
if (saved.ok === false) return refusalResponse(ctx, saved);
|
|
582
|
+
}
|
|
583
|
+
const snap = await products.doc(productId).get();
|
|
584
|
+
if (!snap.exists || snap.get('deletedAt')) return ApiErrors.notFound({
|
|
585
|
+
message: 'No such product',
|
|
586
|
+
headers: ctx.headers
|
|
587
|
+
});
|
|
588
|
+
return apiJson(productView(snap), {
|
|
589
|
+
headers: ctx.headers
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* `PATCH /v1/sites/{siteId}/products/{productId}/variants/{variantId}` —
|
|
594
|
+
* one row of the editor's variant grid: its price, compare-at price, SKU,
|
|
595
|
+
* barcode, weight and stock, through the same save, so every check runs.
|
|
596
|
+
* Answers the whole product.
|
|
597
|
+
*/ export async function updateProductVariant(request, ctx, hostId, productId, variantId, deps = {}) {
|
|
598
|
+
var _snap_get;
|
|
599
|
+
const body = await readJsonBody(request);
|
|
600
|
+
const parsed = readVariantWrite(body);
|
|
601
|
+
if ('errors' in parsed) return validationFailed(ctx, parsed.errors, 'Variant failed validation');
|
|
602
|
+
const write = parsed.values;
|
|
603
|
+
const products = productsOf(ctx, hostId);
|
|
604
|
+
if (Object.keys(write).length > 0) {
|
|
605
|
+
const saved = await saveProduct(_extends({}, saveContext(ctx, hostId, deps), {
|
|
606
|
+
productId,
|
|
607
|
+
create: false,
|
|
608
|
+
product: (stored)=>{
|
|
609
|
+
var _stockRefusal;
|
|
610
|
+
const base = storedProduct(stored);
|
|
611
|
+
if ('refusal' in base) return base;
|
|
612
|
+
const at = base.variants.findIndex((variant)=>variant.id === variantId);
|
|
613
|
+
if (at === -1) return buildRefusal(404, 'No such variant');
|
|
614
|
+
const variants = [
|
|
615
|
+
...base.variants
|
|
616
|
+
];
|
|
617
|
+
variants[at] = applyVariantWrite(variants[at], write);
|
|
618
|
+
const next = _extends({}, base, {
|
|
619
|
+
variants
|
|
620
|
+
});
|
|
621
|
+
return (_stockRefusal = stockRefusal(next, [
|
|
622
|
+
write
|
|
623
|
+
], ()=>'inventory')) != null ? _stockRefusal : next;
|
|
624
|
+
},
|
|
625
|
+
createdBy: null,
|
|
626
|
+
cacheReason: 'product variant updated over the API'
|
|
627
|
+
}));
|
|
628
|
+
if (saved.ok === false) return refusalResponse(ctx, saved);
|
|
629
|
+
}
|
|
630
|
+
const snap = await products.doc(productId).get();
|
|
631
|
+
if (!snap.exists || snap.get('deletedAt')) return ApiErrors.notFound({
|
|
632
|
+
message: 'No such product',
|
|
633
|
+
headers: ctx.headers
|
|
634
|
+
});
|
|
635
|
+
const variants = (_snap_get = snap.get('variants')) != null ? _snap_get : [];
|
|
636
|
+
if (!variants.some((variant)=>variant.id === variantId)) {
|
|
637
|
+
return ApiErrors.notFound({
|
|
638
|
+
message: 'No such variant',
|
|
639
|
+
headers: ctx.headers
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
return apiJson(productView(snap), {
|
|
643
|
+
headers: ctx.headers
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* `DELETE /v1/sites/{siteId}/products/{productId}` — the products list's
|
|
648
|
+
* Delete: `deletedAt` on the product, which takes it off sale, and the
|
|
649
|
+
* site's cache drop. Asked again, it answers the same receipt; a product
|
|
650
|
+
* that never existed is a 404.
|
|
651
|
+
*/ export async function deleteProductOverApi(ctx, hostId, productId, deps = {}) {
|
|
652
|
+
var _deps_dropCache;
|
|
653
|
+
const removed = await deleteProduct({
|
|
654
|
+
firestore: ctx.firestore,
|
|
655
|
+
hostId,
|
|
656
|
+
productId,
|
|
657
|
+
dropCache: (_deps_dropCache = deps.dropCache) != null ? _deps_dropCache : dropPluginSiteCache,
|
|
658
|
+
cacheReason: 'product deleted over the API'
|
|
659
|
+
});
|
|
660
|
+
if (removed.ok === false) return ApiErrors.notFound({
|
|
661
|
+
message: 'No such product',
|
|
662
|
+
headers: ctx.headers
|
|
663
|
+
});
|
|
664
|
+
return apiJson({
|
|
665
|
+
id: productId,
|
|
666
|
+
object: 'product',
|
|
667
|
+
deleted: true
|
|
668
|
+
}, {
|
|
669
|
+
headers: ctx.headers
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
//# sourceMappingURL=product-writes.js.map
|