Shorten printful/webflow naming convention
This commit is contained in:
@@ -7,8 +7,8 @@ export async function up(db: Kysely<any>): Promise<void> {
|
||||
.$call(addDefaultColumns)
|
||||
.addColumn("session_id", "uuid", (cb) => cb.notNull())
|
||||
.addColumn("session_name", "text", (cb) => cb.notNull())
|
||||
.addColumn("printful_product_id_filter", sql`integer[]`)
|
||||
.addColumn("syncing_printful_product_ids", sql`integer[]`, (cb) => cb
|
||||
.addColumn("p_product_id_filter", sql`integer[]`)
|
||||
.addColumn("syncing_p_product_ids", sql`integer[]`, (cb) => cb
|
||||
.notNull()
|
||||
.defaultTo(sql`'{}'::integer[]`)
|
||||
)
|
||||
|
||||
+37
-37
@@ -155,31 +155,31 @@ export const app = new Elysia()
|
||||
return {
|
||||
startDate: latestSync.started_at,
|
||||
status: s.Commerce.Sync.deriveStatus(latestSync),
|
||||
syncingPrintfulProductIds: latestSync.syncing_printful_product_ids
|
||||
syncingPProductIds: latestSync.syncing_p_product_ids
|
||||
}
|
||||
})
|
||||
// Run sync
|
||||
.post("/:printfulProductId?", async ({ params: { printfulProductId }, sessionId }) => {
|
||||
.post("/:pProductId?", async ({ params: { pProductId }, sessionId }) => {
|
||||
await s.Commerce.Sync.start({
|
||||
session: { id: sessionId, name: "Portal" },
|
||||
filter: {
|
||||
printfulProductIds: printfulProductId ? [printfulProductId] : null
|
||||
pProductIds: pProductId ? [pProductId] : null
|
||||
}
|
||||
});
|
||||
}, { params: t.Object({ printfulProductId: t.Optional(t.Numeric()) }) }),
|
||||
}, { params: t.Object({ pProductId: t.Optional(t.Numeric()) }) }),
|
||||
)
|
||||
.get("/:printfulProductId", async ({ params: { printfulProductId } }) => {
|
||||
const printfulProduct = await s.Commerce.Printful.Products.get(printfulProductId);
|
||||
if (!printfulProduct) throw new NotFoundError("Missing printful product");
|
||||
.get("/:pProductId", async ({ params: { pProductId } }) => {
|
||||
const pProduct = await s.Commerce.Printful.Products.get(pProductId);
|
||||
if (!pProduct) throw new NotFoundError("Missing printful product");
|
||||
|
||||
const webflowProductId = printfulProduct.sync_product.external_id.split("-")[0];
|
||||
if (!webflowProductId) throw new NotFoundError("Missing webflow product ID");
|
||||
const wProductId = pProduct.sync_product.external_id.split("-")[0];
|
||||
if (!wProductId) throw new NotFoundError("Missing webflow product ID");
|
||||
|
||||
const webflowProduct = await s.Commerce.Webflow.Products.get(webflowProductId);
|
||||
const wProduct = await s.Commerce.Webflow.Products.get(wProductId);
|
||||
|
||||
return { printfulProduct, webflowProduct };
|
||||
return { pProduct, wProduct };
|
||||
}, {
|
||||
params: t.Object({ printfulProductId: t.Numeric() })
|
||||
params: t.Object({ pProductId: t.Numeric() })
|
||||
})
|
||||
)
|
||||
|
||||
@@ -190,37 +190,37 @@ export const app = new Elysia()
|
||||
|
||||
switch (payload.type) {
|
||||
case Printful.Webhook.Event.ProductUpdated: {
|
||||
const printfulProduct = payload.data.sync_product;
|
||||
log.info({ productId: printfulProduct.id }, "printful webhook: product updated");
|
||||
const pProduct = payload.data.sync_product;
|
||||
log.info({ productId: pProduct.id }, "printful webhook: product updated");
|
||||
|
||||
await s.Commerce.Sync.start({
|
||||
session: { id: randomUUIDv7(), name: "Printful" },
|
||||
filter: {
|
||||
printfulProductIds: [printfulProduct.id]
|
||||
pProductIds: [pProduct.id]
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case Printful.Webhook.Event.ProductDeleted: {
|
||||
const printfulProduct = payload.data.sync_product;
|
||||
const webflowProductId = printfulProduct.external_id.split("-")[0];
|
||||
log.info({ externalId: payload.data.sync_product.external_id, webflowProductId }, "printful webhook: product deleted");
|
||||
if (!webflowProductId) throw new NotFoundError("Missing webflow product ID");
|
||||
const pProduct = payload.data.sync_product;
|
||||
const wProductId = pProduct.external_id.split("-")[0];
|
||||
log.info({ externalId: payload.data.sync_product.external_id, wProductId }, "printful webhook: product deleted");
|
||||
if (!wProductId) throw new NotFoundError("Missing webflow product ID");
|
||||
|
||||
await s.Commerce.Webflow.Products.remove(webflowProductId);
|
||||
await s.Commerce.Webflow.Products.remove(wProductId);
|
||||
break;
|
||||
}
|
||||
case Printful.Webhook.Event.PackageShipped: {
|
||||
const webflowOrderId = payload.data.order.external_id;
|
||||
const wOrderId = payload.data.order.external_id;
|
||||
const shipInfo = payload.data.shipment;
|
||||
log.info({ webflowOrderId, carrier: shipInfo.carrier, tracking: shipInfo.tracking_number }, "printful webhook: package shipped");
|
||||
log.info({ wOrderId, carrier: shipInfo.carrier, tracking: shipInfo.tracking_number }, "printful webhook: package shipped");
|
||||
|
||||
await s.Commerce.Webflow.Orders.update(webflowOrderId, {
|
||||
await s.Commerce.Webflow.Orders.update(wOrderId, {
|
||||
shippingTrackingURL: shipInfo.tracking_url,
|
||||
shippingTracking: shipInfo.tracking_number,
|
||||
shippingProvider: shipInfo.carrier,
|
||||
});
|
||||
await s.Commerce.Webflow.Orders.fulfill(webflowOrderId, {
|
||||
await s.Commerce.Webflow.Orders.fulfill(wOrderId, {
|
||||
sendOrderFulfilledEmail: true,
|
||||
});
|
||||
break;
|
||||
@@ -237,27 +237,27 @@ export const app = new Elysia()
|
||||
|
||||
switch (payload.triggerType) {
|
||||
case Webflow.Webhook.Event.OrderCreated: {
|
||||
const webflowOrder = payload.payload;
|
||||
log.info({ orderId: webflowOrder.orderId }, "webflow webhook: order created");
|
||||
const wOrder = payload.payload;
|
||||
log.info({ orderId: wOrder.orderId }, "webflow webhook: order created");
|
||||
|
||||
await s.Commerce.Printful.Orders.create({
|
||||
external_id: webflowOrder.orderId,
|
||||
external_id: wOrder.orderId,
|
||||
// TODO: derive from webflow
|
||||
shipping: "STANDARD",
|
||||
recipient: {
|
||||
name: webflowOrder.shippingAddress.addressee,
|
||||
address1: webflowOrder.shippingAddress.line1,
|
||||
address2: webflowOrder.shippingAddress.line2,
|
||||
city: webflowOrder.shippingAddress.city,
|
||||
name: wOrder.shippingAddress.addressee,
|
||||
address1: wOrder.shippingAddress.line1,
|
||||
address2: wOrder.shippingAddress.line2,
|
||||
city: wOrder.shippingAddress.city,
|
||||
state_code: zipcodesUs.find(
|
||||
webflowOrder.shippingAddress.postalCode.split("-")[0] ?? "",
|
||||
wOrder.shippingAddress.postalCode.split("-")[0] ?? "",
|
||||
).stateCode,
|
||||
country_code: webflowOrder.shippingAddress.country,
|
||||
zip: webflowOrder.shippingAddress.postalCode,
|
||||
country_code: wOrder.shippingAddress.country,
|
||||
zip: wOrder.shippingAddress.postalCode,
|
||||
},
|
||||
items: webflowOrder.purchasedItems.map((webflowOrderSku) => ({
|
||||
external_variant_id: webflowOrderSku.variantId,
|
||||
quantity: webflowOrderSku.count,
|
||||
items: wOrder.purchasedItems.map((wOrderSku) => ({
|
||||
external_variant_id: wOrderSku.variantId,
|
||||
quantity: wOrderSku.count,
|
||||
})),
|
||||
});
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ class SyncService {
|
||||
session_id: queuedSync.session.id,
|
||||
session_name: queuedSync.session.name,
|
||||
started_at: startDate,
|
||||
printful_product_id_filter: queuedSync.filter?.printfulProductIds ?? null,
|
||||
p_product_id_filter: queuedSync.filter?.pProductIds ?? null,
|
||||
};
|
||||
if (id) {
|
||||
const result = await db.updateTable("product_syncs")
|
||||
@@ -73,17 +73,17 @@ class SyncService {
|
||||
id = result.id;
|
||||
}
|
||||
},
|
||||
onStep: async (printfulProductIds: number[]) => {
|
||||
onStep: async (pProductIds: number[]) => {
|
||||
if (!id) throw new Error("Expected sync run ID");
|
||||
await db.updateTable("product_syncs")
|
||||
.set({ syncing_printful_product_ids: printfulProductIds })
|
||||
.set({ syncing_p_product_ids: pProductIds })
|
||||
.where("id", "=", id)
|
||||
.execute();
|
||||
},
|
||||
onCompletion: async (completionDate, duration) => {
|
||||
if (!id) throw new Error("Expected sync run ID");
|
||||
await db.updateTable("product_syncs")
|
||||
.set({ syncing_printful_product_ids: [], ended_at: completionDate })
|
||||
.set({ syncing_p_product_ids: [], ended_at: completionDate })
|
||||
.where("id", "=", id)
|
||||
.execute();
|
||||
freedSlot = true;
|
||||
@@ -104,7 +104,7 @@ class SyncService {
|
||||
if (Date.now() - (activeSync.started_at?.getTime() ?? 0) > 600000) {
|
||||
log.info("already active sync exceeded timeout");
|
||||
await db.updateTable("product_syncs")
|
||||
.set({ syncing_printful_product_ids: [], ended_at: new Date(), has_failed: true })
|
||||
.set({ syncing_p_product_ids: [], ended_at: new Date(), has_failed: true })
|
||||
.where("id", "=", activeSync.id)
|
||||
.execute();
|
||||
await this.start(queuedSync);
|
||||
@@ -117,7 +117,7 @@ class SyncService {
|
||||
else {
|
||||
if (id) {
|
||||
await db.updateTable("product_syncs")
|
||||
.set({ syncing_printful_product_ids: [], ended_at: new Date(), has_failed: true })
|
||||
.set({ syncing_p_product_ids: [], ended_at: new Date(), has_failed: true })
|
||||
.where("id", "=", id)
|
||||
.execute();
|
||||
freedSlot = true;
|
||||
@@ -173,7 +173,7 @@ class SyncQueueService {
|
||||
const values: Insertable<ProductSyncs> = {
|
||||
session_id: queuedSync.session.id,
|
||||
session_name: queuedSync.session.name,
|
||||
printful_product_id_filter: queuedSync.filter?.printfulProductIds ?? null
|
||||
p_product_id_filter: queuedSync.filter?.pProductIds ?? null
|
||||
};
|
||||
if (queuedSync.id) {
|
||||
await db.updateTable("product_syncs")
|
||||
@@ -204,7 +204,7 @@ class SyncQueueService {
|
||||
name: result.session_name
|
||||
},
|
||||
filter: {
|
||||
printfulProductIds: result.printful_product_id_filter
|
||||
pProductIds: result.p_product_id_filter
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
const synchronizer = $state({
|
||||
status: "none" as SyncStatus,
|
||||
syncingPrintfulProductIds: [] as number[],
|
||||
syncingPProductIds: [] as number[],
|
||||
get isInProgress() {
|
||||
return this.status === "active" || this.status === "queued";
|
||||
},
|
||||
@@ -17,11 +17,11 @@
|
||||
const res = await api.products.sync.get();
|
||||
if (res.error) {
|
||||
synchronizer.status = "none";
|
||||
synchronizer.syncingPrintfulProductIds = [];
|
||||
synchronizer.syncingPProductIds = [];
|
||||
} else {
|
||||
synchronizer.status = res.data.status;
|
||||
synchronizer.syncingPrintfulProductIds =
|
||||
res.data.syncingPrintfulProductIds;
|
||||
synchronizer.syncingPProductIds =
|
||||
res.data.syncingPProductIds;
|
||||
}
|
||||
},
|
||||
startPolling: () => {
|
||||
@@ -34,9 +34,9 @@
|
||||
synchronizer.startPolling();
|
||||
await api.products.sync.post();
|
||||
},
|
||||
sync: async (printfulProductId: number) => {
|
||||
sync: async (pProductId: number) => {
|
||||
synchronizer.startPolling();
|
||||
await api.products.sync({ printfulProductId }).post();
|
||||
await api.products.sync({ pProductId }).post();
|
||||
},
|
||||
});
|
||||
|
||||
@@ -48,18 +48,18 @@
|
||||
});
|
||||
|
||||
const isProductSynced = async (
|
||||
printfulProduct: Printful.Products.SyncProduct,
|
||||
pProduct: Printful.Products.SyncProduct,
|
||||
) => {
|
||||
const webflowProducts = await data.products.webflow;
|
||||
return webflowProducts.some(
|
||||
(p) => p.product.id === printfulProduct.external_id.split("-")[0],
|
||||
const wProducts = await data.products.webflow;
|
||||
return wProducts.some(
|
||||
(p) => p.product.id === pProduct.external_id.split("-")[0],
|
||||
);
|
||||
};
|
||||
</script>
|
||||
|
||||
{#await data.products.printful}
|
||||
<p>Loading...</p>
|
||||
{:then printfulProducts}
|
||||
{:then pProducts}
|
||||
<button
|
||||
disabled={synchronizer.isInProgress}
|
||||
onclick={() => synchronizer.syncAll()}
|
||||
@@ -81,27 +81,27 @@
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{#each printfulProducts as printfulProduct}
|
||||
{#each pProducts as pProduct}
|
||||
<tr class="hover:bg-base-300">
|
||||
<td
|
||||
><button
|
||||
onclick={async () => {
|
||||
const res = await api
|
||||
.products({
|
||||
printfulProductId:
|
||||
printfulProduct.id,
|
||||
pProductId:
|
||||
pProduct.id,
|
||||
})
|
||||
.get();
|
||||
console.log(res.data);
|
||||
}}
|
||||
class="cursor-pointer underline"
|
||||
>
|
||||
{printfulProduct.name}
|
||||
{pProduct.name}
|
||||
</button></td
|
||||
>
|
||||
<td>
|
||||
{#await isProductSynced(printfulProduct) then isSynced}
|
||||
{#if synchronizer.syncingPrintfulProductIds.includes(printfulProduct.id)}
|
||||
{#await isProductSynced(pProduct) then isSynced}
|
||||
{#if synchronizer.syncingPProductIds.includes(pProduct.id)}
|
||||
<div class="badge badge-warning">
|
||||
Syncing...
|
||||
</div>
|
||||
@@ -120,7 +120,7 @@
|
||||
<button
|
||||
disabled={synchronizer.status === "active"}
|
||||
onclick={() =>
|
||||
synchronizer.sync(printfulProduct.id)}
|
||||
synchronizer.sync(pProduct.id)}
|
||||
class="btn"
|
||||
>
|
||||
Sync
|
||||
|
||||
@@ -75,14 +75,14 @@ class ProductsClient {
|
||||
return payload.result;
|
||||
}
|
||||
|
||||
async update(printfulProductId: number, printfulProduct: DeepPartial<Printful.Products.Product>) {
|
||||
const res = await fetch(`${this.creds.apiUrl}/store/products/${printfulProductId}`, {
|
||||
async update(pProductId: number, pProduct: DeepPartial<Printful.Products.Product>) {
|
||||
const res = await fetch(`${this.creds.apiUrl}/store/products/${pProductId}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...this.creds.authHeaders,
|
||||
},
|
||||
body: JSON.stringify(printfulProduct),
|
||||
body: JSON.stringify(pProduct),
|
||||
});
|
||||
if (!res.ok) throw new PrintfulError("Failed to update Printful product", res.status, await parsePayload(res));
|
||||
}
|
||||
@@ -91,20 +91,20 @@ class ProductsClient {
|
||||
class OrdersClient {
|
||||
constructor(private creds: Credentials) { }
|
||||
|
||||
async create(printfulOrder: Printful.Orders.Order) {
|
||||
async create(pOrder: Printful.Orders.Order) {
|
||||
const res = await fetch(`${this.creds.apiUrl}/orders`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...this.creds.authHeaders,
|
||||
},
|
||||
body: JSON.stringify(printfulOrder),
|
||||
body: JSON.stringify(pOrder),
|
||||
});
|
||||
if (!res.ok) throw new PrintfulError("Failed to create Printful order", res.status, await parsePayload(res));
|
||||
}
|
||||
|
||||
async list(opt: PagingOptions = {}): Promise<Printful.Orders.Order[]> {
|
||||
const allPrintfulOrders: Printful.Orders.Order[] = [];
|
||||
const allPOrders: Printful.Orders.Order[] = [];
|
||||
let offset = opt.offset ?? 0;
|
||||
do {
|
||||
const res = await fetch(`${this.creds.apiUrl}/orders?offset=${offset}&limit=${opt.limit ?? 100}`, {
|
||||
@@ -113,11 +113,11 @@ class OrdersClient {
|
||||
});
|
||||
if (!res.ok) throw new PrintfulError("Failed to list Printful orders", res.status, await parsePayload(res));
|
||||
const payload = (await res.json()) as Printful.MetaDataMulti<Printful.Orders.Order>;
|
||||
allPrintfulOrders.push(...payload.result);
|
||||
offset = allPrintfulOrders.length;
|
||||
if (allPrintfulOrders.length >= payload.paging.total) break;
|
||||
allPOrders.push(...payload.result);
|
||||
offset = allPOrders.length;
|
||||
if (allPOrders.length >= payload.paging.total) break;
|
||||
} while (opt.forceAll);
|
||||
return allPrintfulOrders;
|
||||
return allPOrders;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+128
-128
@@ -11,19 +11,19 @@ type ProductEntry = {
|
||||
product: Printful.Products.Product;
|
||||
};
|
||||
|
||||
type MetaPrintfulProduct = {
|
||||
type PMetaProduct = {
|
||||
name: string;
|
||||
webflowProductId: string;
|
||||
wProductId: string;
|
||||
entries: ProductEntry[];
|
||||
};
|
||||
|
||||
export type ProductSyncerOptions = {
|
||||
filter?: {
|
||||
printfulProductIds: number[] | null;
|
||||
pProductIds: number[] | null;
|
||||
},
|
||||
onStart?: (startDate: Date) => Promise<void>
|
||||
onCompletion?: (completionDate: Date, duration: number) => Promise<void>
|
||||
onStep?: (printfulProductIds: number[]) => Promise<void>
|
||||
onStep?: (pProductIds: number[]) => Promise<void>
|
||||
};
|
||||
|
||||
export class ProductSyncer {
|
||||
@@ -41,38 +41,38 @@ export class ProductSyncer {
|
||||
const startDate = new Date();
|
||||
await opt.onStart?.(startDate);
|
||||
|
||||
if (opt.filter?.printfulProductIds)
|
||||
this.log.info({ printfulProductIds: opt.filter.printfulProductIds }, "sync started (filtered)");
|
||||
if (opt.filter?.pProductIds)
|
||||
this.log.info({ pProductIds: opt.filter.pProductIds }, "sync started (filtered)");
|
||||
else
|
||||
this.log.info("sync started (all)");
|
||||
|
||||
this.log.debug("retrieving webflow products");
|
||||
const allWebflowProducts = await this.Webflow.Products.list({ forceAll: true });
|
||||
const allWProducts = await this.Webflow.Products.list({ forceAll: true });
|
||||
|
||||
this.log.debug("retrieving printful products");
|
||||
const allPrintfulProducts = await this.Printful.Products.list({ forceAll: true });
|
||||
const allPProducts = await this.Printful.Products.list({ forceAll: true });
|
||||
|
||||
this.log.info({ printfulProductCount: allPrintfulProducts.length, filter: opt.filter ?? "N/A" }, "generating meta printful products");
|
||||
const metaPrintfulProducts = await this.generateMetaPrintfulProducts(allWebflowProducts, allPrintfulProducts, opt);
|
||||
this.log.info({ pProductCount: allPProducts.length, filter: opt.filter ?? "N/A" }, "generating printful meta products");
|
||||
const pMetaProducts = await this.generatePMetaProducts(allWProducts, allPProducts, opt);
|
||||
|
||||
for (const metaPrintfulProduct of metaPrintfulProducts) {
|
||||
const printfulProductIds = metaPrintfulProduct.entries.map((e) => e.product.sync_product.id);
|
||||
this.log.info({ name: metaPrintfulProduct.name, externalId: metaPrintfulProduct.webflowProductId, printfulProductIds }, "syncing meta printful product");
|
||||
await opt.onStep?.(printfulProductIds);
|
||||
for (const pMetaProduct of pMetaProducts) {
|
||||
const pProductIds = pMetaProduct.entries.map((e) => e.product.sync_product.id);
|
||||
this.log.info({ name: pMetaProduct.name, externalId: pMetaProduct.wProductId, pProductIds }, "syncing printful meta product");
|
||||
await opt.onStep?.(pProductIds);
|
||||
|
||||
const newWebflowSkus: DeepPartial<Webflow.Products.Skus.Sku>[] = this.generateWebflowSkus(metaPrintfulProduct);
|
||||
const newWSkus: DeepPartial<Webflow.Products.Skus.Sku>[] = this.generateWSkus(pMetaProduct);
|
||||
const foundColors = new Set<string>(
|
||||
newWebflowSkus.map((sku) => sku.fieldData?.["sku-values"]?.["color"]).filter((v) => v !== undefined)
|
||||
newWSkus.map((sku) => sku.fieldData?.["sku-values"]?.["color"]).filter((v) => v !== undefined)
|
||||
);
|
||||
const foundSizes = new Set<string>(
|
||||
newWebflowSkus.map((sku) => sku.fieldData?.["sku-values"]?.["size"]).filter((v) => v !== undefined)
|
||||
newWSkus.map((sku) => sku.fieldData?.["sku-values"]?.["size"]).filter((v) => v !== undefined)
|
||||
);
|
||||
|
||||
if (!newWebflowSkus[0]) throw new Error("no webflow SKUs generated — all variants were filtered out");
|
||||
if (!newWSkus[0]) throw new Error("no webflow SKUs generated — all variants were filtered out");
|
||||
|
||||
const webflowProductFieldData = {
|
||||
name: metaPrintfulProduct.name,
|
||||
slug: formatSlug(metaPrintfulProduct.name),
|
||||
const wProductFieldData = {
|
||||
name: pMetaProduct.name,
|
||||
slug: formatSlug(pMetaProduct.name),
|
||||
shippable: true,
|
||||
"tax-category": "standard-taxable",
|
||||
"sku-properties": [
|
||||
@@ -97,101 +97,101 @@ export class ProductSyncer {
|
||||
],
|
||||
};
|
||||
|
||||
const webflowProduct = allWebflowProducts.find((wp) => wp.product.id === metaPrintfulProduct.webflowProductId);
|
||||
const wProduct = allWProducts.find((wp) => wp.product.id === pMetaProduct.wProductId);
|
||||
|
||||
if (webflowProduct) {
|
||||
this.log.info({ id: webflowProduct.product.id }, "existing webflow product found, updating it");
|
||||
if (wProduct) {
|
||||
this.log.info({ id: wProduct.product.id }, "existing webflow product found, updating it");
|
||||
|
||||
// do not update images
|
||||
for (const sku of newWebflowSkus) delete sku.fieldData?.["main-image"];
|
||||
for (const sku of newWSkus) delete sku.fieldData?.["main-image"];
|
||||
|
||||
// handle case where webflow SKU created by associated printful variant external_id update failed
|
||||
if (!newWebflowSkus[0].id) {
|
||||
this.log.warn({ webflowSku: newWebflowSkus[0] }, "missing webflow SKU id");
|
||||
const webflowSkuMatch = this.resolveWebflowSku(
|
||||
webflowProduct.skus,
|
||||
newWebflowSkus[0].fieldData?.["sku-values"]?.["color"],
|
||||
newWebflowSkus[0].fieldData?.["sku-values"]?.["size"],
|
||||
if (!newWSkus[0].id) {
|
||||
this.log.warn({ wSku: newWSkus[0] }, "missing webflow SKU id");
|
||||
const wSkuMatch = this.resolveWSku(
|
||||
wProduct.skus,
|
||||
newWSkus[0].fieldData?.["sku-values"]?.["color"],
|
||||
newWSkus[0].fieldData?.["sku-values"]?.["size"],
|
||||
);
|
||||
|
||||
if (webflowSkuMatch)
|
||||
newWebflowSkus[0].id = webflowSkuMatch.id;
|
||||
if (wSkuMatch)
|
||||
newWSkus[0].id = wSkuMatch.id;
|
||||
else
|
||||
this.log.warn({ webflowSku: newWebflowSkus[0] }, "could not find existing webflow SKU that matches");
|
||||
this.log.warn({ wSku: newWSkus[0] }, "could not find existing webflow SKU that matches");
|
||||
}
|
||||
|
||||
await this.Webflow.Products.update(webflowProduct.product.id, {
|
||||
product: { fieldData: webflowProductFieldData },
|
||||
sku: newWebflowSkus[0],
|
||||
await this.Webflow.Products.update(wProduct.product.id, {
|
||||
product: { fieldData: wProductFieldData },
|
||||
sku: newWSkus[0],
|
||||
});
|
||||
|
||||
for (const newWebflowSku of newWebflowSkus) {
|
||||
const existingWebflowSku = this.resolveWebflowSku(
|
||||
webflowProduct.skus,
|
||||
newWebflowSku.fieldData?.["sku-values"]?.["color"],
|
||||
newWebflowSku.fieldData?.["sku-values"]?.["size"],
|
||||
newWebflowSku.id,
|
||||
for (const newWSku of newWSkus) {
|
||||
const existingWSku = this.resolveWSku(
|
||||
wProduct.skus,
|
||||
newWSku.fieldData?.["sku-values"]?.["color"],
|
||||
newWSku.fieldData?.["sku-values"]?.["size"],
|
||||
newWSku.id,
|
||||
);
|
||||
if (existingWebflowSku) {
|
||||
if (existingWSku) {
|
||||
await this.Webflow.Products.Skus.update(
|
||||
metaPrintfulProduct.webflowProductId,
|
||||
existingWebflowSku.id,
|
||||
newWebflowSku,
|
||||
pMetaProduct.wProductId,
|
||||
existingWSku.id,
|
||||
newWSku,
|
||||
);
|
||||
} else {
|
||||
await this.Webflow.Products.Skus.create(
|
||||
metaPrintfulProduct.webflowProductId,
|
||||
[newWebflowSku],
|
||||
pMetaProduct.wProductId,
|
||||
[newWSku],
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this.log.info("existing webflow product not found, creating it");
|
||||
|
||||
const webflowProductId = await this.Webflow.Products.create({
|
||||
product: { fieldData: webflowProductFieldData },
|
||||
sku: newWebflowSkus[0],
|
||||
const wProductId = await this.Webflow.Products.create({
|
||||
product: { fieldData: wProductFieldData },
|
||||
sku: newWSkus[0],
|
||||
});
|
||||
metaPrintfulProduct.webflowProductId = webflowProductId;
|
||||
pMetaProduct.wProductId = wProductId;
|
||||
|
||||
if (newWebflowSkus.length > 1)
|
||||
await this.Webflow.Products.Skus.create(webflowProductId, newWebflowSkus.slice(1));
|
||||
if (newWSkus.length > 1)
|
||||
await this.Webflow.Products.Skus.create(wProductId, newWSkus.slice(1));
|
||||
}
|
||||
|
||||
// Re-fetch after SKU mutations so newly created SKUs have their real IDs.
|
||||
const freshWebflowProduct = await this.Webflow.Products.get(metaPrintfulProduct.webflowProductId);
|
||||
if (!freshWebflowProduct) throw new Error("webflow product missing");
|
||||
const freshWProduct = await this.Webflow.Products.get(pMetaProduct.wProductId);
|
||||
if (!freshWProduct) throw new Error("webflow product missing");
|
||||
|
||||
// Update printful external IDs
|
||||
for (const { colorGroup, product: printfulProduct } of metaPrintfulProduct.entries) {
|
||||
for (const { colorGroup, product: pProduct } of pMetaProduct.entries) {
|
||||
const expectedExternalId = colorGroup ?
|
||||
`${metaPrintfulProduct.webflowProductId}-${colorGroup}` :
|
||||
metaPrintfulProduct.webflowProductId;
|
||||
if (printfulProduct.sync_product.external_id === expectedExternalId) continue;
|
||||
`${pMetaProduct.wProductId}-${colorGroup}` :
|
||||
pMetaProduct.wProductId;
|
||||
if (pProduct.sync_product.external_id === expectedExternalId) continue;
|
||||
|
||||
const printfulVariantPatches: DeepPartial<Printful.Products.SyncVariant>[] = [];
|
||||
for (const printfulVariant of printfulProduct.sync_variants) {
|
||||
const webflowSku = this.resolveWebflowSku(
|
||||
freshWebflowProduct.skus,
|
||||
colorGroup ?? printfulVariant.color,
|
||||
printfulVariant.size,
|
||||
const pVariantPatches: DeepPartial<Printful.Products.SyncVariant>[] = [];
|
||||
for (const pVariant of pProduct.sync_variants) {
|
||||
const wSku = this.resolveWSku(
|
||||
freshWProduct.skus,
|
||||
colorGroup ?? pVariant.color,
|
||||
pVariant.size,
|
||||
);
|
||||
if (webflowSku) {
|
||||
printfulVariantPatches.push({
|
||||
id: printfulVariant.id,
|
||||
external_id: String(webflowSku.id),
|
||||
if (wSku) {
|
||||
pVariantPatches.push({
|
||||
id: pVariant.id,
|
||||
external_id: String(wSku.id),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await sleep(10000);
|
||||
this.log.info({ printfulProduct: printfulProduct.sync_product.id, externalId: expectedExternalId }, "updating printful product's external ID");
|
||||
await this.Printful.Products.update(printfulProduct.sync_product.id, {
|
||||
this.log.info({ pProduct: pProduct.sync_product.id, externalId: expectedExternalId }, "updating printful product's external ID");
|
||||
await this.Printful.Products.update(pProduct.sync_product.id, {
|
||||
sync_product: {
|
||||
id: printfulProduct.sync_product.id,
|
||||
id: pProduct.sync_product.id,
|
||||
external_id: expectedExternalId,
|
||||
},
|
||||
sync_variants: printfulVariantPatches,
|
||||
sync_variants: pVariantPatches,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -207,105 +207,105 @@ export class ProductSyncer {
|
||||
return m?.[1] ?? null;
|
||||
}
|
||||
|
||||
private generateWebflowSkus(metaPrintfulProduct: MetaPrintfulProduct): DeepPartial<Webflow.Products.Skus.Sku>[] {
|
||||
const webflowSkus: DeepPartial<Webflow.Products.Skus.Sku>[] = [];
|
||||
for (const { colorGroup, product: printfulProduct } of metaPrintfulProduct.entries) {
|
||||
private generateWSkus(pMetaProduct: PMetaProduct): DeepPartial<Webflow.Products.Skus.Sku>[] {
|
||||
const wSkus: DeepPartial<Webflow.Products.Skus.Sku>[] = [];
|
||||
for (const { colorGroup, product: pProduct } of pMetaProduct.entries) {
|
||||
const isColorGrouped = colorGroup !== null;
|
||||
for (const printfulVariant of printfulProduct.sync_variants) {
|
||||
for (const pVariant of pProduct.sync_variants) {
|
||||
if (isColorGrouped) {
|
||||
// Only include sizes present across every color variant.
|
||||
const sizeInAll = metaPrintfulProduct.entries.every((e) =>
|
||||
e.product.sync_variants.some((sv) => sv.size === printfulVariant.size)
|
||||
const sizeInAll = pMetaProduct.entries.every((e) =>
|
||||
e.product.sync_variants.some((sv) => sv.size === pVariant.size)
|
||||
);
|
||||
if (!sizeInAll) continue;
|
||||
}
|
||||
|
||||
const color = isColorGrouped ?
|
||||
colorGroup :
|
||||
printfulVariant.color;
|
||||
pVariant.color;
|
||||
|
||||
this.log.debug(
|
||||
{ color, size: printfulVariant.size, retailPrice: printfulVariant.retail_price },
|
||||
{ color, size: pVariant.size, retailPrice: pVariant.retail_price },
|
||||
"generating webflow SKU from printful variant"
|
||||
);
|
||||
|
||||
webflowSkus.push({
|
||||
id: printfulVariant.external_id,
|
||||
wSkus.push({
|
||||
id: pVariant.external_id,
|
||||
fieldData: {
|
||||
name: printfulVariant.name,
|
||||
slug: formatSlug(printfulVariant.name),
|
||||
name: pVariant.name,
|
||||
slug: formatSlug(pVariant.name),
|
||||
"sku-values": {
|
||||
color,
|
||||
size: printfulVariant.size,
|
||||
size: pVariant.size,
|
||||
},
|
||||
price: {
|
||||
value: Math.round(+printfulVariant.retail_price * 100),
|
||||
unit: printfulVariant.currency,
|
||||
currency: printfulVariant.currency,
|
||||
value: Math.round(+pVariant.retail_price * 100),
|
||||
unit: pVariant.currency,
|
||||
currency: pVariant.currency,
|
||||
},
|
||||
"main-image": PrintfulClient.Util.getVariantMainImage(printfulVariant),
|
||||
"main-image": PrintfulClient.Util.getVariantMainImage(pVariant),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return webflowSkus;
|
||||
return wSkus;
|
||||
}
|
||||
|
||||
async generateMetaPrintfulProducts(
|
||||
allWebflowProducts: Webflow.Products.ProductAndSkus[],
|
||||
allPrintfulProducts: Printful.Products.SyncProduct[],
|
||||
async generatePMetaProducts(
|
||||
allWProducts: Webflow.Products.ProductAndSkus[],
|
||||
allPProducts: Printful.Products.SyncProduct[],
|
||||
opt: ProductSyncerOptions,
|
||||
) {
|
||||
const metaNameFilter = opt.filter?.printfulProductIds
|
||||
?.map((id) => allPrintfulProducts.find((p) => p.id === id))
|
||||
const metaNameFilter = opt.filter?.pProductIds
|
||||
?.map((id) => allPProducts.find((p) => p.id === id))
|
||||
?.filter((p) => p !== undefined)
|
||||
?.map((p) => this.getMetaPrintfulProductName(p));
|
||||
?.map((p) => this.getPMetaProductName(p));
|
||||
|
||||
const metaPrintfulProducts: MetaPrintfulProduct[] = [];
|
||||
for (const printfulProduct of allPrintfulProducts) {
|
||||
const metaName = this.getMetaPrintfulProductName(printfulProduct);
|
||||
const colorGroup = this.parseColorGroup(printfulProduct.name);
|
||||
const webflowProductId = this.isPrintfulProductSynced(printfulProduct, allWebflowProducts) ?
|
||||
printfulProduct.external_id.split("-")[0] ?? "" :
|
||||
const pMetaProducts: PMetaProduct[] = [];
|
||||
for (const pProduct of allPProducts) {
|
||||
const metaName = this.getPMetaProductName(pProduct);
|
||||
const colorGroup = this.parseColorGroup(pProduct.name);
|
||||
const wProductId = this.isPProductSynced(pProduct, allWProducts) ?
|
||||
pProduct.external_id.split("-")[0] ?? "" :
|
||||
"";
|
||||
|
||||
if (metaNameFilter && !metaNameFilter.includes(metaName)) continue;
|
||||
|
||||
let metaPrintfulProduct = metaPrintfulProducts.find((mp) => mp.name === metaName);
|
||||
if (!metaPrintfulProduct) {
|
||||
this.log.debug({ metaName, colorGroup, webflowProductId }, "generating meta printful product");
|
||||
metaPrintfulProduct = {
|
||||
let pMetaProduct = pMetaProducts.find((mp) => mp.name === metaName);
|
||||
if (!pMetaProduct) {
|
||||
this.log.debug({ metaName, colorGroup, wProductId }, "generating printful meta product");
|
||||
pMetaProduct = {
|
||||
name: metaName,
|
||||
webflowProductId,
|
||||
wProductId,
|
||||
entries: [],
|
||||
};
|
||||
metaPrintfulProducts.push(metaPrintfulProduct);
|
||||
} else if (!metaPrintfulProduct.webflowProductId && webflowProductId) {
|
||||
// Prefer a non-empty webflowProductId so a newly added color doesn't shadow an already-synced color's ID.
|
||||
metaPrintfulProduct.webflowProductId = webflowProductId;
|
||||
pMetaProducts.push(pMetaProduct);
|
||||
} else if (!pMetaProduct.wProductId && wProductId) {
|
||||
// Prefer a non-empty wProductId so a newly added color doesn't shadow an already-synced color's ID.
|
||||
pMetaProduct.wProductId = wProductId;
|
||||
}
|
||||
|
||||
const fullPrintfulProduct = await this.Printful.Products.get(printfulProduct.id);
|
||||
if (!fullPrintfulProduct) throw new Error(`Printful product ${printfulProduct.id} not found`);
|
||||
const fullPProduct = await this.Printful.Products.get(pProduct.id);
|
||||
if (!fullPProduct) throw new Error(`Printful product ${pProduct.id} not found`);
|
||||
|
||||
const isDuplicate = allPrintfulProducts.some((p) => p.id !== printfulProduct.id && p.name === printfulProduct.name);
|
||||
if (isDuplicate) this.log.warn({ printfulProductName: printfulProduct.name }, "found duplicate printful product");
|
||||
const isDuplicate = allPProducts.some((p) => p.id !== pProduct.id && p.name === pProduct.name);
|
||||
if (isDuplicate) this.log.warn({ pProductName: pProduct.name }, "found duplicate printful product");
|
||||
|
||||
this.log.debug({ name: metaName, colorGroup }, "adding entry to meta printful product");
|
||||
metaPrintfulProduct.entries.push({ colorGroup, product: fullPrintfulProduct });
|
||||
this.log.debug({ name: metaName, colorGroup }, "adding entry to printful meta product");
|
||||
pMetaProduct.entries.push({ colorGroup, product: fullPProduct });
|
||||
}
|
||||
|
||||
return metaPrintfulProducts;
|
||||
return pMetaProducts;
|
||||
}
|
||||
|
||||
getMetaPrintfulProductName(printfulProduct: Printful.Products.SyncProduct): string {
|
||||
const color = this.parseColorGroup(printfulProduct.name);
|
||||
if (color) return printfulProduct.name.replace(`[${color}]`, "").trimEnd();
|
||||
return printfulProduct.name;
|
||||
getPMetaProductName(pProduct: Printful.Products.SyncProduct): string {
|
||||
const color = this.parseColorGroup(pProduct.name);
|
||||
if (color) return pProduct.name.replace(`[${color}]`, "").trimEnd();
|
||||
return pProduct.name;
|
||||
}
|
||||
|
||||
private resolveWebflowSku(
|
||||
private resolveWSku(
|
||||
existingSkus: Webflow.Products.Skus.Sku[],
|
||||
color: string | undefined,
|
||||
size: string | undefined,
|
||||
@@ -319,7 +319,7 @@ export class ProductSyncer {
|
||||
);
|
||||
}
|
||||
|
||||
private isPrintfulProductSynced(printfulProduct: Printful.Products.SyncProduct, allWebflowProducts: Webflow.Products.ProductAndSkus[]) {
|
||||
return allWebflowProducts.some((wp) => wp.product.id === printfulProduct.external_id.split("-")[0]);
|
||||
private isPProductSynced(pProduct: Printful.Products.SyncProduct, allWProducts: Webflow.Products.ProductAndSkus[]) {
|
||||
return allWProducts.some((wp) => wp.product.id === pProduct.external_id.split("-")[0]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,11 +34,11 @@ class SkusClient {
|
||||
constructor(private creds: Credentials) { }
|
||||
|
||||
async create(
|
||||
webflowProductId: string,
|
||||
wProductId: string,
|
||||
skus: DeepPartial<Webflow.Products.Skus.Sku>[],
|
||||
): Promise<string[]> {
|
||||
const res = await fetch(
|
||||
`${this.creds.apiSitesUrl}/products/${webflowProductId}/skus`,
|
||||
`${this.creds.apiSitesUrl}/products/${wProductId}/skus`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -54,19 +54,19 @@ class SkusClient {
|
||||
}
|
||||
|
||||
async update(
|
||||
webflowProductId: string,
|
||||
webflowSkuId: string,
|
||||
webflowSku: DeepPartial<Webflow.Products.Skus.Sku>,
|
||||
wProductId: string,
|
||||
wSkuId: string,
|
||||
wSku: DeepPartial<Webflow.Products.Skus.Sku>,
|
||||
): Promise<void> {
|
||||
const res = await fetch(
|
||||
`${this.creds.apiSitesUrl}/products/${webflowProductId}/skus/${webflowSkuId}`,
|
||||
`${this.creds.apiSitesUrl}/products/${wProductId}/skus/${wSkuId}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...this.creds.authHeader,
|
||||
},
|
||||
body: JSON.stringify({ sku: webflowSku }),
|
||||
body: JSON.stringify({ sku: wSku }),
|
||||
},
|
||||
);
|
||||
if (!res.ok) throw new WebflowError("Failed to update Webflow product SKU", res.status, await parsePayload(res));
|
||||
@@ -81,7 +81,7 @@ class ProductsClient {
|
||||
}
|
||||
|
||||
async create(
|
||||
webflowProductAndSku: DeepPartial<Webflow.Products.ProductAndSku>,
|
||||
wProductAndSku: DeepPartial<Webflow.Products.ProductAndSku>,
|
||||
): Promise<string> {
|
||||
const res = await fetch(`${this.creds.apiSitesUrl}/products`, {
|
||||
method: "POST",
|
||||
@@ -89,7 +89,7 @@ class ProductsClient {
|
||||
"Content-Type": "application/json",
|
||||
...this.creds.authHeader,
|
||||
},
|
||||
body: JSON.stringify(webflowProductAndSku),
|
||||
body: JSON.stringify(wProductAndSku),
|
||||
});
|
||||
if (!res.ok) throw new WebflowError("Failed to create Webflow product", res.status, await parsePayload(res));
|
||||
const payload = (await res.json()) as { product: { id: string } };
|
||||
@@ -97,7 +97,7 @@ class ProductsClient {
|
||||
}
|
||||
|
||||
async list(opt: PagingOptions = {}): Promise<Webflow.Products.ProductAndSkus[]> {
|
||||
const allWebflowProducts: Webflow.Products.ProductAndSkus[] = [];
|
||||
const allWProducts: Webflow.Products.ProductAndSkus[] = [];
|
||||
let offset = opt.offset ?? 0;
|
||||
do {
|
||||
const res = await fetch(`${this.creds.apiSitesUrl}/products?offset=${offset}&limit=${opt.limit ?? 100}`, {
|
||||
@@ -106,15 +106,15 @@ class ProductsClient {
|
||||
});
|
||||
if (!res.ok) throw new WebflowError("Failed to list Webflow products", res.status, await parsePayload(res));
|
||||
const payload = (await res.json()) as Webflow.MetaDataMulti<"items", Webflow.Products.ProductAndSkus>;
|
||||
allWebflowProducts.push(...payload.items);
|
||||
offset = allWebflowProducts.length;
|
||||
if (allWebflowProducts.length >= (payload?.pagination?.total ?? 0)) break;
|
||||
allWProducts.push(...payload.items);
|
||||
offset = allWProducts.length;
|
||||
if (allWProducts.length >= (payload?.pagination?.total ?? 0)) break;
|
||||
} while (opt.forceAll);
|
||||
return allWebflowProducts;
|
||||
return allWProducts;
|
||||
}
|
||||
|
||||
async get(webflowProductId: string): Promise<Webflow.Products.ProductAndSkus | undefined> {
|
||||
const res = await fetch(`${this.creds.apiSitesUrl}/products/${webflowProductId}`, {
|
||||
async get(wProductId: string): Promise<Webflow.Products.ProductAndSkus | undefined> {
|
||||
const res = await fetch(`${this.creds.apiSitesUrl}/products/${wProductId}`, {
|
||||
method: "GET",
|
||||
headers: this.creds.authHeader,
|
||||
});
|
||||
@@ -124,23 +124,23 @@ class ProductsClient {
|
||||
}
|
||||
|
||||
async update(
|
||||
webflowProductId: string,
|
||||
webflowProduct: DeepPartial<Webflow.Products.ProductAndSku>,
|
||||
wProductId: string,
|
||||
wProduct: DeepPartial<Webflow.Products.ProductAndSku>,
|
||||
): Promise<void> {
|
||||
const res = await fetch(`${this.creds.apiSitesUrl}/products/${webflowProductId}`, {
|
||||
const res = await fetch(`${this.creds.apiSitesUrl}/products/${wProductId}`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...this.creds.authHeader,
|
||||
},
|
||||
body: JSON.stringify(webflowProduct),
|
||||
body: JSON.stringify(wProduct),
|
||||
});
|
||||
if (!res.ok) throw new WebflowError("Failed to update Webflow product", res.status, await parsePayload(res));
|
||||
}
|
||||
|
||||
async remove(webflowProductId: string): Promise<void> {
|
||||
async remove(wProductId: string): Promise<void> {
|
||||
const res = await fetch(
|
||||
`${this.creds.apiCollectionsUrl}/items/${webflowProductId}`,
|
||||
`${this.creds.apiCollectionsUrl}/items/${wProductId}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
@@ -179,30 +179,30 @@ class OrdersClient {
|
||||
}
|
||||
|
||||
async update(
|
||||
webflowOrderId: string,
|
||||
webflowOrderUpdate: {
|
||||
wOrderId: string,
|
||||
wOrderUpdate: {
|
||||
comment?: string;
|
||||
shippingProvider?: string;
|
||||
shippingTracking?: string;
|
||||
shippingTrackingURL: string;
|
||||
},
|
||||
): Promise<void> {
|
||||
const res = await fetch(`${this.creds.apiSitesUrl}/orders/${webflowOrderId}`, {
|
||||
const res = await fetch(`${this.creds.apiSitesUrl}/orders/${wOrderId}`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...this.creds.authHeader,
|
||||
},
|
||||
body: JSON.stringify(webflowOrderUpdate),
|
||||
body: JSON.stringify(wOrderUpdate),
|
||||
});
|
||||
if (!res.ok) throw new WebflowError("Failed to update Webflow order", res.status, await parsePayload(res));
|
||||
}
|
||||
|
||||
async fulfill(
|
||||
webflowOrderId: string,
|
||||
wOrderId: string,
|
||||
opt: { sendOrderFulfilledEmail?: boolean } = {},
|
||||
): Promise<void> {
|
||||
const res = await fetch(`${this.creds.apiSitesUrl}/orders/${webflowOrderId}/fulfill`, {
|
||||
const res = await fetch(`${this.creds.apiSitesUrl}/orders/${wOrderId}/fulfill`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
|
||||
Reference in New Issue
Block a user