@aglyn/plugins-commerce 1.34.1 → 1.35.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/woo-connections-card.component.d.ts +52 -0
- package/src/lib/components/console/woo-connections-card.component.js +189 -0
- package/src/lib/components/console/woo-connections-card.component.js.map +1 -0
- package/src/lib/plugin.js +13 -1
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/server/order-event-triggers.js +9 -0
- package/src/lib/server/order-event-triggers.js.map +1 -1
- package/src/lib/server/woo/woo-connections.d.ts +23 -0
- package/src/lib/server/woo/woo-connections.js +109 -0
- package/src/lib/server/woo/woo-connections.js.map +1 -0
- package/src/lib/server/woo/woo-context.d.ts +45 -0
- package/src/lib/server/woo/woo-context.js +36 -0
- package/src/lib/server/woo/woo-context.js.map +1 -0
- package/src/lib/server/woo/woo-ids.d.ts +45 -0
- package/src/lib/server/woo/woo-ids.js +141 -0
- package/src/lib/server/woo/woo-ids.js.map +1 -0
- package/src/lib/server/woo/woo-meta.d.ts +68 -0
- package/src/lib/server/woo/woo-meta.js +127 -0
- package/src/lib/server/woo/woo-meta.js.map +1 -0
- package/src/lib/server/woo/woo-orders.d.ts +136 -0
- package/src/lib/server/woo/woo-orders.js +378 -0
- package/src/lib/server/woo/woo-orders.js.map +1 -0
- package/src/lib/server/woo/woo-products.d.ts +19 -0
- package/src/lib/server/woo/woo-products.js +662 -0
- package/src/lib/server/woo/woo-products.js.map +1 -0
- package/src/lib/server/woo/woo-route.d.ts +49 -0
- package/src/lib/server/woo/woo-route.js +333 -0
- package/src/lib/server/woo/woo-route.js.map +1 -0
- package/src/lib/server/woo/woo-shapes.d.ts +421 -0
- package/src/lib/server/woo/woo-shapes.js +835 -0
- package/src/lib/server/woo/woo-shapes.js.map +1 -0
- package/src/lib/server/woo/woo-system.d.ts +35 -0
- package/src/lib/server/woo/woo-system.js +339 -0
- package/src/lib/server/woo/woo-system.js.map +1 -0
- package/src/lib/server/woo/woo-webhooks.d.ts +53 -0
- package/src/lib/server/woo/woo-webhooks.js +204 -0
- package/src/lib/server/woo/woo-webhooks.js.map +1 -0
- package/src/lib/server.js +15 -0
- package/src/lib/server.js.map +1 -1
|
@@ -0,0 +1,662 @@
|
|
|
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
|
+
*/ /*==========================================
|
|
18
|
+
* PRODUCTS AND VARIATIONS, IN WOOCOMMERCE'S DIALECT.
|
|
19
|
+
*
|
|
20
|
+
* Every write goes through the store's own product writers
|
|
21
|
+
* (`api-v1/product-writes.ts`), so a product an app publishes is saved
|
|
22
|
+
* exactly as the editor would save it: search keys, stock verdict, slug,
|
|
23
|
+
* collections, plan allowance, cache drop. WooCommerce's model differs in
|
|
24
|
+
* one way that matters: a variable product's variations are created one by
|
|
25
|
+
* one, while the store's variants are every combination of the product's
|
|
26
|
+
* options. A variation is therefore found (or made, by adding its values to
|
|
27
|
+
* the product's options) in that grid and priced; combinations nobody
|
|
28
|
+
* priced stay unpriced, which the storefront shows as not for sale. Deleting
|
|
29
|
+
* a variation unprices it.
|
|
30
|
+
*=========================================*/ import { requireScope, requireSitePermission } from "@aglyn/tenant-data-admin/server/api-v1-kit";
|
|
31
|
+
import { variantComboKey } from "../../model/product-write.js";
|
|
32
|
+
import { createProduct, deleteProductOverApi, updateProduct, updateProductVariant } from "../api-v1/product-writes.js";
|
|
33
|
+
import { jsonRequest, readAnswer } from "./woo-context.js";
|
|
34
|
+
import { wooIdsFor, wooIdTarget } from "./woo-ids.js";
|
|
35
|
+
import { mergeMeta, metaList, readProductMeta, readProductMetas, writeProductMeta } from "./woo-meta.js";
|
|
36
|
+
import { imagesFromWoo, optionsWithVariation, productWriteFromWoo, readWooPage, variantWriteFromWoo, variationOptionsFromWoo, wooError, wooImageId, wooInvalidId, wooNotFound, wooPaged, wooProduct, wooRefusalFrom, wooVariation } from "./woo-shapes.js";
|
|
37
|
+
const productsOf = (ctx)=>ctx.api.firestore.collection('hosts').doc(ctx.hostId).collection('products');
|
|
38
|
+
const variantsOf = (data)=>Array.isArray(data['variants']) ? data['variants'] : [];
|
|
39
|
+
const optionsOf = (data)=>Array.isArray(data['options']) ? data['options'].map((option)=>{
|
|
40
|
+
var _option_name;
|
|
41
|
+
return {
|
|
42
|
+
name: String((_option_name = option.name) != null ? _option_name : ''),
|
|
43
|
+
values: Array.isArray(option.values) ? option.values.map(String) : []
|
|
44
|
+
};
|
|
45
|
+
}) : [];
|
|
46
|
+
async function categoriesOf(ctx) {
|
|
47
|
+
const snap = await ctx.api.firestore.collection('hosts').doc(ctx.hostId).collection('productCategories').get();
|
|
48
|
+
const out = new Map();
|
|
49
|
+
for (const doc of snap.docs){
|
|
50
|
+
var _doc_get, _doc_get1;
|
|
51
|
+
const name = String((_doc_get = doc.get('name')) != null ? _doc_get : '');
|
|
52
|
+
out.set(doc.id, {
|
|
53
|
+
id: wooImageId(`category:${doc.id}`),
|
|
54
|
+
name,
|
|
55
|
+
slug: String((_doc_get1 = doc.get('slug')) != null ? _doc_get1 : name.toLowerCase().replace(/[^a-z0-9]+/g, '-'))
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
/** The ids a product's shape needs: its own and each variant's. */ async function idsForProduct(ctx, productId, data) {
|
|
61
|
+
const variants = variantsOf(data).filter((variant)=>variant.id);
|
|
62
|
+
const targets = [
|
|
63
|
+
{
|
|
64
|
+
kind: 'product',
|
|
65
|
+
productId
|
|
66
|
+
},
|
|
67
|
+
...variants.map((variant)=>({
|
|
68
|
+
kind: 'variant',
|
|
69
|
+
productId,
|
|
70
|
+
variantId: String(variant.id)
|
|
71
|
+
}))
|
|
72
|
+
];
|
|
73
|
+
const ns = await wooIdsFor(ctx.api.firestore, ctx.hostId, targets);
|
|
74
|
+
return {
|
|
75
|
+
product: ns[0],
|
|
76
|
+
variants: new Map(variants.map((variant, index)=>[
|
|
77
|
+
String(variant.id),
|
|
78
|
+
ns[index + 1]
|
|
79
|
+
]))
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
/** A product's WooCommerce shape, with what the app stored beside it. */ async function shapeProduct(ctx, productId, data, meta, categories) {
|
|
83
|
+
const ids = await idsForProduct(ctx, productId, data);
|
|
84
|
+
const shaped = wooProduct(data, ids, {
|
|
85
|
+
origin: ctx.origin,
|
|
86
|
+
categories
|
|
87
|
+
});
|
|
88
|
+
return _extends({}, shaped, {
|
|
89
|
+
sku: shaped.type === 'variable' ? meta.sku : shaped.sku,
|
|
90
|
+
meta_data: metaList(meta.meta)
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
function shapeVariation(ctx, data, variant, variationId, productId, meta) {
|
|
94
|
+
var _meta_variants_String, _shaped_image, _stored_meta;
|
|
95
|
+
const stored = (_meta_variants_String = meta.variants[String(variant.id)]) != null ? _meta_variants_String : {};
|
|
96
|
+
const shaped = wooVariation(data, variant, variationId, {
|
|
97
|
+
origin: ctx.origin,
|
|
98
|
+
categories: new Map()
|
|
99
|
+
});
|
|
100
|
+
return _extends({}, shaped, {
|
|
101
|
+
parent_id: productId,
|
|
102
|
+
image: (_shaped_image = shaped.image) != null ? _shaped_image : stored.image ? {
|
|
103
|
+
id: wooImageId(stored.image),
|
|
104
|
+
src: stored.image,
|
|
105
|
+
name: '',
|
|
106
|
+
alt: '',
|
|
107
|
+
position: 0
|
|
108
|
+
} : null,
|
|
109
|
+
meta_data: metaList((_stored_meta = stored.meta) != null ? _stored_meta : {})
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
/** The product an integer names, read; `null` when it names none (or a variation). */ async function productByWooId(ctx, raw) {
|
|
113
|
+
var _snap_data;
|
|
114
|
+
const target = await wooIdTarget(ctx.api.firestore, ctx.hostId, Number(raw));
|
|
115
|
+
if (!target || target.kind !== 'product') return null;
|
|
116
|
+
const snap = await productsOf(ctx).doc(target.productId).get();
|
|
117
|
+
if (!snap.exists || snap.get('deletedAt')) return null;
|
|
118
|
+
return {
|
|
119
|
+
productId: target.productId,
|
|
120
|
+
data: (_snap_data = snap.data()) != null ? _snap_data : {}
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
function writeRefusal(ctx, hostDoc) {
|
|
124
|
+
var _requireScope;
|
|
125
|
+
const denied = (_requireScope = requireScope(ctx.api, 'products:write')) != null ? _requireScope : requireSitePermission(ctx.api, hostDoc, 'site.edit');
|
|
126
|
+
return denied ? wooError(denied.status, 'woocommerce_rest_cannot_create', 'Sorry, you are not allowed to change products in this store.') : null;
|
|
127
|
+
}
|
|
128
|
+
/** Run one of the store's product writers and read its answer. */ async function run(response) {
|
|
129
|
+
return readAnswer(await response);
|
|
130
|
+
}
|
|
131
|
+
/** The stored product after a write, or a refusal. */ async function reread(ctx, productId) {
|
|
132
|
+
var _snap_data;
|
|
133
|
+
const snap = await productsOf(ctx).doc(productId).get();
|
|
134
|
+
return snap.exists && !snap.get('deletedAt') ? (_snap_data = snap.data()) != null ? _snap_data : {} : null;
|
|
135
|
+
}
|
|
136
|
+
// ── Products ────────────────────────────────────────────────────────────────
|
|
137
|
+
async function listProducts(ctx) {
|
|
138
|
+
var _search_get, _search_get1;
|
|
139
|
+
const search = ctx.url.searchParams;
|
|
140
|
+
const page = readWooPage(search);
|
|
141
|
+
const [snap, categories] = await Promise.all([
|
|
142
|
+
productsOf(ctx).get(),
|
|
143
|
+
categoriesOf(ctx)
|
|
144
|
+
]);
|
|
145
|
+
const status = search.get('status');
|
|
146
|
+
const sku = search.get('sku');
|
|
147
|
+
const term = ((_search_get = search.get('search')) != null ? _search_get : '').toLowerCase();
|
|
148
|
+
const type = search.get('type');
|
|
149
|
+
const include = new Set(((_search_get1 = search.get('include')) != null ? _search_get1 : '').split(',').map(Number).filter(Boolean));
|
|
150
|
+
let docs = snap.docs.filter((doc)=>!doc.get('deletedAt'));
|
|
151
|
+
if (status && status !== 'any') {
|
|
152
|
+
const wanted = status === 'publish' ? 'active' : status === 'private' ? 'archived' : 'draft';
|
|
153
|
+
docs = docs.filter((doc)=>{
|
|
154
|
+
var _doc_get;
|
|
155
|
+
return ((_doc_get = doc.get('status')) != null ? _doc_get : 'draft') === wanted;
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
if (term) docs = docs.filter((doc)=>{
|
|
159
|
+
var _doc_get;
|
|
160
|
+
return String((_doc_get = doc.get('name')) != null ? _doc_get : '').toLowerCase().includes(term);
|
|
161
|
+
});
|
|
162
|
+
if (type === 'simple' || type === 'variable') {
|
|
163
|
+
docs = docs.filter((doc)=>(optionsOf(doc.data()).length > 0 ? 'variable' : 'simple') === type);
|
|
164
|
+
}
|
|
165
|
+
const metas = await readProductMetas(ctx.api.firestore, ctx.hostId, docs.map((doc)=>doc.id));
|
|
166
|
+
if (sku) {
|
|
167
|
+
const wanted = new Set(sku.split(',').map((value)=>value.trim()).filter(Boolean));
|
|
168
|
+
docs = docs.filter((doc)=>{
|
|
169
|
+
var _ref;
|
|
170
|
+
var _metas_get;
|
|
171
|
+
return wanted.has((_ref = (_metas_get = metas.get(doc.id)) == null ? void 0 : _metas_get.sku) != null ? _ref : '') || variantsOf(doc.data()).some((variant)=>variant.sku && wanted.has(variant.sku));
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
if (include.size) {
|
|
175
|
+
const ids = await wooIdsFor(ctx.api.firestore, ctx.hostId, docs.map((doc)=>({
|
|
176
|
+
kind: 'product',
|
|
177
|
+
productId: doc.id
|
|
178
|
+
})));
|
|
179
|
+
docs = docs.filter((_, index)=>include.has(ids[index]));
|
|
180
|
+
}
|
|
181
|
+
const ascending = search.get('order') === 'asc';
|
|
182
|
+
docs.sort((a, b)=>{
|
|
183
|
+
var _a_get, _b_get;
|
|
184
|
+
const delta = Number((_a_get = a.get('createdAtMs')) != null ? _a_get : 0) - Number((_b_get = b.get('createdAtMs')) != null ? _b_get : 0);
|
|
185
|
+
return ascending ? delta : -delta;
|
|
186
|
+
});
|
|
187
|
+
const window = docs.slice(page.offset, page.offset + page.perPage);
|
|
188
|
+
const shaped = await Promise.all(window.map((doc)=>shapeProduct(ctx, doc.id, doc.data(), metas.get(doc.id), categories)));
|
|
189
|
+
return wooPaged(shaped, _extends({}, page, {
|
|
190
|
+
offset: 0
|
|
191
|
+
}), {
|
|
192
|
+
'X-WP-Total': String(docs.length),
|
|
193
|
+
'X-WP-TotalPages': String(Math.max(1, Math.ceil(docs.length / page.perPage)))
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
async function getProduct(ctx, raw) {
|
|
197
|
+
const found = await productByWooId(ctx, raw);
|
|
198
|
+
if (!found) return wooInvalidId('product');
|
|
199
|
+
const [meta, categories] = await Promise.all([
|
|
200
|
+
readProductMeta(ctx.api.firestore, ctx.hostId, found.productId),
|
|
201
|
+
categoriesOf(ctx)
|
|
202
|
+
]);
|
|
203
|
+
return Response.json(await shapeProduct(ctx, found.productId, found.data, meta, categories));
|
|
204
|
+
}
|
|
205
|
+
/** The store's category ids for the WooCommerce category ids a write names. */ async function storeCategoryIds(ctx, wooIds) {
|
|
206
|
+
if (!wooIds.length) return undefined;
|
|
207
|
+
const categories = await categoriesOf(ctx);
|
|
208
|
+
const wanted = new Set(wooIds);
|
|
209
|
+
return [
|
|
210
|
+
...categories.entries()
|
|
211
|
+
].filter(([, category])=>wanted.has(category.id)).map(([id])=>id);
|
|
212
|
+
}
|
|
213
|
+
async function hostDoc(ctx) {
|
|
214
|
+
var _ref;
|
|
215
|
+
var _ctx_api_site;
|
|
216
|
+
return (_ref = (_ctx_api_site = ctx.api.site) == null ? void 0 : _ctx_api_site.snapshot) != null ? _ref : await ctx.api.firestore.collection('hosts').doc(ctx.hostId).get();
|
|
217
|
+
}
|
|
218
|
+
/** Create one product from a WooCommerce body; answers its id or a refusal. */ async function createOne(ctx, body) {
|
|
219
|
+
var _ref;
|
|
220
|
+
var _answer_body;
|
|
221
|
+
const parsed = productWriteFromWoo(body, true);
|
|
222
|
+
if ('error' in parsed) return {
|
|
223
|
+
refusal: wooError(400, 'woocommerce_rest_invalid_param', parsed.error)
|
|
224
|
+
};
|
|
225
|
+
const values = _extends({}, parsed.values);
|
|
226
|
+
const categoryIds = await storeCategoryIds(ctx, parsed.categoryIds);
|
|
227
|
+
if (categoryIds == null ? void 0 : categoryIds.length) values['categoryIds'] = categoryIds;
|
|
228
|
+
if (parsed.simpleVariant) values['variants'] = [
|
|
229
|
+
_extends({
|
|
230
|
+
options: {}
|
|
231
|
+
}, parsed.simpleVariant)
|
|
232
|
+
];
|
|
233
|
+
const answer = await run(createProduct(jsonRequest('POST', values), ctx.api, ctx.hostId));
|
|
234
|
+
if (answer.status >= 400) return {
|
|
235
|
+
refusal: wooRefusalFrom(answer)
|
|
236
|
+
};
|
|
237
|
+
const productId = String((_ref = (_answer_body = answer.body) == null ? void 0 : _answer_body.id) != null ? _ref : '');
|
|
238
|
+
const meta = {
|
|
239
|
+
sku: typeof body['sku'] === 'string' ? body['sku'].trim() : '',
|
|
240
|
+
meta: mergeMeta({}, body['meta_data']),
|
|
241
|
+
variants: {}
|
|
242
|
+
};
|
|
243
|
+
if (meta.sku || Object.keys(meta.meta).length) await writeProductMeta(ctx.api.firestore, ctx.hostId, productId, meta);
|
|
244
|
+
return {
|
|
245
|
+
productId
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
/** Update one product from a WooCommerce body. */ async function updateOne(ctx, productId, body) {
|
|
249
|
+
const parsed = productWriteFromWoo(body, false);
|
|
250
|
+
if ('error' in parsed) return wooError(400, 'woocommerce_rest_invalid_param', parsed.error);
|
|
251
|
+
const values = _extends({}, parsed.values);
|
|
252
|
+
const categoryIds = await storeCategoryIds(ctx, parsed.categoryIds);
|
|
253
|
+
if (categoryIds) values['categoryIds'] = categoryIds;
|
|
254
|
+
if (parsed.simpleVariant) {
|
|
255
|
+
const stored = await reread(ctx, productId);
|
|
256
|
+
if (stored && !optionsOf(stored).length && !values['options']) values['variants'] = [
|
|
257
|
+
_extends({
|
|
258
|
+
options: {}
|
|
259
|
+
}, parsed.simpleVariant)
|
|
260
|
+
];
|
|
261
|
+
}
|
|
262
|
+
if (Object.keys(values).length) {
|
|
263
|
+
const answer = await run(updateProduct(jsonRequest('PATCH', values), ctx.api, ctx.hostId, productId));
|
|
264
|
+
if (answer.status >= 400) return wooRefusalFrom(answer);
|
|
265
|
+
}
|
|
266
|
+
if ('sku' in body || 'meta_data' in body) {
|
|
267
|
+
const meta = await readProductMeta(ctx.api.firestore, ctx.hostId, productId);
|
|
268
|
+
if (typeof body['sku'] === 'string') meta.sku = body['sku'].trim();
|
|
269
|
+
meta.meta = mergeMeta(meta.meta, body['meta_data']);
|
|
270
|
+
await writeProductMeta(ctx.api.firestore, ctx.hostId, productId, meta);
|
|
271
|
+
}
|
|
272
|
+
return null;
|
|
273
|
+
}
|
|
274
|
+
async function postProduct(ctx) {
|
|
275
|
+
const created = await createOne(ctx, ctx.body);
|
|
276
|
+
if ('refusal' in created) return created.refusal;
|
|
277
|
+
ctx.note({
|
|
278
|
+
productId: created.productId
|
|
279
|
+
});
|
|
280
|
+
const data = await reread(ctx, created.productId);
|
|
281
|
+
if (!data) return wooInvalidId('product');
|
|
282
|
+
const [meta, categories] = await Promise.all([
|
|
283
|
+
readProductMeta(ctx.api.firestore, ctx.hostId, created.productId),
|
|
284
|
+
categoriesOf(ctx)
|
|
285
|
+
]);
|
|
286
|
+
return Response.json(await shapeProduct(ctx, created.productId, data, meta, categories), {
|
|
287
|
+
status: 201
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
async function putProduct(ctx, raw) {
|
|
291
|
+
const found = await productByWooId(ctx, raw);
|
|
292
|
+
if (!found) return wooInvalidId('product');
|
|
293
|
+
const refused = await updateOne(ctx, found.productId, ctx.body);
|
|
294
|
+
if (refused) return refused;
|
|
295
|
+
return getProduct(ctx, raw);
|
|
296
|
+
}
|
|
297
|
+
async function deleteProduct(ctx, raw) {
|
|
298
|
+
const found = await productByWooId(ctx, raw);
|
|
299
|
+
if (!found) return wooInvalidId('product');
|
|
300
|
+
const [meta, categories] = await Promise.all([
|
|
301
|
+
readProductMeta(ctx.api.firestore, ctx.hostId, found.productId),
|
|
302
|
+
categoriesOf(ctx)
|
|
303
|
+
]);
|
|
304
|
+
const before = await shapeProduct(ctx, found.productId, found.data, meta, categories);
|
|
305
|
+
const answer = await run(deleteProductOverApi(ctx.api, ctx.hostId, found.productId));
|
|
306
|
+
if (answer.status >= 400) return wooRefusalFrom(answer);
|
|
307
|
+
return Response.json(before);
|
|
308
|
+
}
|
|
309
|
+
async function batchProducts(ctx) {
|
|
310
|
+
const out = {
|
|
311
|
+
create: [],
|
|
312
|
+
update: [],
|
|
313
|
+
delete: []
|
|
314
|
+
};
|
|
315
|
+
const categories = await categoriesOf(ctx);
|
|
316
|
+
const asError = async (response)=>{
|
|
317
|
+
const body = await response.json().catch(()=>({}));
|
|
318
|
+
return {
|
|
319
|
+
id: 0,
|
|
320
|
+
error: {
|
|
321
|
+
code: body['code'],
|
|
322
|
+
message: body['message'],
|
|
323
|
+
data: body['data']
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
};
|
|
327
|
+
for (const body of (Array.isArray(ctx.body['create']) ? ctx.body['create'] : []).slice(0, 100)){
|
|
328
|
+
const created = await createOne(ctx, body != null ? body : {});
|
|
329
|
+
if ('refusal' in created) out['create'].push(await asError(created.refusal));
|
|
330
|
+
else {
|
|
331
|
+
var _ref;
|
|
332
|
+
const data = (_ref = await reread(ctx, created.productId)) != null ? _ref : {};
|
|
333
|
+
const meta = await readProductMeta(ctx.api.firestore, ctx.hostId, created.productId);
|
|
334
|
+
out['create'].push(await shapeProduct(ctx, created.productId, data, meta, categories));
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
for (const body of (Array.isArray(ctx.body['update']) ? ctx.body['update'] : []).slice(0, 100)){
|
|
338
|
+
var _record_id;
|
|
339
|
+
const record = body != null ? body : {};
|
|
340
|
+
const found = await productByWooId(ctx, String((_record_id = record['id']) != null ? _record_id : ''));
|
|
341
|
+
if (!found) {
|
|
342
|
+
out['update'].push(await asError(wooInvalidId('product')));
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
const refused = await updateOne(ctx, found.productId, record);
|
|
346
|
+
if (refused) out['update'].push(await asError(refused));
|
|
347
|
+
else {
|
|
348
|
+
var _ref1;
|
|
349
|
+
const data = (_ref1 = await reread(ctx, found.productId)) != null ? _ref1 : {};
|
|
350
|
+
const meta = await readProductMeta(ctx.api.firestore, ctx.hostId, found.productId);
|
|
351
|
+
out['update'].push(await shapeProduct(ctx, found.productId, data, meta, categories));
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
for (const raw of (Array.isArray(ctx.body['delete']) ? ctx.body['delete'] : []).slice(0, 100)){
|
|
355
|
+
out['delete'].push(await (await deleteProduct(ctx, String(raw))).json().catch(()=>({})));
|
|
356
|
+
}
|
|
357
|
+
return Response.json(out);
|
|
358
|
+
}
|
|
359
|
+
// ── Variations ──────────────────────────────────────────────────────────────
|
|
360
|
+
/**
|
|
361
|
+
* Find or make the variants a set of WooCommerce variation writes name, and
|
|
362
|
+
* apply their prices, in as few saves as the writes allow: one to add every
|
|
363
|
+
* missing option value, one for every variant's fields. Answers, per write,
|
|
364
|
+
* the variant id it landed on, or a refusal.
|
|
365
|
+
*/ async function applyVariations(ctx, productId, writes) {
|
|
366
|
+
var _ref;
|
|
367
|
+
const stored = await reread(ctx, productId);
|
|
368
|
+
if (!stored) return {
|
|
369
|
+
refusal: wooInvalidId('product')
|
|
370
|
+
};
|
|
371
|
+
let options = optionsOf(stored);
|
|
372
|
+
const selections = writes.map((write)=>write.variantId ? null : variationOptionsFromWoo(write.body['attributes'], options));
|
|
373
|
+
for (const selection of selections){
|
|
374
|
+
if (!selection) continue;
|
|
375
|
+
const extended = optionsWithVariation(options, selection);
|
|
376
|
+
if (extended) options = extended;
|
|
377
|
+
}
|
|
378
|
+
if (JSON.stringify(options) !== JSON.stringify(optionsOf(stored))) {
|
|
379
|
+
const answer = await run(updateProduct(jsonRequest('PATCH', {
|
|
380
|
+
options
|
|
381
|
+
}), ctx.api, ctx.hostId, productId));
|
|
382
|
+
if (answer.status >= 400) return {
|
|
383
|
+
refusal: wooRefusalFrom(answer)
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
const current = (_ref = await reread(ctx, productId)) != null ? _ref : stored;
|
|
387
|
+
const variants = variantsOf(current);
|
|
388
|
+
const byCombo = new Map(variants.map((variant)=>[
|
|
389
|
+
variantComboKey(variant.options),
|
|
390
|
+
String(variant.id)
|
|
391
|
+
]));
|
|
392
|
+
const results = [];
|
|
393
|
+
const variantWrites = [];
|
|
394
|
+
const images = [];
|
|
395
|
+
writes.forEach((write, index)=>{
|
|
396
|
+
var _write_variantId, _selections_index;
|
|
397
|
+
var _imagesFromWoo;
|
|
398
|
+
const variantId = (_write_variantId = write.variantId) != null ? _write_variantId : byCombo.get(variantComboKey((_selections_index = selections[index]) != null ? _selections_index : {}));
|
|
399
|
+
if (!variantId || !variants.some((variant)=>String(variant.id) === variantId)) {
|
|
400
|
+
results.push({
|
|
401
|
+
refusal: wooError(400, 'woocommerce_rest_invalid_param', 'The variation’s attributes do not name one of the product’s variations.')
|
|
402
|
+
});
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
const read = variantWriteFromWoo(write.body);
|
|
406
|
+
if ('error' in read) {
|
|
407
|
+
results.push({
|
|
408
|
+
refusal: wooError(400, 'woocommerce_rest_invalid_param', read.error)
|
|
409
|
+
});
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
if (Object.keys(read.write).length) variantWrites.push(_extends({
|
|
413
|
+
id: variantId
|
|
414
|
+
}, read.write));
|
|
415
|
+
const image = (_imagesFromWoo = imagesFromWoo(write.body['image'] ? [
|
|
416
|
+
write.body['image']
|
|
417
|
+
] : [])) == null ? void 0 : _imagesFromWoo[0];
|
|
418
|
+
if (image) images.push(image);
|
|
419
|
+
results.push({
|
|
420
|
+
variantId
|
|
421
|
+
});
|
|
422
|
+
});
|
|
423
|
+
const media = Array.isArray(current['mediaUrls']) ? current['mediaUrls'] : [];
|
|
424
|
+
const newImages = [
|
|
425
|
+
...new Set(images)
|
|
426
|
+
].filter((src)=>!media.includes(src));
|
|
427
|
+
if (variantWrites.length || newImages.length) {
|
|
428
|
+
const body = {};
|
|
429
|
+
if (variantWrites.length) body['variants'] = variantWrites;
|
|
430
|
+
if (newImages.length) body['mediaUrls'] = [
|
|
431
|
+
...media,
|
|
432
|
+
...newImages
|
|
433
|
+
];
|
|
434
|
+
const answer = await run(updateProduct(jsonRequest('PATCH', body), ctx.api, ctx.hostId, productId));
|
|
435
|
+
if (answer.status >= 400) return {
|
|
436
|
+
refusal: wooRefusalFrom(answer)
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
// What the app keeps on each variation: its meta and its picture.
|
|
440
|
+
const meta = await readProductMeta(ctx.api.firestore, ctx.hostId, productId);
|
|
441
|
+
let metaChanged = false;
|
|
442
|
+
writes.forEach((write, index)=>{
|
|
443
|
+
var _meta_variants_result_variantId;
|
|
444
|
+
var _imagesFromWoo;
|
|
445
|
+
const result = results[index];
|
|
446
|
+
if (!('variantId' in result)) return;
|
|
447
|
+
const entry = _extends({}, (_meta_variants_result_variantId = meta.variants[result.variantId]) != null ? _meta_variants_result_variantId : {});
|
|
448
|
+
if ('meta_data' in write.body) {
|
|
449
|
+
var _entry_meta;
|
|
450
|
+
entry.meta = mergeMeta((_entry_meta = entry.meta) != null ? _entry_meta : {}, write.body['meta_data']);
|
|
451
|
+
metaChanged = true;
|
|
452
|
+
}
|
|
453
|
+
const image = (_imagesFromWoo = imagesFromWoo(write.body['image'] ? [
|
|
454
|
+
write.body['image']
|
|
455
|
+
] : [])) == null ? void 0 : _imagesFromWoo[0];
|
|
456
|
+
if (image) {
|
|
457
|
+
entry.image = image;
|
|
458
|
+
metaChanged = true;
|
|
459
|
+
}
|
|
460
|
+
meta.variants[result.variantId] = entry;
|
|
461
|
+
});
|
|
462
|
+
if (metaChanged) await writeProductMeta(ctx.api.firestore, ctx.hostId, productId, meta);
|
|
463
|
+
return {
|
|
464
|
+
results
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
async function variationContext(ctx, rawProduct) {
|
|
468
|
+
const found = await productByWooId(ctx, rawProduct);
|
|
469
|
+
if (!found) return null;
|
|
470
|
+
return found;
|
|
471
|
+
}
|
|
472
|
+
async function shapeAllVariations(ctx, productId) {
|
|
473
|
+
var _ref;
|
|
474
|
+
const data = (_ref = await reread(ctx, productId)) != null ? _ref : {};
|
|
475
|
+
const [ids, meta] = await Promise.all([
|
|
476
|
+
idsForProduct(ctx, productId, data),
|
|
477
|
+
readProductMeta(ctx.api.firestore, ctx.hostId, productId)
|
|
478
|
+
]);
|
|
479
|
+
return {
|
|
480
|
+
data,
|
|
481
|
+
ids,
|
|
482
|
+
meta,
|
|
483
|
+
shaped: new Map(variantsOf(data).map((variant)=>[
|
|
484
|
+
String(variant.id),
|
|
485
|
+
shapeVariation(ctx, data, variant, ids.variants.get(String(variant.id)), ids.product, meta)
|
|
486
|
+
]))
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
async function listVariations(ctx, rawProduct) {
|
|
490
|
+
const found = await variationContext(ctx, rawProduct);
|
|
491
|
+
if (!found) return wooInvalidId('product');
|
|
492
|
+
const { shaped } = await shapeAllVariations(ctx, found.productId);
|
|
493
|
+
let list = [
|
|
494
|
+
...shaped.values()
|
|
495
|
+
];
|
|
496
|
+
const sku = ctx.url.searchParams.get('sku');
|
|
497
|
+
if (sku) list = list.filter((variation)=>variation.sku === sku);
|
|
498
|
+
return wooPaged(list, readWooPage(ctx.url.searchParams));
|
|
499
|
+
}
|
|
500
|
+
async function variantIdFor(ctx, productId, raw) {
|
|
501
|
+
const target = await wooIdTarget(ctx.api.firestore, ctx.hostId, Number(raw));
|
|
502
|
+
return (target == null ? void 0 : target.kind) === 'variant' && target.productId === productId ? target.variantId : null;
|
|
503
|
+
}
|
|
504
|
+
async function getVariation(ctx, rawProduct, rawVariation) {
|
|
505
|
+
const found = await variationContext(ctx, rawProduct);
|
|
506
|
+
if (!found) return wooInvalidId('product');
|
|
507
|
+
const variantId = await variantIdFor(ctx, found.productId, rawVariation);
|
|
508
|
+
const shaped = variantId ? (await shapeAllVariations(ctx, found.productId)).shaped.get(variantId) : undefined;
|
|
509
|
+
return shaped ? Response.json(shaped) : wooInvalidId('variation');
|
|
510
|
+
}
|
|
511
|
+
async function postVariation(ctx, rawProduct) {
|
|
512
|
+
const found = await variationContext(ctx, rawProduct);
|
|
513
|
+
if (!found) return wooInvalidId('product');
|
|
514
|
+
const applied = await applyVariations(ctx, found.productId, [
|
|
515
|
+
{
|
|
516
|
+
body: ctx.body
|
|
517
|
+
}
|
|
518
|
+
]);
|
|
519
|
+
if ('refusal' in applied) return applied.refusal;
|
|
520
|
+
const result = applied.results[0];
|
|
521
|
+
if ('refusal' in result) return result.refusal;
|
|
522
|
+
const shaped = (await shapeAllVariations(ctx, found.productId)).shaped.get(result.variantId);
|
|
523
|
+
return Response.json(shaped, {
|
|
524
|
+
status: 201
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
async function putVariation(ctx, rawProduct, rawVariation) {
|
|
528
|
+
const found = await variationContext(ctx, rawProduct);
|
|
529
|
+
if (!found) return wooInvalidId('product');
|
|
530
|
+
const variantId = await variantIdFor(ctx, found.productId, rawVariation);
|
|
531
|
+
if (!variantId) return wooInvalidId('variation');
|
|
532
|
+
const applied = await applyVariations(ctx, found.productId, [
|
|
533
|
+
{
|
|
534
|
+
variantId,
|
|
535
|
+
body: ctx.body
|
|
536
|
+
}
|
|
537
|
+
]);
|
|
538
|
+
if ('refusal' in applied) return applied.refusal;
|
|
539
|
+
const result = applied.results[0];
|
|
540
|
+
if ('refusal' in result) return result.refusal;
|
|
541
|
+
return Response.json((await shapeAllVariations(ctx, found.productId)).shaped.get(variantId));
|
|
542
|
+
}
|
|
543
|
+
async function deleteVariation(ctx, rawProduct, rawVariation) {
|
|
544
|
+
const found = await variationContext(ctx, rawProduct);
|
|
545
|
+
if (!found) return wooInvalidId('product');
|
|
546
|
+
const variantId = await variantIdFor(ctx, found.productId, rawVariation);
|
|
547
|
+
if (!variantId) return wooInvalidId('variation');
|
|
548
|
+
const before = (await shapeAllVariations(ctx, found.productId)).shaped.get(variantId);
|
|
549
|
+
const answer = await run(updateProductVariant(jsonRequest('PATCH', {
|
|
550
|
+
priceUsd: null
|
|
551
|
+
}), ctx.api, ctx.hostId, found.productId, variantId));
|
|
552
|
+
if (answer.status >= 400) return wooRefusalFrom(answer);
|
|
553
|
+
return Response.json(before);
|
|
554
|
+
}
|
|
555
|
+
async function batchVariations(ctx, rawProduct) {
|
|
556
|
+
const found = await variationContext(ctx, rawProduct);
|
|
557
|
+
if (!found) return wooInvalidId('product');
|
|
558
|
+
const creates = (Array.isArray(ctx.body['create']) ? ctx.body['create'] : []).slice(0, 100);
|
|
559
|
+
const updates = (Array.isArray(ctx.body['update']) ? ctx.body['update'] : []).slice(0, 100);
|
|
560
|
+
const deletes = (Array.isArray(ctx.body['delete']) ? ctx.body['delete'] : []).slice(0, 100);
|
|
561
|
+
const updateIds = await Promise.all(updates.map((body)=>{
|
|
562
|
+
var _ref;
|
|
563
|
+
return variantIdFor(ctx, found.productId, String((_ref = body == null ? void 0 : body['id']) != null ? _ref : ''));
|
|
564
|
+
}));
|
|
565
|
+
const writes = [
|
|
566
|
+
...creates.map((body)=>({
|
|
567
|
+
body: body != null ? body : {}
|
|
568
|
+
})),
|
|
569
|
+
...updates.map((body, index)=>{
|
|
570
|
+
var _updateIds_index;
|
|
571
|
+
return {
|
|
572
|
+
variantId: (_updateIds_index = updateIds[index]) != null ? _updateIds_index : '__missing__',
|
|
573
|
+
body: body != null ? body : {}
|
|
574
|
+
};
|
|
575
|
+
})
|
|
576
|
+
];
|
|
577
|
+
const applied = writes.length ? await applyVariations(ctx, found.productId, writes) : {
|
|
578
|
+
results: []
|
|
579
|
+
};
|
|
580
|
+
if ('refusal' in applied) return applied.refusal;
|
|
581
|
+
const after = await shapeAllVariations(ctx, found.productId);
|
|
582
|
+
const toEntry = async (result)=>{
|
|
583
|
+
var _after_shaped_get;
|
|
584
|
+
if ('variantId' in result) return (_after_shaped_get = after.shaped.get(result.variantId)) != null ? _after_shaped_get : {
|
|
585
|
+
id: 0
|
|
586
|
+
};
|
|
587
|
+
const body = await result.refusal.json().catch(()=>({}));
|
|
588
|
+
return {
|
|
589
|
+
id: 0,
|
|
590
|
+
error: {
|
|
591
|
+
code: body['code'],
|
|
592
|
+
message: body['message'],
|
|
593
|
+
data: body['data']
|
|
594
|
+
}
|
|
595
|
+
};
|
|
596
|
+
};
|
|
597
|
+
const createResults = await Promise.all(applied.results.slice(0, creates.length).map(toEntry));
|
|
598
|
+
const updateResults = await Promise.all(applied.results.slice(creates.length).map(toEntry));
|
|
599
|
+
const deleteResults = [];
|
|
600
|
+
for (const raw of deletes)deleteResults.push(await (await deleteVariation(ctx, rawProduct, String(raw))).json().catch(()=>({})));
|
|
601
|
+
return Response.json({
|
|
602
|
+
create: createResults,
|
|
603
|
+
update: updateResults,
|
|
604
|
+
delete: deleteResults
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
// ── Dispatch ────────────────────────────────────────────────────────────────
|
|
608
|
+
/** `products…` under `/wc/v3`. `null` when the route is not a product route. */ export async function handleWooProducts(ctx) {
|
|
609
|
+
const [, first, second, third, fourth] = ctx.segments;
|
|
610
|
+
const method = ctx.request.method;
|
|
611
|
+
const writing = method !== 'GET' && method !== 'HEAD';
|
|
612
|
+
if (writing) {
|
|
613
|
+
const refused = writeRefusal(ctx, await hostDoc(ctx));
|
|
614
|
+
if (refused) return refused;
|
|
615
|
+
} else {
|
|
616
|
+
const denied = requireScope(ctx.api, 'products:read');
|
|
617
|
+
if (denied) return wooError(403, 'woocommerce_rest_cannot_view', 'Sorry, you cannot list resources.');
|
|
618
|
+
}
|
|
619
|
+
if (first === undefined) {
|
|
620
|
+
if (method === 'GET') return listProducts(ctx);
|
|
621
|
+
if (method === 'POST') return postProduct(ctx);
|
|
622
|
+
return null;
|
|
623
|
+
}
|
|
624
|
+
if (first === 'batch' && second === undefined && (method === 'POST' || method === 'PUT' || method === 'PATCH')) return batchProducts(ctx);
|
|
625
|
+
if (first === 'categories' && second === undefined && method === 'GET') {
|
|
626
|
+
const categories = [
|
|
627
|
+
...(await categoriesOf(ctx)).values()
|
|
628
|
+
].map((category)=>_extends({}, category, {
|
|
629
|
+
parent: 0,
|
|
630
|
+
description: '',
|
|
631
|
+
display: 'default',
|
|
632
|
+
image: null,
|
|
633
|
+
menu_order: 0,
|
|
634
|
+
count: 0
|
|
635
|
+
}));
|
|
636
|
+
return wooPaged(categories, readWooPage(ctx.url.searchParams));
|
|
637
|
+
}
|
|
638
|
+
if ((first === 'tags' || first === 'attributes' || first === 'shipping_classes') && second === undefined && method === 'GET') {
|
|
639
|
+
return wooPaged([], readWooPage(ctx.url.searchParams));
|
|
640
|
+
}
|
|
641
|
+
if (!/^\d+$/.test(first)) return null;
|
|
642
|
+
if (second === undefined) {
|
|
643
|
+
if (method === 'GET') return getProduct(ctx, first);
|
|
644
|
+
if (method === 'PUT' || method === 'PATCH' || method === 'POST') return putProduct(ctx, first);
|
|
645
|
+
if (method === 'DELETE') return deleteProduct(ctx, first);
|
|
646
|
+
return null;
|
|
647
|
+
}
|
|
648
|
+
if (second !== 'variations' || fourth !== undefined) return null;
|
|
649
|
+
if (third === undefined) {
|
|
650
|
+
if (method === 'GET') return listVariations(ctx, first);
|
|
651
|
+
if (method === 'POST') return postVariation(ctx, first);
|
|
652
|
+
return null;
|
|
653
|
+
}
|
|
654
|
+
if (third === 'batch' && (method === 'POST' || method === 'PUT' || method === 'PATCH')) return batchVariations(ctx, first);
|
|
655
|
+
if (!/^\d+$/.test(third)) return wooNotFound();
|
|
656
|
+
if (method === 'GET') return getVariation(ctx, first, third);
|
|
657
|
+
if (method === 'PUT' || method === 'PATCH' || method === 'POST') return putVariation(ctx, first, third);
|
|
658
|
+
if (method === 'DELETE') return deleteVariation(ctx, first, third);
|
|
659
|
+
return null;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
//# sourceMappingURL=woo-products.js.map
|