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