@stacksjs/commerce 0.75.515 → 0.75.518
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/dist/auctions/bids/fetch.js +1 -1
- package/dist/auctions/bids/place.js +1 -1
- package/dist/auctions/engine/increments.js +1 -1
- package/dist/auctions/engine/proxy.js +1 -1
- package/dist/auctions/engine/winners.js +1 -1
- package/dist/auctions/lots/fetch.js +1 -1
- package/dist/auctions/lots/lifecycle.js +1 -1
- package/dist/auctions/pledges/index.js +1 -1
- package/dist/auctions/realtime.js +1 -1
- package/dist/carts/destroy.js +1 -1
- package/dist/carts/fetch.js +1 -1
- package/dist/carts/store.js +1 -1
- package/dist/carts/update.js +1 -1
- package/dist/catalog.js +1 -1
- package/dist/coupons/destroy.js +1 -1
- package/dist/coupons/fetch.js +1 -1
- package/dist/coupons/store.js +1 -1
- package/dist/coupons/update.js +2 -2
- package/dist/customers/destroy.js +1 -1
- package/dist/customers/fetch.js +1 -1
- package/dist/customers/store.js +1 -1
- package/dist/customers/update.js +1 -1
- package/dist/devices/destroy.js +1 -1
- package/dist/devices/export.js +1 -1
- package/dist/devices/fetch.js +1 -1
- package/dist/devices/store.js +1 -1
- package/dist/devices/update.js +1 -1
- package/dist/dsfinvk.js +4 -4
- package/dist/errors/destroy.js +1 -1
- package/dist/errors/fetch.js +3 -3
- package/dist/errors/update.js +1 -1
- package/dist/fiskaly.js +1 -1
- package/dist/gdpdu-dtd.js +1 -1
- package/dist/gift-cards/destroy.js +1 -1
- package/dist/gift-cards/fetch.js +1 -1
- package/dist/gift-cards/store.js +1 -1
- package/dist/gift-cards/update.js +2 -2
- package/dist/imports/account-mapping.js +1 -1
- package/dist/imports/account-writer.js +1 -1
- package/dist/imports/admin-http.js +1 -1
- package/dist/imports/credentials.js +1 -1
- package/dist/imports/http.js +1 -1
- package/dist/imports/identity.js +1 -1
- package/dist/imports/money.js +1 -1
- package/dist/imports/shopify-admin.js +1 -1
- package/dist/imports/shopify.js +1 -1
- package/dist/imports/shopware-admin.js +1 -1
- package/dist/imports/shopware.js +1 -1
- package/dist/imports/text.js +1 -1
- package/dist/imports/woocommerce-admin.js +1 -1
- package/dist/imports/woocommerce.js +1 -1
- package/dist/imports/writer.js +1 -1
- package/dist/inventory.js +1 -1
- package/dist/kassensichv.js +1 -1
- package/dist/money.js +1 -1
- package/dist/orders/destroy.js +1 -1
- package/dist/orders/events.js +1 -1
- package/dist/orders/export.js +1 -1
- package/dist/orders/fetch.js +1 -1
- package/dist/orders/guards.js +1 -1
- package/dist/orders/place-order.js +1 -1
- package/dist/orders/store.js +1 -1
- package/dist/orders/totals.js +1 -1
- package/dist/orders/transition.js +1 -1
- package/dist/orders/update.js +1 -1
- package/dist/orders/webhook.js +1 -1
- package/dist/payments/destroy.js +1 -1
- package/dist/payments/fetch.js +1 -1
- package/dist/payments/store.js +1 -1
- package/dist/payments/update.js +2 -2
- package/dist/products/categories/destroy.js +1 -1
- package/dist/products/categories/fetch.js +1 -1
- package/dist/products/categories/store.js +1 -1
- package/dist/products/categories/update.js +1 -1
- package/dist/products/items/destroy.js +1 -1
- package/dist/products/items/fetch.js +1 -1
- package/dist/products/items/store.js +1 -1
- package/dist/products/items/update.js +1 -1
- package/dist/products/manufacturers/destroy.js +1 -1
- package/dist/products/manufacturers/fetch.js +1 -1
- package/dist/products/manufacturers/store.js +1 -1
- package/dist/products/manufacturers/update.js +1 -1
- package/dist/products/reviews/destroy.js +1 -1
- package/dist/products/reviews/fetch.js +1 -1
- package/dist/products/reviews/stats.js +1 -1
- package/dist/products/reviews/store.js +1 -1
- package/dist/products/reviews/update.js +1 -1
- package/dist/products/units/destroy.js +1 -1
- package/dist/products/units/fetch.js +1 -1
- package/dist/products/units/store.js +1 -1
- package/dist/products/units/update.js +1 -1
- package/dist/products/variants/destroy.js +1 -1
- package/dist/products/variants/fetch.js +1 -1
- package/dist/products/variants/store.js +1 -1
- package/dist/products/variants/update.js +1 -1
- package/dist/receipt-text.js +1 -1
- package/dist/receipts/destroy.js +1 -1
- package/dist/receipts/fetch.js +1 -1
- package/dist/receipts/printer.js +1 -1
- package/dist/receipts/store.js +1 -1
- package/dist/receipts/timestamp.js +1 -1
- package/dist/receipts/update.js +1 -1
- package/dist/refund-allocation.js +1 -1
- package/dist/register.js +1 -1
- package/dist/releases.js +1 -1
- package/dist/sales-tax.js +1 -1
- package/dist/shippings/couriers/destroy.js +1 -1
- package/dist/shippings/couriers/fetch.js +1 -1
- package/dist/shippings/couriers/store.js +1 -1
- package/dist/shippings/couriers/update.js +1 -1
- package/dist/shippings/delivery-routes/destroy.js +1 -1
- package/dist/shippings/delivery-routes/fetch.js +1 -1
- package/dist/shippings/delivery-routes/store.js +1 -1
- package/dist/shippings/delivery-routes/update.js +1 -1
- package/dist/shippings/delivery-routes/validate-write.js +1 -1
- package/dist/shippings/digital-deliveries/destroy.js +1 -1
- package/dist/shippings/digital-deliveries/fetch.js +1 -1
- package/dist/shippings/digital-deliveries/store.js +1 -1
- package/dist/shippings/digital-deliveries/update.js +1 -1
- package/dist/shippings/geocoding/index.js +1 -1
- package/dist/shippings/geocoding/nominatim.js +1 -1
- package/dist/shippings/license-keys/destroy.js +1 -1
- package/dist/shippings/license-keys/fetch.js +1 -1
- package/dist/shippings/license-keys/store.js +1 -1
- package/dist/shippings/license-keys/update.js +1 -1
- package/dist/shippings/license-keys/validate-write.js +1 -1
- package/dist/shippings/shipping-methods/destroy.js +1 -1
- package/dist/shippings/shipping-methods/fetch.js +1 -1
- package/dist/shippings/shipping-methods/store.js +1 -1
- package/dist/shippings/shipping-methods/update.js +1 -1
- package/dist/shippings/shipping-rates/destroy.js +1 -1
- package/dist/shippings/shipping-rates/fetch.js +1 -1
- package/dist/shippings/shipping-rates/store.js +1 -1
- package/dist/shippings/shipping-rates/update.js +1 -1
- package/dist/shippings/shipping-rates/validate-write.js +1 -1
- package/dist/shippings/shipping-zones/destroy.js +1 -1
- package/dist/shippings/shipping-zones/fetch.js +1 -1
- package/dist/shippings/shipping-zones/store.js +1 -1
- package/dist/shippings/shipping-zones/update.js +1 -1
- package/dist/shippings/tracking/geo.js +1 -1
- package/dist/shippings/tracking/ping.js +1 -1
- package/dist/shippings/tracking/stops.js +1 -1
- package/dist/shippings/write-data.js +1 -1
- package/dist/tax/destroy.js +1 -1
- package/dist/tax/fetch.js +1 -1
- package/dist/tax/store.js +1 -1
- package/dist/tax/update.js +1 -1
- package/dist/tax-input.js +1 -1
- package/dist/utils/inserted-id.js +1 -1
- package/dist/utils/inventory-adjustment.js +1 -1
- package/dist/utils/typed-stats.js +1 -1
- package/dist/waitlists/products/destroy.js +1 -1
- package/dist/waitlists/products/export.js +1 -1
- package/dist/waitlists/products/fetch.js +1 -1
- package/dist/waitlists/products/store.js +1 -1
- package/dist/waitlists/products/update.js +1 -1
- package/dist/waitlists/products/write-data.js +1 -1
- package/dist/waitlists/restaurant/destroy.js +1 -1
- package/dist/waitlists/restaurant/export.js +1 -1
- package/dist/waitlists/restaurant/fetch.js +1 -1
- package/dist/waitlists/restaurant/store.js +1 -1
- package/dist/waitlists/restaurant/update.js +1 -1
- package/dist/waitlists/restaurant/write-data.js +1 -1
- package/package.json +14 -14
package/dist/errors/fetch.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{db,sqlHelpers}from"@stacksjs/database/runtime";import{env}from"@stacksjs/env";import{formatDate}from"@stacksjs/orm";export async function fetchById(id){return await db.selectFrom("errors").where("id","=",id).selectAll().executeTakeFirst()}export async function fetchAll(){return await db.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}export async function fetchGrouped(){const errors=await db.selectFrom("errors").select(["id","type","message","resolution","created_at"]).orderBy("created_at","desc").execute()
|
|
1
|
+
import{db,sqlHelpers}from"@stacksjs/database/runtime";import{env}from"@stacksjs/env";import{formatDate}from"@stacksjs/orm";export async function fetchById(id){return await db.selectFrom("errors").where("id","=",id).selectAll().executeTakeFirst()}export async function fetchAll(){return await db.selectFrom("errors").selectAll().orderBy("created_at","desc").execute()}export async function fetchGrouped(){const errors=await db.selectFrom("errors").select(["id","type","message","resolution","created_at"]).orderBy("created_at","desc").execute();const groupMap=new Map;for(const error of errors){const key=`${error.type}:${error.message}`;if(!groupMap.has(key)){groupMap.set(key,{errors:[],firstSeen:new Date(error.created_at),lastSeen:new Date(error.created_at)})}const group=groupMap.get(key);group.errors.push(error);const errorDate=new Date(error.created_at);if(errorDate<group.firstSeen)group.firstSeen=errorDate;if(errorDate>group.lastSeen)group.lastSeen=errorDate}const stacks=await fetchStacks([...groupMap.values()].flatMap((group)=>group.errors[0]?[group.errors[0].id]:[]));const groupedErrors=[];for(const[_,group]of groupMap){const representative=group.errors[0];if(!representative)continue;const statusLabel=representative.resolution??"unresolved";groupedErrors.push({id:representative.id,type:representative.type,message:representative.message,stack:stacks.get(Number(representative.id))??null,status:statusLabel,count:group.errors.length,first_seen:group.firstSeen.toISOString(),last_seen:group.lastSeen.toISOString(),error_ids:group.errors.map((e)=>e.id)})}groupedErrors.sort((a,b)=>new Date(b.last_seen).getTime()-new Date(a.last_seen).getTime());return groupedErrors}function groupOrder(query){const direction=query.direction==="asc"?"ASC":"DESC";const by={last_seen:`created_at ${direction}`,count:`occurrences ${direction}`,type:`LOWER(type) ${direction}`,status:`CASE WHEN resolution = 'resolved' THEN 1 WHEN resolution = 'ignored' THEN 2 ELSE 0 END ${direction}`}[query.sort??"last_seen"];return`${by}, created_at DESC, id DESC`}export async function fetchGroupedPage(query){const helpers=sqlHelpers(env.DB_CONNECTION||"sqlite");const values=[];const bind=(value)=>{values.push(value);return helpers.param(values.length)};const rowFilters=[];if(query.search){const term=`%${query.search}%`;rowFilters.push(`(LOWER(type) LIKE LOWER(${bind(term)}) OR LOWER(message) LIKE LOWER(${bind(term)}))`)}if(query.type)rowFilters.push(`type = ${bind(query.type)}`);const groupFilters=["group_rank = 1"];if(query.status==="unresolved")groupFilters.push(`(resolution = ${bind("unresolved")} OR resolution IS NULL)`);else if(query.status!=="all")groupFilters.push(`resolution = ${bind(query.status)}`);const ranked=`(
|
|
2
2
|
SELECT id, type, message, resolution, created_at,
|
|
3
3
|
ROW_NUMBER() OVER (PARTITION BY type, message ORDER BY created_at DESC, id DESC) AS group_rank,
|
|
4
4
|
COUNT(id) OVER (PARTITION BY type, message) AS occurrences,
|
|
5
5
|
MIN(created_at) OVER (PARTITION BY type, message) AS first_seen
|
|
6
6
|
FROM errors
|
|
7
7
|
${rowFilters.length>0?`WHERE ${rowFilters.join(" AND ")}`:""}
|
|
8
|
-
) ranked
|
|
9
|
-
ORDER BY ${groupOrder(query)} LIMIT ${Math.trunc(query.perPage)} OFFSET ${Math.trunc((page-1)*query.perPage)}`,values).execute(),db.unsafe("SELECT DISTINCT type FROM errors ORDER BY type").execute()])
|
|
8
|
+
) ranked`;const where=`WHERE ${groupFilters.join(" AND ")}`;const[counted]=await db.unsafe(`SELECT COUNT(id) AS count FROM ${ranked} ${where}`,values).execute();const total=Number(counted?.count??0)||0;const page=Math.min(query.page,Math.max(1,Math.ceil(total/query.perPage)));const[rows,types]=await Promise.all([total===0?Promise.resolve([]):db.unsafe(`SELECT id, type, message, resolution, occurrences, first_seen, created_at AS last_seen FROM ${ranked} ${where}
|
|
9
|
+
ORDER BY ${groupOrder(query)} LIMIT ${Math.trunc(query.perPage)} OFFSET ${Math.trunc((page-1)*query.perPage)}`,values).execute(),db.unsafe("SELECT DISTINCT type FROM errors ORDER BY type").execute()]);const stacks=await fetchStacks(rows.map((row)=>Number(row.id)));return{groups:rows.map((row)=>({id:Number(row.id),type:row.type,message:row.message,stack:stacks.get(Number(row.id))??null,status:row.resolution??"unresolved",count:Number(row.occurrences)||0,first_seen:new Date(row.first_seen).toISOString(),last_seen:new Date(row.last_seen).toISOString()})),total,page,types:types.map((row)=>String(row.type))}}const STACK_BATCH=500;async function fetchStacks(ids){const stacks=new Map;for(let start=0;start<ids.length;start+=STACK_BATCH){const rows=await db.selectFrom("errors").select(["id","stack"]).where("id","in",ids.slice(start,start+STACK_BATCH)).execute();for(const row of rows)stacks.set(Number(row.id),row.stack??null)}return stacks}export async function fetchByGroup(type,message){return await db.selectFrom("errors").where("type","=",type).where("message","=",message).selectAll().orderBy("created_at","desc").execute()}async function countSince(since){const row=await db.selectFrom("errors").where("created_at",">=",formatDate(since)).select(db.fn.count("id").as("count")).executeTakeFirst();return Number(row?.count??0)}export async function fetchStats(){const now=new Date;const yesterday=new Date(now.getTime()-24*60*60*1000);const twoDaysAgo=new Date(now.getTime()-48*60*60*1000);const byResolution=await db.selectFrom("errors").select(["resolution",db.fn.count("id").as("count")]).groupBy("resolution").execute();let total=0;let resolved=0;let ignored=0;for(const row of byResolution){const count=Number(row.count);total+=count;if(row.resolution==="resolved")resolved+=count;else if(row.resolution==="ignored")ignored+=count}const last24h=await countSince(yesterday);const previous24h=await countSince(twoDaysAgo)-last24h;const trend=previous24h===0?last24h>0?100:0:Math.round((last24h-previous24h)/previous24h*100);return{total,unresolved:total-resolved-ignored,resolved,ignored,last_24h:last24h,trend}}export async function fetchTimeline(){const now=new Date;const firstHour=new Date(now.getTime()-23*60*60*1000);firstHour.setMinutes(0,0,0);const errors=await db.selectFrom("errors").select(["created_at"]).where("created_at",">=",formatDate(firstHour)).execute();const timeline=[];for(let i=23;i>=0;i--){const hourStart=new Date(now.getTime()-i*60*60*1000);hourStart.setMinutes(0,0,0);const hourEnd=new Date(hourStart.getTime()+60*60*1000);const count=errors.filter((e)=>{const date=new Date(e.created_at);return date>=hourStart&&date<hourEnd}).length;timeline.push({hour:hourStart.toISOString(),count})}return timeline}
|
package/dist/errors/update.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{db}from"@stacksjs/database/runtime";import{sql}from"@stacksjs/database/runtime";import{log}from"@stacksjs/logging";export async function update(id,data){try{await db.updateTable("errors").set({...data,updated_at:sql.raw("CURRENT_TIMESTAMP")}).where("id","=",id).execute();return
|
|
1
|
+
import{db}from"@stacksjs/database/runtime";import{sql}from"@stacksjs/database/runtime";import{log}from"@stacksjs/logging";export async function update(id,data){try{await db.updateTable("errors").set({...data,updated_at:sql.raw("CURRENT_TIMESTAMP")}).where("id","=",id).execute();return true}catch(error){log.error("[commerce/errors] update failed",{id,error});return false}}export async function bulkUpdateStatus(ids,status){try{await db.updateTable("errors").set({status,updated_at:sql.raw("CURRENT_TIMESTAMP")}).where("id","in",ids).execute();return true}catch(error){log.error("[commerce/errors] bulkUpdateStatus failed",{count:ids.length,status,error});return false}}export async function resolveGroup(type,message){try{await db.updateTable("errors").set({resolution:"resolved",updated_at:sql.raw("CURRENT_TIMESTAMP")}).where("type","=",type).where("message","=",message).execute();return true}catch(error){log.error("[commerce/errors] resolveGroup failed",{type,message,error});return false}}export async function ignoreGroup(type,message){try{await db.updateTable("errors").set({resolution:"ignored",updated_at:sql.raw("CURRENT_TIMESTAMP")}).where("type","=",type).where("message","=",message).execute();return true}catch(error){log.error("[commerce/errors] ignoreGroup failed",{type,message,error});return false}}export async function unresolveGroup(type,message){try{await db.updateTable("errors").set({resolution:"unresolved",updated_at:sql.raw("CURRENT_TIMESTAMP")}).where("type","=",type).where("message","=",message).execute();return true}catch(error){log.error("[commerce/errors] unresolveGroup failed",{type,message,error});return false}}
|
package/dist/fiskaly.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const FISKALY_SIGN_DE_URL="https://kassensichv-middleware.fiskaly.com/api/v2";export class FiskalyError extends Error{failure;status;code;constructor(message,failure,status,code=null){super(message);this.failure=failure;this.status=status;this.code=code;this.name="FiskalyError"}get outage(){return this.failure==="unreachable"||this.failure==="rate_limited"||this.failure==="failed"&&(this.status===0||this.status>=500)}}function failureFor(status){if(status===401||status===403)return"rejected";if(status===404)return"not_found";if(status===409)return"conflict";if(status===400||status===422)return"invalid";if(status===429)return"rate_limited";return"failed"}export function fiskalySignDe(options){const base=(options.baseUrl||FISKALY_SIGN_DE_URL).replace(/\/$/,"")
|
|
1
|
+
export const FISKALY_SIGN_DE_URL="https://kassensichv-middleware.fiskaly.com/api/v2";export class FiskalyError extends Error{failure;status;code;constructor(message,failure,status,code=null){super(message);this.failure=failure;this.status=status;this.code=code;this.name="FiskalyError"}get outage(){return this.failure==="unreachable"||this.failure==="rate_limited"||this.failure==="failed"&&(this.status===0||this.status>=500)}}function failureFor(status){if(status===401||status===403)return"rejected";if(status===404)return"not_found";if(status===409)return"conflict";if(status===400||status===422)return"invalid";if(status===429)return"rate_limited";return"failed"}export function fiskalySignDe(options){const base=(options.baseUrl||FISKALY_SIGN_DE_URL).replace(/\/$/,"");const doFetch=options.fetch??fetch;const timeoutMs=options.timeoutMs??15000;let token=null;async function send(method,path,body,bearer,timeout=timeoutMs){let res;try{res=await doFetch(`${base}${path}`,{method,headers:{Accept:"application/json",...body===undefined?{}:{"Content-Type":"application/json"},...bearer?{Authorization:`Bearer ${bearer}`}:{}},body:body===undefined?undefined:JSON.stringify(body),signal:AbortSignal.timeout(timeout)})}catch(error){throw new FiskalyError(`Could not reach fiskaly: ${error instanceof Error?error.message:String(error)}`,"unreachable",0)}const text=await res.text();let json=null;try{json=text?JSON.parse(text):null}catch{json=null}if(!res.ok){const message=typeof json?.message==="string"&&json.message?json.message:`fiskaly answered ${res.status}`;throw new FiskalyError(message,failureFor(res.status),res.status,typeof json?.code==="string"?json.code:null)}return{status:res.status,json}}function keep(json){const expiresIn=Number(json?.access_token_expires_in);const expiresAt=Number(json?.access_token_expires_at);token={accessToken:String(json?.access_token||""),refreshToken:typeof json?.refresh_token==="string"?json.refresh_token:null,expiresAt:Number.isFinite(expiresAt)&&expiresAt>0?expiresAt*1000:Date.now()+(Number.isFinite(expiresIn)&&expiresIn>0?expiresIn:300)*1000};if(!token.accessToken)throw new FiskalyError("fiskaly answered no access token","failed",200);return token}async function bearer(){if(token&&token.expiresAt-60000>Date.now())return token.accessToken;if(token?.refreshToken){try{return keep((await send("POST","/auth",{refresh_token:token.refreshToken},null)).json).accessToken}catch(error){if(!(error instanceof FiskalyError)||error.failure!=="rejected")throw error}}return keep((await send("POST","/auth",{api_key:options.apiKey,api_secret:options.apiSecret},null)).json).accessToken}async function call(method,path,body,timeout){try{return(await send(method,path,body,await bearer(),timeout)).json}catch(error){if(error instanceof FiskalyError&&error.status===401&&token){token=null;return(await send(method,path,body,await bearer(),timeout)).json}throw error}}const id=(value)=>encodeURIComponent(value);return{async authenticate(){token=null;const json=(await send("POST","/auth",{api_key:options.apiKey,api_secret:options.apiSecret},null)).json;keep(json);const claims=json?.access_token_claims??{};return{organizationId:typeof claims.organization_id==="string"?claims.organization_id:null,environment:typeof claims.env==="string"?claims.env:null}},createTss:(tssId,metadata)=>call("PUT",`/tss/${id(tssId)}`,metadata?{metadata}:{}),retrieveTss:(tssId)=>call("GET",`/tss/${id(tssId)}`),setTssState:(tssId,state)=>call("PATCH",`/tss/${id(tssId)}`,{state},state==="UNINITIALIZED"?Math.max(timeoutMs,60000):undefined),changeAdminPin:(tssId,adminPuk,newAdminPin)=>call("PATCH",`/tss/${id(tssId)}/admin`,{admin_puk:adminPuk,new_admin_pin:newAdminPin}),authenticateAdmin:(tssId,adminPin)=>call("POST",`/tss/${id(tssId)}/admin/auth`,{admin_pin:adminPin}),logoutAdmin:(tssId)=>call("POST",`/tss/${id(tssId)}/admin/logout`,{}),upsertClient:(tssId,clientId,serialNumber)=>call("PUT",`/tss/${id(tssId)}/client/${id(clientId)}`,{serial_number:serialNumber}),retrieveClient:(tssId,clientId)=>call("GET",`/tss/${id(tssId)}/client/${id(clientId)}`),startTransaction:(tssId,txId,clientId)=>call("PUT",`/tss/${id(tssId)}/tx/${id(txId)}?tx_revision=1`,{state:"ACTIVE",client_id:clientId}),finishTransaction:(tssId,txId,clientId,receipt,revision=2)=>call("PUT",`/tss/${id(tssId)}/tx/${id(txId)}?tx_revision=${revision}`,{state:"FINISHED",client_id:clientId,schema:{standard_v1:{receipt}}}),cancelTransaction:(tssId,txId,clientId,revision=2)=>call("PUT",`/tss/${id(tssId)}/tx/${id(txId)}?tx_revision=${revision}`,{state:"CANCELLED",client_id:clientId}),retrieveTransaction:(tssId,txId)=>call("GET",`/tss/${id(tssId)}/tx/${id(txId)}`)}}export async function provisionTss(api,input){let tss=null;let adminPuk=input.adminPuk??null;try{tss=await api.retrieveTss(input.tssId)}catch(error){if(!(error instanceof FiskalyError)||error.failure!=="not_found")throw error}if(!tss){tss=await api.createTss(input.tssId,input.metadata);if(tss.admin_puk)adminPuk=tss.admin_puk}if(tss.state==="DISABLED"||tss.state==="DEFECTIVE"||tss.state==="DELETED"||tss.state==="EVICTED")throw new FiskalyError(`The TSE is ${tss.state.toLowerCase()} and cannot sign`,"invalid",409,"E_TSS_STATE");if(tss.state==="CREATED"){tss=await api.setTssState(input.tssId,"UNINITIALIZED");if(!adminPuk)throw new FiskalyError("The admin PUK of this TSE was not kept, so its PIN cannot be set","invalid",409,"E_ADMIN_PUK_MISSING");await api.changeAdminPin(input.tssId,adminPuk,input.adminPin)}await api.authenticateAdmin(input.tssId,input.adminPin);try{if(tss.state==="UNINITIALIZED")tss=await api.setTssState(input.tssId,"INITIALIZED");const client=await api.upsertClient(input.tssId,input.clientId,input.clientSerialNumber);tss=await api.retrieveTss(input.tssId);return{tss,client,adminPuk}}finally{await api.logoutAdmin(input.tssId).catch(()=>{})}}export function newAdminPin(length=10){if(!Number.isSafeInteger(length)||length<6)throw new Error("An admin PIN needs at least 6 characters");let pin="";while(pin.length<length){const bytes=new Uint8Array(length);crypto.getRandomValues(bytes);for(const byte of bytes)if(byte<250&&pin.length<length)pin+=String(byte%10)}return pin}export function isClientSerialNumber(value){return/^(?!\s)[A-Za-z0-9 '()+,\-.:=?]{1,70}(?<!\s)$/.test(value)}
|
package/dist/gdpdu-dtd.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{db,matchedRows}from"@stacksjs/database/runtime";import{formatDate}from"@stacksjs/orm";import{fetchById}from"./fetch";import{mutationCount}from"../utils/mutation-count";export async function destroy(id){const result=await db.deleteFrom("gift_cards").where("id","=",id).executeTakeFirst();return mutationCount(result)>0}export async function bulkDestroy(ids){if(!ids.length)return 0
|
|
1
|
+
import{db,matchedRows}from"@stacksjs/database/runtime";import{formatDate}from"@stacksjs/orm";import{fetchById}from"./fetch";import{mutationCount}from"../utils/mutation-count";export async function destroy(id){const result=await db.deleteFrom("gift_cards").where("id","=",id).executeTakeFirst();return mutationCount(result)>0}export async function bulkDestroy(ids){if(!ids.length){return 0}const result=await db.deleteFrom("gift_cards").where("id","in",ids).executeTakeFirst();return mutationCount(result)}export async function destroyExpired(){const now=formatDate(new Date);const result=await db.deleteFrom("gift_cards").where("expiry_date","<",now).executeTakeFirst();return mutationCount(result)}export async function deactivate(id){const giftCard=await fetchById(id);if(!giftCard){throw new Error(`Gift card with ID ${id} not found`)}const matched=await matchedRows(db.updateTable("gift_cards").set({is_active:false,status:"DEACTIVATED",updated_at:formatDate(new Date)}).where("id","=",id));return matched.length>0}
|
package/dist/gift-cards/fetch.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{db,sql}from"@stacksjs/database/runtime";import{formatDate,toTimestamp}from"@stacksjs/orm";import{asModelRow,asModelRows}from"../utils/model-row";import{aggregateStats}from"../utils/typed-stats";export async function fetchAll(){const giftCards=await db.selectFrom("gift_cards").selectAll().execute();return asModelRows(giftCards)}export async function fetchById(id){const row=await db.selectFrom("gift_cards").where("id","=",id).selectAll().executeTakeFirst();return asModelRow(row
|
|
1
|
+
import{db,sql}from"@stacksjs/database/runtime";import{formatDate,toTimestamp}from"@stacksjs/orm";import{asModelRow,asModelRows}from"../utils/model-row";import{aggregateStats}from"../utils/typed-stats";export async function fetchAll(){const giftCards=await db.selectFrom("gift_cards").selectAll().execute();return asModelRows(giftCards)}export async function fetchById(id){const row=await db.selectFrom("gift_cards").where("id","=",id).selectAll().executeTakeFirst();return asModelRow(row,true)}export async function fetchByCode(code){const row=await db.selectFrom("gift_cards").where("code","=",code).selectAll().executeTakeFirst();return asModelRow(row,true)}export async function fetchActive(){const giftCards=await db.selectFrom("gift_cards").where("is_active","=",true).selectAll().execute();return asModelRows(giftCards)}export async function fetchStats(){const{count:totalCount}=await aggregateStats("gift_cards",{count:{kind:"count"}});const currentDate=toTimestamp(new Date);const activeGiftCards=await db.selectFrom("gift_cards").where("is_active","=",true).where("status","=","ACTIVE").whereRaw(sql`(expiry_date >= ${sql.literal(currentDate)} OR expiry_date IS NULL)`).select(db.fn.count("id").as("count")).executeTakeFirst();const giftCardsByStatus=await db.selectFrom("gift_cards").select(["status",db.fn.count("id").as("count")]).groupBy("status").execute();const{count:lowBalanceCount}=await aggregateStats("gift_cards",{count:{kind:"count"}},(qb)=>qb.whereRaw(sql`current_balance / initial_balance < 0.25`));const{count:mediumBalanceCount}=await aggregateStats("gift_cards",{count:{kind:"count"}},(qb)=>qb.whereRaw(sql`current_balance / initial_balance >= 0.25 AND current_balance / initial_balance <= 0.75`));const{count:highBalanceCount}=await aggregateStats("gift_cards",{count:{kind:"count"}},(qb)=>qb.whereRaw(sql`current_balance / initial_balance > 0.75`));const thirtyDaysFromNow=new Date;thirtyDaysFromNow.setDate(thirtyDaysFromNow.getDate()+30);const expiringGiftCards=await db.selectFrom("gift_cards").where("is_active","=",true).where("status","=","ACTIVE").where("expiry_date","<=",toTimestamp(thirtyDaysFromNow)).where("expiry_date",">=",currentDate).selectAll().limit(5).execute();const recentlyUsedGiftCards=await db.selectFrom("gift_cards").whereNotNull("last_used_date").selectAll().limit(5).execute();return{total:totalCount,active:Number(activeGiftCards?.count||0),by_status:giftCardsByStatus.map((item)=>({status:item.status,count:Number(item.count)})),by_balance:{low:lowBalanceCount,medium:mediumBalanceCount,high:highBalanceCount},expiring_soon:asModelRows(expiringGiftCards),recently_used:asModelRows(recentlyUsedGiftCards)}}export async function checkBalance(code){const giftCard=await fetchByCode(code);if(!giftCard){return{valid:false,message:"Gift card not found"}}if(!giftCard.isActive||giftCard.status!=="ACTIVE"){return{valid:false,balance:giftCard.currentBalance,currency:giftCard.currency,message:`Gift card is ${giftCard.status.toLowerCase()}`}}if(giftCard.expiryDate){const expiryDate=new Date(giftCard.expiryDate);const currentDate=new Date;if(expiryDate<currentDate){return{valid:false,balance:giftCard.currentBalance,currency:giftCard.currency,message:"Gift card has expired"}}}return{valid:true,balance:giftCard.currentBalance,currency:giftCard.currency}}export async function compareActiveGiftCards(_daysRange=30){const today=new Date;const currentPeriodStart=new Date(today);currentPeriodStart.setDate(today.getDate()-_daysRange);const previousPeriodEnd=new Date(currentPeriodStart);previousPeriodEnd.setDate(previousPeriodEnd.getDate()-1);const previousPeriodStart=new Date(previousPeriodEnd);previousPeriodStart.setDate(previousPeriodEnd.getDate()-_daysRange);const currentPeriodActive=await db.selectFrom("gift_cards").select(db.fn.count("id").as("count")).where("is_active","=",true).where("status","=","ACTIVE").whereRaw(sql`(expiry_date >= ${sql.literal(toTimestamp(today))} OR expiry_date IS NULL)`).where("created_at",">=",formatDate(currentPeriodStart)).where("created_at","<=",formatDate(today)).executeTakeFirst();const previousPeriodActive=await db.selectFrom("gift_cards").select(db.fn.count("id").as("count")).where("is_active","=",true).where("status","=","ACTIVE").whereRaw(sql`(expiry_date >= ${sql.literal(toTimestamp(previousPeriodStart))} OR expiry_date IS NULL)`).where("created_at",">=",formatDate(previousPeriodStart)).where("created_at","<=",formatDate(previousPeriodEnd)).executeTakeFirst();const currentCount=Number(currentPeriodActive?.count||0);const previousCount=Number(previousPeriodActive?.count||0);const difference=currentCount-previousCount;const percentageChange=previousCount!==0?difference/previousCount*100:currentCount>0?100:0;return{current_period:currentCount,previous_period:previousCount,difference,percentage_change:percentageChange,days_range:_daysRange}}export async function calculateGiftCardValues(_daysRange=30){const today=new Date;const currentPeriodStart=new Date(today);currentPeriodStart.setDate(today.getDate()-_daysRange);const previousPeriodEnd=new Date(currentPeriodStart);previousPeriodEnd.setDate(previousPeriodEnd.getDate()-1);const previousPeriodStart=new Date(previousPeriodEnd);previousPeriodStart.setDate(previousPeriodEnd.getDate()-_daysRange);const currentPeriodValues=await db.selectFrom("gift_cards").select([db.fn.sum("initial_balance").as("total_initial"),db.fn.sum("current_balance").as("total_balance"),db.fn.count("id").as("card_count")]).where("is_active","=",true).where("status","=","ACTIVE").whereRaw(sql`(expiry_date >= ${sql.literal(toTimestamp(today))} OR expiry_date IS NULL)`).where("created_at",">=",formatDate(currentPeriodStart)).where("created_at","<=",formatDate(today)).executeTakeFirst();const previousPeriodValues=await db.selectFrom("gift_cards").select([db.fn.sum("initial_balance").as("total_initial"),db.fn.sum("current_balance").as("total_balance"),db.fn.count("id").as("card_count")]).where("is_active","=",true).where("status","=","ACTIVE").whereRaw(sql`(expiry_date >= ${sql.literal(toTimestamp(previousPeriodStart))} OR expiry_date IS NULL)`).where("created_at",">=",formatDate(previousPeriodStart)).where("created_at","<=",formatDate(previousPeriodEnd)).executeTakeFirst();const currentInitialValue=Number(currentPeriodValues?.total_initial||0);const currentBalance=Number(currentPeriodValues?.total_balance||0);const currentCardCount=Number(currentPeriodValues?.card_count||0);const previousInitialValue=Number(previousPeriodValues?.total_initial||0);const previousBalance=Number(previousPeriodValues?.total_balance||0);const previousCardCount=Number(previousPeriodValues?.card_count||0);const currentUtilizationRate=currentInitialValue>0?(currentInitialValue-currentBalance)/currentInitialValue*100:0;const previousUtilizationRate=previousInitialValue>0?(previousInitialValue-previousBalance)/previousInitialValue*100:0;const currentAverageInitial=currentCardCount>0?currentInitialValue/currentCardCount:0;const currentAverageBalance=currentCardCount>0?currentBalance/currentCardCount:0;const initialValueDifference=currentInitialValue-previousInitialValue;const balanceDifference=currentBalance-previousBalance;const cardCountDifference=currentCardCount-previousCardCount;const initialValuePercentageChange=previousInitialValue!==0?initialValueDifference/previousInitialValue*100:currentInitialValue>0?100:0;const balancePercentageChange=previousBalance!==0?balanceDifference/previousBalance*100:currentBalance>0?100:0;const cardCountPercentageChange=previousCardCount!==0?cardCountDifference/previousCardCount*100:currentCardCount>0?100:0;return{current_period:{total_initial_value:currentInitialValue,total_remaining_balance:currentBalance,utilization_rate:currentUtilizationRate,card_count:currentCardCount,average_initial_value:currentAverageInitial,average_remaining_balance:currentAverageBalance},previous_period:{total_initial_value:previousInitialValue,total_remaining_balance:previousBalance,utilization_rate:previousUtilizationRate,card_count:previousCardCount},comparison:{initial_value:{difference:initialValueDifference,percentage:Math.abs(initialValuePercentageChange),is_increase:initialValueDifference>=0},balance:{difference:balanceDifference,percentage:Math.abs(balancePercentageChange),is_increase:balanceDifference>=0},card_count:{difference:cardCountDifference,percentage:Math.abs(cardCountPercentageChange),is_increase:cardCountDifference>=0}},days_range:_daysRange}}export async function fetchTotalValue(){const{total_value}=await aggregateStats("gift_cards",{total_value:{kind:"sum",column:"initial_balance"}});return{total_value}}export async function fetchTotalCurrentBalance(){const{total_balance}=await aggregateStats("gift_cards",{total_balance:{kind:"sum",column:"current_balance"}});return{total_balance}}
|
package/dist/gift-cards/store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{randomUUIDv7}from"bun";import{db,sqlDateTimeInput}from"@stacksjs/database/runtime";import{asModelRow}from"../utils/model-row";import{HttpError}from"@stacksjs/error-handling";import{isUniqueViolation}from"@stacksjs/orm";import{insertedId}from"../utils/inserted-id";export function giftCardDates(data){const dates={};for(const column of["expiry_date","last_used_date"])if(Object.prototype.hasOwnProperty.call(data,column))dates[column]=sqlDateTimeInput(data[column])
|
|
1
|
+
import{randomUUIDv7}from"bun";import{db,sqlDateTimeInput}from"@stacksjs/database/runtime";import{asModelRow}from"../utils/model-row";import{HttpError}from"@stacksjs/error-handling";import{isUniqueViolation}from"@stacksjs/orm";import{insertedId}from"../utils/inserted-id";export function giftCardDates(data){const dates={};for(const column of["expiry_date","last_used_date"]){if(Object.prototype.hasOwnProperty.call(data,column))dates[column]=sqlDateTimeInput(data[column])}return dates}export async function store(data){const d=data;const giftCardData={...data,...giftCardDates(d),current_balance:d.current_balance??d.initial_balance,status:data.status||"ACTIVE",is_active:d.is_active??true,uuid:randomUUIDv7()};try{const createdGiftCard=await db.insertInto("gift_cards").values(giftCardData).executeTakeFirst();const id=insertedId(createdGiftCard);if(id!==undefined){const giftCard=await db.selectFrom("gift_cards").where("id","=",id).selectAll().executeTakeFirst();return asModelRow(giftCard)}const giftCard=await db.selectFrom("gift_cards").where("uuid","=",giftCardData.uuid).selectAll().executeTakeFirst();return asModelRow(giftCard,true)}catch(error){if(error instanceof HttpError)throw error;if(isUniqueViolation(error))throw new HttpError(409,"A gift card with this code already exists");if(error instanceof Error)throw new Error(`Failed to create gift card: ${error.message}`);throw error}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{db,mutationCount,parseSqlDateTime,sqlHelpers}from"@stacksjs/database/runtime";import{env}from"@stacksjs/env";import{HttpError}from"@stacksjs/error-handling";import{formatDate,isUniqueViolation}from"@stacksjs/orm";import{fetchById}from"./fetch";import{giftCardDates}from"./store";export async function update(id,data){
|
|
1
|
+
import{db,mutationCount,parseSqlDateTime,sqlHelpers}from"@stacksjs/database/runtime";import{env}from"@stacksjs/env";import{HttpError}from"@stacksjs/error-handling";import{formatDate,isUniqueViolation}from"@stacksjs/orm";import{fetchById}from"./fetch";import{giftCardDates}from"./store";export async function update(id,data){const existingGiftCard=await fetchById(id);if(!existingGiftCard)return;try{await db.updateTable("gift_cards").set({...data,...giftCardDates(data),updated_at:formatDate(new Date)}).where("id","=",id).execute();return await fetchById(id)}catch(error){if(error instanceof HttpError)throw error;if(isUniqueViolation(error))throw new HttpError(409,"A gift card with this code already exists");if(error instanceof Error)throw new Error(`Failed to update gift card: ${error.message}`);throw error}}export async function updateBalance(id,amount){if(!Number.isFinite(amount))throw new Error(`Gift card balance adjustment must be a finite number, got ${amount}`);const dialect=sqlHelpers(env.DB_CONNECTION||"sqlite");const p=dialect.param;const now=formatDate(new Date);const isRedemption=amount<0;const isReload=amount>0;const statusPredicate=isReload?`(status = 'ACTIVE' OR (status = 'USED' AND is_reloadable = ${dialect.boolTrue}))`:`status = 'ACTIVE'`;const values=[];const bind=(value)=>{values.push(value);return p(values.length)};const statement=await db.unsafe(`UPDATE gift_cards
|
|
2
2
|
SET status = CASE WHEN current_balance + ${bind(amount)} = 0 THEN 'USED' WHEN 1 = 0 THEN status ELSE 'ACTIVE' END,
|
|
3
3
|
current_balance = current_balance + ${bind(amount)},
|
|
4
4
|
${isRedemption?`last_used_date = ${bind(now)},
|
|
@@ -7,4 +7,4 @@ import{db,mutationCount,parseSqlDateTime,sqlHelpers}from"@stacksjs/database/runt
|
|
|
7
7
|
AND is_active = ${dialect.boolTrue}
|
|
8
8
|
AND ${statusPredicate}
|
|
9
9
|
AND (expiry_date IS NULL OR expiry_date >= ${bind(now)})
|
|
10
|
-
AND current_balance + ${bind(amount)} >= 0`,values);if(mutationCount(statement)>0)return await fetchById(id)
|
|
10
|
+
AND current_balance + ${bind(amount)} >= 0`,values);if(mutationCount(statement)>0){return await fetchById(id)}const existing=await fetchById(id);if(!existing)throw new Error(`Gift card with ID ${id} not found`);const row=existing;if(!row.is_active&&!row.isActive)throw new Error(`Gift card is not active`);if(existing.status==="USED"&&isReload&&!(row.is_reloadable??row.isReloadable))throw new Error(`Gift card is not reloadable`);if(existing.status!=="ACTIVE")throw new Error(`Gift card is not active`);const expiry=parseSqlDateTime(row.expiry_date??row.expiryDate);const checkedAt=parseSqlDateTime(now);if(expiry&&checkedAt&&expiry.getTime()<checkedAt.getTime())throw new Error(`Gift card has expired`);if(amount===0&&Number(row.current_balance??row.currentBalance)>=0)return existing;throw new Error(`Insufficient gift card balance`)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decimalToMinor,numberToMinor,PriceFormatError}from"./money";import{cleanName,optionalString}from"./text";const EMAIL=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;export function normalizeEmail(input){if(typeof input!=="string")return null;const email=input.trim().toLowerCase();return EMAIL.test(email)?email:null}export function isoTimestamp(input){if(typeof input!=="string"||input.trim()==="")return null;const at=new Date(input.trim());return Number.isNaN(at.getTime())?null:at.toISOString()}export function gmtTimestamp(input){if(typeof input!=="string"||input.trim()==="")return null;const raw=input.trim();return isoTimestamp(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(raw)?raw:`${raw}Z`)}export function personName(...parts){const name=parts.map((part)=>cleanName(part)).filter(Boolean).join(" ");return name===""?null:name}export function phoneOf(...candidates){for(const candidate of candidates){const phone=optionalString(typeof candidate==="number"?String(candidate):candidate);if(phone)return phone.slice(0,50)}return null}export function addressLine(...parts){const line=parts.map((part)=>cleanName(part)).filter(Boolean).join(", ");return line===""?null:line}export function signedMinor(value,exponent){if(value===null||value===
|
|
1
|
+
import{decimalToMinor,numberToMinor,PriceFormatError}from"./money";import{cleanName,optionalString}from"./text";const EMAIL=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;export function normalizeEmail(input){if(typeof input!=="string")return null;const email=input.trim().toLowerCase();return EMAIL.test(email)?email:null}export function isoTimestamp(input){if(typeof input!=="string"||input.trim()==="")return null;const at=new Date(input.trim());return Number.isNaN(at.getTime())?null:at.toISOString()}export function gmtTimestamp(input){if(typeof input!=="string"||input.trim()==="")return null;const raw=input.trim();return isoTimestamp(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(raw)?raw:`${raw}Z`)}export function personName(...parts){const name=parts.map((part)=>cleanName(part)).filter(Boolean).join(" ");return name===""?null:name}export function phoneOf(...candidates){for(const candidate of candidates){const phone=optionalString(typeof candidate==="number"?String(candidate):candidate);if(phone)return phone.slice(0,50)}return null}export function addressLine(...parts){const line=parts.map((part)=>cleanName(part)).filter(Boolean).join(", ");return line===""?null:line}export function signedMinor(value,exponent){if(value===null||value===undefined||value==="")return null;if(typeof value==="number"){if(!Number.isFinite(value))throw new PriceFormatError(value,"expected a finite number");const magnitude=numberToMinor(Math.abs(value),exponent);return value<0?-magnitude:magnitude}if(typeof value!=="string")throw new PriceFormatError(value,"expected a decimal amount");const raw=value.trim();const negative=raw.startsWith("-");const magnitude=decimalToMinor(negative||raw.startsWith("+")?raw.slice(1):raw,exponent);if(magnitude===null)return null;return negative?-magnitude:magnitude}export function amountOrZero(value,exponent,label,externalId,warnings,fallback=0){let minor;try{minor=signedMinor(value,exponent)}catch(error){if(!(error instanceof PriceFormatError))throw error;warnings.push({externalId,message:`${label}: ${error.message}; recorded as ${fallback}`});return fallback}if(minor===null)return fallback;if(minor<0){warnings.push({externalId,message:`${label} is negative (${String(value)}); recorded as ${fallback}`});return fallback}return minor}export function unitFromTotal(totalMinor,quantity){if(quantity<=1)return totalMinor;return Math.floor((2*totalMinor+quantity)/(2*quantity))}export function quantityOf(value){const quantity=typeof value==="string"?Number(value):value;return typeof quantity==="number"&&Number.isInteger(quantity)&&quantity>0?quantity:null}export function currencyCode(value){const code=typeof value==="string"?value.trim().toUpperCase():"";return/^[A-Z]{3}$/.test(code)?code:null}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{db,sqlHelpers}from"@stacksjs/database/runtime";import{env}from"@stacksjs/env";import{formatDate}from"@stacksjs/orm";import{DEFAULT_CUSTOMER_AVATAR}from"../customers/store";import{normalizeStoreUrl,storeHost}from"./http";import{catalogUuid}from"./identity";import{formatMinor}from"./money";const NAME_MAX=255;export function customerUuid(source,host,externalId,email){return catalogUuid(source,host,"customer",externalId??`email:${email}`)}export function promotedCustomerUuid(source,host,existingUuid,externalId,email){if(!externalId)return null;if(existingUuid!==null&&existingUuid!==customerUuid(source,host,null,email))return null;return customerUuid(source,host,externalId,email)}function stamp(iso){return iso?formatDate(new Date(iso)):null}export function customerRow(customer,uuid,now,mode){const row={name:customer.name.slice(0,NAME_MAX),updated_at:now};if(mode==="create"){row.uuid=uuid;row.email=customer.email;row.phone=customer.phone;row.total_spent=customer.totalSpentMinor??0;row.last_order=stamp(customer.lastOrderAt);row.status=customer.active===!1?"Inactive":"Active";row.avatar=customer.avatarUrl??DEFAULT_CUSTOMER_AVATAR;row.created_at=stamp(customer.createdAt)??now;return row}if(customer.phone!==null)row.phone=customer.phone;if(customer.totalSpentMinor!==null)row.total_spent=customer.totalSpentMinor;if(customer.lastOrderAt!==null)row.last_order=stamp(customer.lastOrderAt);if(customer.active!==null)row.status=customer.active?"Active":"Inactive";return row}export function lineLabel(line){return line.sku?`${line.name} (SKU ${line.sku})`:line.name}export function orderRow(order,host,customerId,now){const row={uuid:catalogUuid(order.source,host,"order",order.externalId),status:order.status,total_amount:order.totalMinor,currency:order.currency,tax_amount:order.taxMinor,discount_amount:order.discountMinor,delivery_fee:order.shippingMinor,tip_amount:order.tipMinor,order_type:order.shippingAddress?"DELIVERY":"TAKEOUT",delivery_address:order.shippingAddress,special_instructions:order.note,created_at:stamp(order.placedAt)??now,updated_at:now};if(customerId!==null)row.customer_id=customerId;return row}class CustomerIndex{byUuid=new Map;byEmail=new Map;uuidById=new Map;async load(repository,keys){const uuids=[...new Set(keys.map((key)=>key.uuid).filter((uuid)=>uuid!==null&&!this.byUuid.has(uuid)))],emails=[...new Set(keys.map((key)=>key.email).filter((email)=>email!==null&&!this.byEmail.has(email)))];if(uuids.length===0&&emails.length===0)return;for(const row of await repository.findCustomers({uuids,emails}))this.remember(row.id,row.uuid,row.email)}remember(id,uuid,email){if(uuid){const previous=this.uuidById.get(id);if(previous&&previous!==uuid)this.byUuid.delete(previous);this.byUuid.set(uuid,id);this.uuidById.set(id,uuid)}if(email)this.byEmail.set(email.trim().toLowerCase(),id)}find(uuid,email){const byUuid=uuid?this.byUuid.get(uuid):void 0;if(byUuid!==void 0)return{id:byUuid,matchedBy:"uuid"};const byEmail=email?this.byEmail.get(email):void 0;return byEmail!==void 0?{id:byEmail,matchedBy:"email"}:null}uuidOf(id){return this.uuidById.get(id)??null}emailTakenByOther(email,id){const holder=this.byEmail.get(email);return holder!==void 0&&holder!==id}}function base(options){const storeUrl=normalizeStoreUrl(options.storeUrl);return{storeUrl,host:storeHost(storeUrl),clock:options.now??(()=>new Date),fetchOptions:{credentials:options.credentials,limit:options.limit,fetch:options.fetch,currency:options.currency,adminUrl:options.adminUrl,sleep:options.sleep}}}export async function importCustomers(options){const{storeUrl,host,clock,fetchOptions}=base(options),{adapter,repository}=options,index=new CustomerIndex,seenEmails=new Set,result={source:adapter.name,storeUrl,dryRun:options.dryRun===!0,pages:[],customers:[],counts:{customers:{created:0,updated:0},merged:0},warnings:[]};async function write(customer,repo){const now=formatDate(clock()),uuid=customerUuid(customer.source,host,customer.externalId,customer.email),found=index.find(uuid,customer.email);if(!found){const id=await repo.createCustomer(customerRow(customer,uuid,now,"create"));index.remember(id,uuid,customer.email);return{action:"create",externalId:customer.externalId,email:customer.email,name:customer.name,matchedBy:null}}const row=customerRow(customer,uuid,now,"update");if(found.matchedBy==="uuid")if(index.emailTakenByOther(customer.email,found.id))result.warnings.push({externalId:customer.externalId??void 0,message:`email changed to ${customer.email}, which another customer already has; kept the old address`});else row.email=customer.email;const promoted=found.matchedBy==="email"?promotedCustomerUuid(customer.source,host,index.uuidOf(found.id),customer.externalId,customer.email):null;if(promoted)row.uuid=promoted;await repo.updateCustomer(found.id,row);index.remember(found.id,promoted,customer.email);return{action:"update",externalId:customer.externalId,email:customer.email,name:customer.name,matchedBy:found.matchedBy}}for await(const page of adapter.customers(storeUrl,fetchOptions)){result.pages.push(page.url);result.warnings.push(...page.warnings);const fresh=[];for(const customer of page.items){if(seenEmails.has(customer.email)){result.counts.merged++;continue}seenEmails.add(customer.email);fresh.push(customer)}await index.load(repository,fresh.map((customer)=>({uuid:customerUuid(customer.source,host,customer.externalId,customer.email),email:customer.email})));for(const customer of fresh){const imported=await write(customer,repository);result.counts.customers[imported.action==="create"?"created":"updated"]++;result.customers.push(imported);options.onCustomer?.(imported)}}if(result.counts.merged>0)result.warnings.push({message:`${result.counts.merged} source customer${result.counts.merged===1?"":"s"} shared an email with another and ${result.counts.merged===1?"was":"were"} merged into one Stacks customer`});return result}export async function importOrders(options){const{storeUrl,host,clock,fetchOptions}=base(options),{adapter,repository}=options,index=new CustomerIndex,seenOrders=new Set,currencies=new Set,unlinkedExamples=new Set,refundExamples=[],result={source:adapter.name,storeUrl,dryRun:options.dryRun===!0,pages:[],orders:[],counts:{orders:{created:0,updated:0},customers:{created:0,updated:0},lines:{linked:0,unlinked:0,productless:0},duplicates:0,partlyRefunded:0},currencies:[],warnings:[]},productUuid=(order,id)=>catalogUuid(order.source,host,"product",id),variantUuid=(order,id)=>catalogUuid(order.source,host,"variant",id);function orderCustomerUuid(order){const customer=order.customer;if(customer?.externalId)return customerUuid(order.source,host,customer.externalId,customer.email??"");return customer?.email?customerUuid(order.source,host,null,customer.email):null}async function customerFor(order,repo,now){const customer=order.customer;if(!customer)return null;const uuid=orderCustomerUuid(order),found=index.find(uuid,customer.email);if(found){const promoted=found.matchedBy==="email"&&customer.email?promotedCustomerUuid(order.source,host,index.uuidOf(found.id),customer.externalId,customer.email):null;if(promoted){await repo.updateCustomer(found.id,{uuid:promoted,updated_at:now});index.remember(found.id,promoted,customer.email)}return found.id}if(!customer.email){result.warnings.push({externalId:order.externalId,message:`order ${order.number??order.externalId} has no customer email; imported without a customer`});return null}const id=await repo.createCustomer(customerRow({source:order.source,externalId:customer.externalId,email:customer.email,name:customer.name??customer.email,phone:customer.phone,active:null,totalSpentMinor:null,currency:null,lastOrderAt:order.placedAt,avatarUrl:null,createdAt:order.placedAt},uuid,now,"create"));index.remember(id,uuid,customer.email);result.counts.customers.created++;return id}async function write(order,repo,known){const now=formatDate(clock()),customerId=await customerFor(order,repo,now),row=orderRow(order,host,customerId,now),existing=known.orders.get(row.uuid);let orderId;if(existing===void 0)orderId=await repo.createOrder(row);else{orderId=existing;const changes={...row};delete changes.uuid;await repo.updateOrder(orderId,changes)}let unlinked=0,productless=0;const items=order.lines.map((line)=>{const productId=(line.productExternalId?known.products.get(productUuid(order,line.productExternalId)):void 0)??(line.variantExternalId?known.variants.get(variantUuid(order,line.variantExternalId)):void 0)??null;if(productId===null)if(!line.productExternalId&&!line.variantExternalId)productless++;else{unlinked++;if(unlinkedExamples.size<5)unlinkedExamples.add(lineLabel(line))}return{order_id:orderId,product_id:productId,quantity:line.quantity,price:line.unitPriceMinor,special_instructions:lineLabel(line),created_at:now,updated_at:now}});await repo.replaceOrderItems(orderId,items);return{action:existing===void 0?"create":"update",externalId:order.externalId,number:order.number,status:order.status,sourceStatus:order.sourceStatus,totalMinor:order.totalMinor,currency:order.currency,lines:items.length,unlinkedLines:unlinked,productlessLines:productless,refundedMinor:order.refundedMinor??0,customerEmail:order.customer?.email??null,customerId}}for await(const page of adapter.orders(storeUrl,fetchOptions)){result.pages.push(page.url);result.warnings.push(...page.warnings);const fresh=page.items.filter((order)=>{if(!seenOrders.has(order.externalId)){seenOrders.add(order.externalId);return!0}result.counts.duplicates++;return!1}),orderUuids=fresh.map((order)=>catalogUuid(order.source,host,"order",order.externalId)),productUuids=[...new Set(fresh.flatMap((order)=>order.lines.flatMap((line)=>line.productExternalId?[productUuid(order,line.productExternalId)]:[])))],variantUuids=[...new Set(fresh.flatMap((order)=>order.lines.flatMap((line)=>line.variantExternalId?[variantUuid(order,line.variantExternalId)]:[])))],known={orders:orderUuids.length>0?await repository.findOrders(orderUuids):new Map,products:productUuids.length>0?await repository.findProducts(productUuids):new Map,variants:variantUuids.length>0?await repository.findVariantProducts(variantUuids):new Map};await index.load(repository,fresh.map((order)=>({uuid:orderCustomerUuid(order),email:order.customer?.email??null})));const latest=new Map;for(const order of fresh){currencies.add(order.currency);const{customerId,...imported}=repository.transaction?await repository.transaction((repo)=>write(order,repo,known)):await write(order,repository,known);result.counts.orders[imported.action==="create"?"created":"updated"]++;result.counts.lines.linked+=imported.lines-imported.unlinkedLines-imported.productlessLines;result.counts.lines.unlinked+=imported.unlinkedLines;result.counts.lines.productless+=imported.productlessLines;if(imported.refundedMinor>0&&imported.status!=="REFUNDED"){result.counts.partlyRefunded++;if(refundExamples.length<3)refundExamples.push(`${imported.number??imported.externalId}: ${formatMinor(imported.refundedMinor,imported.currency)} of ${formatMinor(imported.totalMinor,imported.currency)}`)}const placed=stamp(order.placedAt);if(customerId!==null&&placed&&placed>(latest.get(customerId)??""))latest.set(customerId,placed);result.orders.push(imported);options.onOrder?.(imported)}if(repository.advanceLastOrder)for(const[customerId,at]of latest)await repository.advanceLastOrder(customerId,at)}result.currencies=[...currencies].sort();if(result.counts.lines.unlinked>0){const examples=[...unlinkedExamples].map((label)=>`"${label}"`).join(", "),one=result.counts.lines.unlinked===1;result.warnings.push({message:`${result.counts.lines.unlinked} order line${one?" references a product":"s reference products"} not in Stacks (e.g. ${examples}); kept with ${one?"its":"their"} label and price but no product link. Import the catalog (buddy commerce:import <url> --from ${adapter.name}), then re-run the order import to link ${one?"it":"them"}.`})}if(result.counts.partlyRefunded>0){const one=result.counts.partlyRefunded===1;result.warnings.push({message:`${result.counts.partlyRefunded} order${one?" was":"s were"} partly refunded at the source (${refundExamples.join("; ")}${one?"":", ..."}). Stacks orders have no refund column, so total_amount is what was charged.`})}return result}export function createDatabaseAccountRepository(connection=db){async function idByUuid(table,uuid){const row=await connection.selectFrom(table).where("uuid","=",uuid).select("id").executeTakeFirst();if(!row)throw Error(`Inserted a row into ${table} but could not read it back (uuid ${uuid})`);return Number(row.id)}async function chunked(values,read){const rows=[];for(let start=0;start<values.length;start+=500)rows.push(...await read(values.slice(start,start+500)));return rows}const repository={async findCustomers({uuids,emails}){const byUuid=await chunked(uuids,(chunk)=>connection.selectFrom("customers").where("uuid","in",chunk).select(["id","uuid","email"]).execute()),param=sqlHelpers(env.DB_CONNECTION||"sqlite").param,byEmail=await chunked(emails.map((email)=>email.trim().toLowerCase()),async(chunk)=>{const placeholders=chunk.map((_,index)=>param(index+1)).join(", "),rows=await connection.unsafe(`SELECT id, uuid, email FROM customers WHERE LOWER(email) IN (${placeholders})`,chunk);return Array.isArray(rows)?rows:[]});return[...byUuid,...byEmail].map((row)=>({id:Number(row.id),uuid:row.uuid??null,email:String(row.email)}))},async createCustomer(row){await connection.insertInto("customers").values(row).execute();return idByUuid("customers",row.uuid)},async updateCustomer(id,row){await connection.updateTable("customers").set(row).where("id","=",id).execute()},async advanceLastOrder(id,at){const param=sqlHelpers(env.DB_CONNECTION||"sqlite").param;await connection.unsafe(`UPDATE customers SET last_order = ${param(1)} WHERE id = ${param(2)} AND (last_order IS NULL OR last_order < ${param(3)})`,[at,id,at])},async findOrders(uuids){const rows=await chunked(uuids,(chunk)=>connection.selectFrom("orders").where("uuid","in",chunk).select(["id","uuid"]).execute());return new Map(rows.map((row)=>[String(row.uuid),Number(row.id)]))},async createOrder(row){await connection.insertInto("orders").values(row).execute();return idByUuid("orders",row.uuid)},async updateOrder(id,row){await connection.updateTable("orders").set(row).where("id","=",id).execute()},async replaceOrderItems(orderId,rows){await connection.deleteFrom("order_items").where("order_id","=",orderId).execute();if(rows.length>0)await connection.insertInto("order_items").values(rows).execute()},async findProducts(uuids){const rows=await chunked(uuids,(chunk)=>connection.selectFrom("products").where("uuid","in",chunk).select(["id","uuid"]).execute());return new Map(rows.map((row)=>[String(row.uuid),Number(row.id)]))},async findVariantProducts(uuids){const rows=await chunked(uuids,(chunk)=>connection.selectFrom("product_variants").where("uuid","in",chunk).select(["uuid","product_id"]).execute());return new Map(rows.filter((row)=>row.product_id!==null&&row.product_id!==void 0).map((row)=>[String(row.uuid),Number(row.product_id)]))}};if(connection===db)repository.transaction=(work)=>db.transaction((trx)=>work(createDatabaseAccountRepository(trx)));return repository}export function createMemoryAccountRepository(shared={tables:{}}){const tables=shared.tables;for(const table of["customers","orders","order_items","products","product_variants"])tables[table]??=[];function insert(table,row){const rows=tables[table],id=rows.reduce((max,entry)=>Math.max(max,Number(entry.id)),0)+1;rows.push({id,...row});return id}function update(table,id,row){const target=tables[table].find((entry)=>entry.id===id);if(target)Object.assign(target,row)}const byUuid=(table,uuids)=>new Map(tables[table].filter((row)=>uuids.includes(row.uuid)).map((row)=>[row.uuid,row.id]));return{tables,findCustomers:async({uuids,emails})=>tables.customers.filter((row)=>uuids.includes(row.uuid)||emails.includes(String(row.email).trim().toLowerCase())).map((row)=>({id:row.id,uuid:row.uuid??null,email:row.email})),createCustomer:async(row)=>{if(tables.customers.some((existing)=>existing.email===row.email))throw Error(`UNIQUE constraint failed: customers.email (${row.email})`);return insert("customers",row)},updateCustomer:async(id,row)=>update("customers",id,row),advanceLastOrder:async(id,at)=>{const row=tables.customers.find((entry)=>entry.id===id);if(row&&(row.last_order===null||row.last_order===void 0||String(row.last_order)<at))row.last_order=at},findOrders:async(uuids)=>byUuid("orders",uuids),createOrder:async(row)=>insert("orders",row),updateOrder:async(id,row)=>update("orders",id,row),replaceOrderItems:async(orderId,rows)=>{tables.order_items=tables.order_items.filter((row)=>row.order_id!==orderId);for(const row of rows)insert("order_items",row)},findProducts:async(uuids)=>byUuid("products",uuids),findVariantProducts:async(uuids)=>new Map(tables.product_variants.filter((row)=>uuids.includes(row.uuid)).map((row)=>[row.uuid,row.product_id]))}}export function createReadOnlyAccountRepository(inner){let nextId=-1;const fake=async()=>nextId--,pretend=[];return{async findCustomers(query){const found=await inner.findCustomers(query),extra=pretend.filter((row)=>row.uuid!==null&&query.uuids.includes(row.uuid)||query.emails.includes(row.email));return[...found,...extra]},findOrders:inner.findOrders,findProducts:inner.findProducts,findVariantProducts:inner.findVariantProducts,async createCustomer(row){const id=nextId--;pretend.push({id,uuid:row.uuid??null,email:String(row.email??"").toLowerCase()});return id},createOrder:fake,updateCustomer:async()=>{},advanceLastOrder:async()=>{},updateOrder:async()=>{},replaceOrderItems:async()=>{}}}
|
|
1
|
+
import{db,sqlHelpers}from"@stacksjs/database/runtime";import{env}from"@stacksjs/env";import{formatDate}from"@stacksjs/orm";import{DEFAULT_CUSTOMER_AVATAR}from"../customers/store";import{normalizeStoreUrl,storeHost}from"./http";import{catalogUuid}from"./identity";import{formatMinor}from"./money";const NAME_MAX=255;export function customerUuid(source,host,externalId,email){return catalogUuid(source,host,"customer",externalId??`email:${email}`)}export function promotedCustomerUuid(source,host,existingUuid,externalId,email){if(!externalId)return null;if(existingUuid!==null&&existingUuid!==customerUuid(source,host,null,email))return null;return customerUuid(source,host,externalId,email)}function stamp(iso){return iso?formatDate(new Date(iso)):null}export function customerRow(customer,uuid,now,mode){const row={name:customer.name.slice(0,NAME_MAX),updated_at:now};if(mode==="create"){row.uuid=uuid;row.email=customer.email;row.phone=customer.phone;row.total_spent=customer.totalSpentMinor??0;row.last_order=stamp(customer.lastOrderAt);row.status=customer.active===false?"Inactive":"Active";row.avatar=customer.avatarUrl??DEFAULT_CUSTOMER_AVATAR;row.created_at=stamp(customer.createdAt)??now;return row}if(customer.phone!==null)row.phone=customer.phone;if(customer.totalSpentMinor!==null)row.total_spent=customer.totalSpentMinor;if(customer.lastOrderAt!==null)row.last_order=stamp(customer.lastOrderAt);if(customer.active!==null)row.status=customer.active?"Active":"Inactive";return row}export function lineLabel(line){return line.sku?`${line.name} (SKU ${line.sku})`:line.name}export function orderRow(order,host,customerId,now){const row={uuid:catalogUuid(order.source,host,"order",order.externalId),status:order.status,total_amount:order.totalMinor,currency:order.currency,tax_amount:order.taxMinor,discount_amount:order.discountMinor,delivery_fee:order.shippingMinor,tip_amount:order.tipMinor,order_type:order.shippingAddress?"DELIVERY":"TAKEOUT",delivery_address:order.shippingAddress,special_instructions:order.note,created_at:stamp(order.placedAt)??now,updated_at:now};if(customerId!==null)row.customer_id=customerId;return row}class CustomerIndex{byUuid=new Map;byEmail=new Map;uuidById=new Map;async load(repository,keys){const uuids=[...new Set(keys.map((key)=>key.uuid).filter((uuid)=>uuid!==null&&!this.byUuid.has(uuid)))];const emails=[...new Set(keys.map((key)=>key.email).filter((email)=>email!==null&&!this.byEmail.has(email)))];if(uuids.length===0&&emails.length===0)return;for(const row of await repository.findCustomers({uuids,emails}))this.remember(row.id,row.uuid,row.email)}remember(id,uuid,email){if(uuid){const previous=this.uuidById.get(id);if(previous&&previous!==uuid)this.byUuid.delete(previous);this.byUuid.set(uuid,id);this.uuidById.set(id,uuid)}if(email)this.byEmail.set(email.trim().toLowerCase(),id)}find(uuid,email){const byUuid=uuid?this.byUuid.get(uuid):undefined;if(byUuid!==undefined)return{id:byUuid,matchedBy:"uuid"};const byEmail=email?this.byEmail.get(email):undefined;return byEmail!==undefined?{id:byEmail,matchedBy:"email"}:null}uuidOf(id){return this.uuidById.get(id)??null}emailTakenByOther(email,id){const holder=this.byEmail.get(email);return holder!==undefined&&holder!==id}}function base(options){const storeUrl=normalizeStoreUrl(options.storeUrl);return{storeUrl,host:storeHost(storeUrl),clock:options.now??(()=>new Date),fetchOptions:{credentials:options.credentials,limit:options.limit,fetch:options.fetch,currency:options.currency,adminUrl:options.adminUrl,sleep:options.sleep}}}export async function importCustomers(options){const{storeUrl,host,clock,fetchOptions}=base(options);const{adapter,repository}=options;const index=new CustomerIndex;const seenEmails=new Set;const result={source:adapter.name,storeUrl,dryRun:options.dryRun===true,pages:[],customers:[],counts:{customers:{created:0,updated:0},merged:0},warnings:[]};async function write(customer,repo){const now=formatDate(clock());const uuid=customerUuid(customer.source,host,customer.externalId,customer.email);const found=index.find(uuid,customer.email);if(!found){const id=await repo.createCustomer(customerRow(customer,uuid,now,"create"));index.remember(id,uuid,customer.email);return{action:"create",externalId:customer.externalId,email:customer.email,name:customer.name,matchedBy:null}}const row=customerRow(customer,uuid,now,"update");if(found.matchedBy==="uuid"){if(index.emailTakenByOther(customer.email,found.id))result.warnings.push({externalId:customer.externalId??undefined,message:`email changed to ${customer.email}, which another customer already has; kept the old address`});else row.email=customer.email}const promoted=found.matchedBy==="email"?promotedCustomerUuid(customer.source,host,index.uuidOf(found.id),customer.externalId,customer.email):null;if(promoted)row.uuid=promoted;await repo.updateCustomer(found.id,row);index.remember(found.id,promoted,customer.email);return{action:"update",externalId:customer.externalId,email:customer.email,name:customer.name,matchedBy:found.matchedBy}}for await(const page of adapter.customers(storeUrl,fetchOptions)){result.pages.push(page.url);result.warnings.push(...page.warnings);const fresh=[];for(const customer of page.items){if(seenEmails.has(customer.email)){result.counts.merged++;continue}seenEmails.add(customer.email);fresh.push(customer)}await index.load(repository,fresh.map((customer)=>({uuid:customerUuid(customer.source,host,customer.externalId,customer.email),email:customer.email})));for(const customer of fresh){const imported=await write(customer,repository);result.counts.customers[imported.action==="create"?"created":"updated"]++;result.customers.push(imported);options.onCustomer?.(imported)}}if(result.counts.merged>0)result.warnings.push({message:`${result.counts.merged} source customer${result.counts.merged===1?"":"s"} shared an email with another and ${result.counts.merged===1?"was":"were"} merged into one Stacks customer`});return result}export async function importOrders(options){const{storeUrl,host,clock,fetchOptions}=base(options);const{adapter,repository}=options;const index=new CustomerIndex;const seenOrders=new Set;const currencies=new Set;const unlinkedExamples=new Set;const refundExamples=[];const result={source:adapter.name,storeUrl,dryRun:options.dryRun===true,pages:[],orders:[],counts:{orders:{created:0,updated:0},customers:{created:0,updated:0},lines:{linked:0,unlinked:0,productless:0},duplicates:0,partlyRefunded:0},currencies:[],warnings:[]};const productUuid=(order,id)=>catalogUuid(order.source,host,"product",id);const variantUuid=(order,id)=>catalogUuid(order.source,host,"variant",id);function orderCustomerUuid(order){const customer=order.customer;if(customer?.externalId)return customerUuid(order.source,host,customer.externalId,customer.email??"");return customer?.email?customerUuid(order.source,host,null,customer.email):null}async function customerFor(order,repo,now){const customer=order.customer;if(!customer)return null;const uuid=orderCustomerUuid(order);const found=index.find(uuid,customer.email);if(found){const promoted=found.matchedBy==="email"&&customer.email?promotedCustomerUuid(order.source,host,index.uuidOf(found.id),customer.externalId,customer.email):null;if(promoted){await repo.updateCustomer(found.id,{uuid:promoted,updated_at:now});index.remember(found.id,promoted,customer.email)}return found.id}if(!customer.email){result.warnings.push({externalId:order.externalId,message:`order ${order.number??order.externalId} has no customer email; imported without a customer`});return null}const id=await repo.createCustomer(customerRow({source:order.source,externalId:customer.externalId,email:customer.email,name:customer.name??customer.email,phone:customer.phone,active:null,totalSpentMinor:null,currency:null,lastOrderAt:order.placedAt,avatarUrl:null,createdAt:order.placedAt},uuid,now,"create"));index.remember(id,uuid,customer.email);result.counts.customers.created++;return id}async function write(order,repo,known){const now=formatDate(clock());const customerId=await customerFor(order,repo,now);const row=orderRow(order,host,customerId,now);const existing=known.orders.get(row.uuid);let orderId;if(existing===undefined){orderId=await repo.createOrder(row)}else{orderId=existing;const changes={...row};delete changes.uuid;await repo.updateOrder(orderId,changes)}let unlinked=0;let productless=0;const items=order.lines.map((line)=>{const productId=(line.productExternalId?known.products.get(productUuid(order,line.productExternalId)):undefined)??(line.variantExternalId?known.variants.get(variantUuid(order,line.variantExternalId)):undefined)??null;if(productId===null){if(!line.productExternalId&&!line.variantExternalId){productless++}else{unlinked++;if(unlinkedExamples.size<5)unlinkedExamples.add(lineLabel(line))}}return{order_id:orderId,product_id:productId,quantity:line.quantity,price:line.unitPriceMinor,special_instructions:lineLabel(line),created_at:now,updated_at:now}});await repo.replaceOrderItems(orderId,items);return{action:existing===undefined?"create":"update",externalId:order.externalId,number:order.number,status:order.status,sourceStatus:order.sourceStatus,totalMinor:order.totalMinor,currency:order.currency,lines:items.length,unlinkedLines:unlinked,productlessLines:productless,refundedMinor:order.refundedMinor??0,customerEmail:order.customer?.email??null,customerId}}for await(const page of adapter.orders(storeUrl,fetchOptions)){result.pages.push(page.url);result.warnings.push(...page.warnings);const fresh=page.items.filter((order)=>{if(!seenOrders.has(order.externalId)){seenOrders.add(order.externalId);return true}result.counts.duplicates++;return false});const orderUuids=fresh.map((order)=>catalogUuid(order.source,host,"order",order.externalId));const productUuids=[...new Set(fresh.flatMap((order)=>order.lines.flatMap((line)=>line.productExternalId?[productUuid(order,line.productExternalId)]:[])))];const variantUuids=[...new Set(fresh.flatMap((order)=>order.lines.flatMap((line)=>line.variantExternalId?[variantUuid(order,line.variantExternalId)]:[])))];const known={orders:orderUuids.length>0?await repository.findOrders(orderUuids):new Map,products:productUuids.length>0?await repository.findProducts(productUuids):new Map,variants:variantUuids.length>0?await repository.findVariantProducts(variantUuids):new Map};await index.load(repository,fresh.map((order)=>({uuid:orderCustomerUuid(order),email:order.customer?.email??null})));const latest=new Map;for(const order of fresh){currencies.add(order.currency);const{customerId,...imported}=repository.transaction?await repository.transaction((repo)=>write(order,repo,known)):await write(order,repository,known);result.counts.orders[imported.action==="create"?"created":"updated"]++;result.counts.lines.linked+=imported.lines-imported.unlinkedLines-imported.productlessLines;result.counts.lines.unlinked+=imported.unlinkedLines;result.counts.lines.productless+=imported.productlessLines;if(imported.refundedMinor>0&&imported.status!=="REFUNDED"){result.counts.partlyRefunded++;if(refundExamples.length<3)refundExamples.push(`${imported.number??imported.externalId}: ${formatMinor(imported.refundedMinor,imported.currency)} of ${formatMinor(imported.totalMinor,imported.currency)}`)}const placed=stamp(order.placedAt);if(customerId!==null&&placed&&placed>(latest.get(customerId)??""))latest.set(customerId,placed);result.orders.push(imported);options.onOrder?.(imported)}if(repository.advanceLastOrder){for(const[customerId,at]of latest)await repository.advanceLastOrder(customerId,at)}}result.currencies=[...currencies].sort();if(result.counts.lines.unlinked>0){const examples=[...unlinkedExamples].map((label)=>`"${label}"`).join(", ");const one=result.counts.lines.unlinked===1;result.warnings.push({message:`${result.counts.lines.unlinked} order line${one?" references a product":"s reference products"} not in Stacks (e.g. ${examples}); kept with ${one?"its":"their"} label and price but no product link. Import the catalog (buddy commerce:import <url> --from ${adapter.name}), then re-run the order import to link ${one?"it":"them"}.`})}if(result.counts.partlyRefunded>0){const one=result.counts.partlyRefunded===1;result.warnings.push({message:`${result.counts.partlyRefunded} order${one?" was":"s were"} partly refunded at the source (${refundExamples.join("; ")}${one?"":", ..."}). Stacks orders have no refund column, so total_amount is what was charged.`})}return result}export function createDatabaseAccountRepository(connection=db){async function idByUuid(table,uuid){const row=await connection.selectFrom(table).where("uuid","=",uuid).select("id").executeTakeFirst();if(!row)throw new Error(`Inserted a row into ${table} but could not read it back (uuid ${uuid})`);return Number(row.id)}async function chunked(values,read){const rows=[];for(let start=0;start<values.length;start+=500)rows.push(...await read(values.slice(start,start+500)));return rows}const repository={async findCustomers({uuids,emails}){const byUuid=await chunked(uuids,(chunk)=>connection.selectFrom("customers").where("uuid","in",chunk).select(["id","uuid","email"]).execute());const param=sqlHelpers(env.DB_CONNECTION||"sqlite").param;const byEmail=await chunked(emails.map((email)=>email.trim().toLowerCase()),async(chunk)=>{const placeholders=chunk.map((_,index)=>param(index+1)).join(", ");const rows=await connection.unsafe(`SELECT id, uuid, email FROM customers WHERE LOWER(email) IN (${placeholders})`,chunk);return Array.isArray(rows)?rows:[]});return[...byUuid,...byEmail].map((row)=>({id:Number(row.id),uuid:row.uuid??null,email:String(row.email)}))},async createCustomer(row){await connection.insertInto("customers").values(row).execute();return idByUuid("customers",row.uuid)},async updateCustomer(id,row){await connection.updateTable("customers").set(row).where("id","=",id).execute()},async advanceLastOrder(id,at){const param=sqlHelpers(env.DB_CONNECTION||"sqlite").param;await connection.unsafe(`UPDATE customers SET last_order = ${param(1)} WHERE id = ${param(2)} AND (last_order IS NULL OR last_order < ${param(3)})`,[at,id,at])},async findOrders(uuids){const rows=await chunked(uuids,(chunk)=>connection.selectFrom("orders").where("uuid","in",chunk).select(["id","uuid"]).execute());return new Map(rows.map((row)=>[String(row.uuid),Number(row.id)]))},async createOrder(row){await connection.insertInto("orders").values(row).execute();return idByUuid("orders",row.uuid)},async updateOrder(id,row){await connection.updateTable("orders").set(row).where("id","=",id).execute()},async replaceOrderItems(orderId,rows){await connection.deleteFrom("order_items").where("order_id","=",orderId).execute();if(rows.length>0)await connection.insertInto("order_items").values(rows).execute()},async findProducts(uuids){const rows=await chunked(uuids,(chunk)=>connection.selectFrom("products").where("uuid","in",chunk).select(["id","uuid"]).execute());return new Map(rows.map((row)=>[String(row.uuid),Number(row.id)]))},async findVariantProducts(uuids){const rows=await chunked(uuids,(chunk)=>connection.selectFrom("product_variants").where("uuid","in",chunk).select(["uuid","product_id"]).execute());return new Map(rows.filter((row)=>row.product_id!==null&&row.product_id!==undefined).map((row)=>[String(row.uuid),Number(row.product_id)]))}};if(connection===db)repository.transaction=(work)=>db.transaction((trx)=>work(createDatabaseAccountRepository(trx)));return repository}export function createMemoryAccountRepository(shared={tables:{}}){const tables=shared.tables;for(const table of["customers","orders","order_items","products","product_variants"])tables[table]??=[];function insert(table,row){const rows=tables[table];const id=rows.reduce((max,entry)=>Math.max(max,Number(entry.id)),0)+1;rows.push({id,...row});return id}function update(table,id,row){const target=tables[table].find((entry)=>entry.id===id);if(target)Object.assign(target,row)}const byUuid=(table,uuids)=>new Map(tables[table].filter((row)=>uuids.includes(row.uuid)).map((row)=>[row.uuid,row.id]));return{tables,findCustomers:async({uuids,emails})=>tables.customers.filter((row)=>uuids.includes(row.uuid)||emails.includes(String(row.email).trim().toLowerCase())).map((row)=>({id:row.id,uuid:row.uuid??null,email:row.email})),createCustomer:async(row)=>{if(tables.customers.some((existing)=>existing.email===row.email))throw new Error(`UNIQUE constraint failed: customers.email (${row.email})`);return insert("customers",row)},updateCustomer:async(id,row)=>update("customers",id,row),advanceLastOrder:async(id,at)=>{const row=tables.customers.find((entry)=>entry.id===id);if(row&&(row.last_order===null||row.last_order===undefined||String(row.last_order)<at))row.last_order=at},findOrders:async(uuids)=>byUuid("orders",uuids),createOrder:async(row)=>insert("orders",row),updateOrder:async(id,row)=>update("orders",id,row),replaceOrderItems:async(orderId,rows)=>{tables.order_items=tables.order_items.filter((row)=>row.order_id!==orderId);for(const row of rows)insert("order_items",row)},findProducts:async(uuids)=>byUuid("products",uuids),findVariantProducts:async(uuids)=>new Map(tables.product_variants.filter((row)=>uuids.includes(row.uuid)).map((row)=>[row.uuid,row.product_id]))}}export function createReadOnlyAccountRepository(inner){let nextId=-1;const fake=async()=>nextId--;const pretend=[];return{async findCustomers(query){const found=await inner.findCustomers(query);const extra=pretend.filter((row)=>row.uuid!==null&&query.uuids.includes(row.uuid)||query.emails.includes(row.email));return[...found,...extra]},findOrders:inner.findOrders,findProducts:inner.findProducts,findVariantProducts:inner.findVariantProducts,async createCustomer(row){const id=nextId--;pretend.push({id,uuid:row.uuid??null,email:String(row.email??"").toLowerCase()});return id},createOrder:fake,updateCustomer:async()=>{},advanceLastOrder:async()=>{},updateOrder:async()=>{},replaceOrderItems:async()=>{}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CatalogFetchError,fetchJson}from"./http";import{redactSecrets}from"./credentials";export const MAX_RETRIES=5;const DEFAULT_RETRY_SECONDS=2
|
|
1
|
+
import{CatalogFetchError,fetchJson}from"./http";import{redactSecrets}from"./credentials";export const MAX_RETRIES=5;const DEFAULT_RETRY_SECONDS=2;const MAX_RETRY_SECONDS=60;export const defaultSleep=(ms)=>new Promise((resolve)=>setTimeout(resolve,ms));export class AdminCredentialError extends CatalogFetchError{constructor(url,message,status){super(url,message,status);this.name="AdminCredentialError"}}function scrub(error,secrets,suffix=""){const message=redactSecrets(`${error.message}${suffix}`,secrets);const body=error.body===undefined?undefined:redactSecrets(error.body,secrets);return new CatalogFetchError(redactSecrets(error.url,secrets),message,error.status,body,error.retryAfter)}export async function adminRequest(url,options){const{fetch:fetcher,secrets,credentialHelp,hint="",sleep,...request}=options;const wait=sleep??defaultSleep;for(let attempt=0;;attempt++){try{return await fetchJson(url,fetcher,"",request)}catch(error){if(!(error instanceof CatalogFetchError))throw error;if(error.status===429&&attempt<MAX_RETRIES){const seconds=error.retryAfter!==undefined&&error.retryAfter>=0?error.retryAfter:DEFAULT_RETRY_SECONDS;await wait(Math.min(seconds,MAX_RETRY_SECONDS)*1000);continue}if(error.status===401||error.status===403){const reason=error.status===401?"The credentials were rejected.":"The credentials were accepted but lack permission to read this.";throw new AdminCredentialError(redactSecrets(url,secrets),redactSecrets(`${url} responded ${error.status}. ${reason} ${credentialHelp}`,secrets),error.status)}if(error.status===429)throw scrub(error,secrets,` Still rate limited after ${MAX_RETRIES} retries; re-run later, the import resumes safely.`);throw scrub(error,secrets,hint?` ${hint}`:"")}}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const ACCOUNT_CREDENTIAL_ENV={shopify:["SHOPIFY_ADMIN_TOKEN"],woocommerce:["WOOCOMMERCE_CONSUMER_KEY","WOOCOMMERCE_CONSUMER_SECRET"],shopware:["SHOPWARE_CLIENT_ID","SHOPWARE_CLIENT_SECRET"]}
|
|
1
|
+
export const ACCOUNT_CREDENTIAL_ENV={shopify:["SHOPIFY_ADMIN_TOKEN"],woocommerce:["WOOCOMMERCE_CONSUMER_KEY","WOOCOMMERCE_CONSUMER_SECRET"],shopware:["SHOPWARE_CLIENT_ID","SHOPWARE_CLIENT_SECRET"]};export const ACCOUNT_CREDENTIAL_HELP={shopify:"Create a custom app for the store (Shopify admin > Settings > Apps > Develop apps, or the Shopify Dev Dashboard), give it the Admin API scopes read_customers and read_orders (plus read_all_orders for orders older than 60 days), install it, and copy its Admin API access token (shpat_...).",woocommerce:"Create a key in WordPress admin > WooCommerce > Settings > Advanced > REST API > Add key, with Read permission, for a user who can manage WooCommerce. The key starts with ck_ and the secret with cs_.",shopware:"Create an integration in the Shopware Administration > Settings > System > Integrations, with a role that can read customers and orders. Its access key id (SWIA...) is the client id and its secret access key is the client secret."};export class MissingCredentialsError extends Error{constructor(message){super(message);this.name="MissingCredentialsError"}}function read(env,name){const value=env[name]?.trim();return value?value:undefined}export function readAccountCredentials(source,env){const key=source.trim().toLowerCase();const names=ACCOUNT_CREDENTIAL_ENV[key];if(!names)throw new MissingCredentialsError(`Customers and orders can be imported from ${Object.keys(ACCOUNT_CREDENTIAL_ENV).join(", ")}; got "${source}".`);const missing=names.filter((name)=>!read(env,name));if(missing.length>0){const what=missing.length===1?`${missing[0]} is not set`:`${missing.join(" and ")} are not set`;throw new MissingCredentialsError(`Importing customers or orders from ${key} needs Admin API credentials in the environment: ${what}. They are read from env (or .env) only, never from a flag, so they stay out of shell history. ${ACCOUNT_CREDENTIAL_HELP[key]}`)}const values=names.map((name)=>read(env,name));for(const[index,value]of values.entries()){if(/\s/.test(value))throw new MissingCredentialsError(`${names[index]} contains whitespace; paste the credential exactly as issued. ${ACCOUNT_CREDENTIAL_HELP[key]}`)}if(key==="shopify")return{source:"shopify",accessToken:values[0]};if(key==="woocommerce")return{source:"woocommerce",consumerKey:values[0],consumerSecret:values[1]};if(/^SWSC/i.test(values[0]))throw new MissingCredentialsError(`SHOPWARE_CLIENT_ID looks like a sales channel access key (SWSC...), which only reads the public catalog. ${ACCOUNT_CREDENTIAL_HELP.shopware}`);return{source:"shopware",clientId:values[0],clientSecret:values[1]}}export function credentialSecrets(credentials){switch(credentials.source){case"shopify":return[credentials.accessToken];case"woocommerce":return[credentials.consumerKey,credentials.consumerSecret];case"shopware":return[credentials.clientId,credentials.clientSecret]}}export function redactSecrets(text,secrets){let result=text;for(const secret of secrets){if(secret.length>=4)result=result.split(secret).join("[redacted]")}return result}
|
package/dist/imports/http.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export class CatalogFetchError extends Error{url;status;body;retryAfter;constructor(url,message,status,body,retryAfter){super(message);this.url=url;this.status=status;this.body=body;this.retryAfter=retryAfter;this.name="CatalogFetchError"}}const ERROR_BODY_MAX=2000
|
|
1
|
+
export class CatalogFetchError extends Error{url;status;body;retryAfter;constructor(url,message,status,body,retryAfter){super(message);this.url=url;this.status=status;this.body=body;this.retryAfter=retryAfter;this.name="CatalogFetchError"}}const ERROR_BODY_MAX=2000;const DEFAULT_TIMEOUT_MS=30000;export function normalizeStoreUrl(input){const raw=input.trim();if(!raw)throw new TypeError("A store URL is required, e.g. https://shop.example.com");const withScheme=/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)?raw:`https://${raw}`;let url;try{url=new URL(withScheme)}catch{throw new TypeError(`"${input}" is not a valid store URL`)}if(url.protocol!=="https:"&&url.protocol!=="http:")throw new TypeError(`"${input}" must be an http(s) URL`);const path=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host.toLowerCase()}${path}`}export function storeHost(storeUrl){return new URL(storeUrl).host.toLowerCase()}export function retryAfterSeconds(header,now=Date.now){const raw=header?.trim();if(!raw)return;if(/^\d+(?:\.\d+)?$/.test(raw))return Number(raw);const at=Date.parse(raw);return Number.isNaN(at)?undefined:Math.max(0,(at-now())/1000)}export async function fetchJson(url,fetcher=fetch,hint="",request={}){const suffix=hint?` ${hint}`:"";const headers={accept:"application/json",...request.headers};if(request.json!==undefined)headers["content-type"]="application/json";let response;try{response=await fetcher(url,{method:request.method??(request.json!==undefined?"POST":"GET"),headers,...request.json!==undefined?{body:JSON.stringify(request.json)}:{},signal:AbortSignal.timeout(DEFAULT_TIMEOUT_MS)})}catch(error){const reason=error instanceof Error?error.message:String(error);throw new CatalogFetchError(url,`Could not reach ${url}: ${reason}.${suffix}`)}if(!response.ok){const status=`${response.status}${response.statusText?` ${response.statusText}`:""}`;const body=await response.text().catch(()=>"");throw new CatalogFetchError(url,`${url} responded ${status}.${suffix}`,response.status,body?body.slice(0,ERROR_BODY_MAX):undefined,retryAfterSeconds(response.headers.get("retry-after")))}const body=await response.text();try{return{data:JSON.parse(body),headers:response.headers}}catch{const type=response.headers.get("content-type")||"no content-type";throw new CatalogFetchError(url,`${url} did not return JSON (${type}).${suffix}`,response.status)}}
|
package/dist/imports/identity.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";export const CATALOG_IMPORT_NAMESPACE="5d0c8a3e-6f1b-4c2a-9e47-b18f3d2a6c90";export function uuidV5(name,namespace=CATALOG_IMPORT_NAMESPACE){const namespaceHex=namespace.replace(/-/g,"");if(!/^[0-9a-f]{32}$/i.test(namespaceHex))throw TypeError(`Invalid namespace UUID "${namespace}"`);const bytes=createHash("sha1").update(Buffer.from(namespaceHex,"hex")).update(name,"utf8").digest().subarray(0,16);bytes[6]=bytes[6]&15|80;bytes[8]=bytes[8]&63|128;const hex=bytes.toString("hex");return`${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`}export function catalogUuid(source,host,kind,externalId){return uuidV5(`${source}:${host.toLowerCase()}:${kind}:${externalId}`)}
|
|
1
|
+
import{createHash}from"node:crypto";export const CATALOG_IMPORT_NAMESPACE="5d0c8a3e-6f1b-4c2a-9e47-b18f3d2a6c90";export function uuidV5(name,namespace=CATALOG_IMPORT_NAMESPACE){const namespaceHex=namespace.replace(/-/g,"");if(!/^[0-9a-f]{32}$/i.test(namespaceHex))throw new TypeError(`Invalid namespace UUID "${namespace}"`);const bytes=createHash("sha1").update(Buffer.from(namespaceHex,"hex")).update(name,"utf8").digest().subarray(0,16);bytes[6]=bytes[6]&15|80;bytes[8]=bytes[8]&63|128;const hex=bytes.toString("hex");return`${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`}export function catalogUuid(source,host,kind,externalId){return uuidV5(`${source}:${host.toLowerCase()}:${kind}:${externalId}`)}
|
package/dist/imports/money.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decimalToMinor,PriceFormatError}from"../money";export{currencyExponent,decimalToMinor,formatMinor,minorToDecimal,PriceFormatError,rescaleMinor}from"../money";export function numberToDecimalString(value){if(typeof value!=="number"||!Number.isFinite(value))throw new PriceFormatError(value,"expected a finite number");if(value<0)throw new PriceFormatError(value,"expected an amount of zero or more");const text=String(value)
|
|
1
|
+
import{decimalToMinor,PriceFormatError}from"../money";export{currencyExponent,decimalToMinor,formatMinor,minorToDecimal,PriceFormatError,rescaleMinor}from"../money";export function numberToDecimalString(value){if(typeof value!=="number"||!Number.isFinite(value))throw new PriceFormatError(value,"expected a finite number");if(value<0)throw new PriceFormatError(value,"expected an amount of zero or more");const text=String(value);const match=/^(\d+)(?:\.(\d+))?e([+-]\d+)$/.exec(text);if(!match)return text;const[,whole,fraction="",exponent]=match;const digits=`${whole}${fraction}`;const point=whole.length+Number(exponent);if(point<=0)return`0.${"0".repeat(-point)}${digits}`;if(point>=digits.length)return`${digits}${"0".repeat(point-digits.length)}`;return`${digits.slice(0,point)}.${digits.slice(point)}`}export function numberToMinor(value,exponent=2){if(value===null||value===undefined)return null;if(typeof value==="string")return decimalToMinor(value,exponent);return decimalToMinor(numberToDecimalString(value),exponent)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{addressLine,amountOrZero,currencyCode,isoTimestamp,normalizeEmail,personName,phoneOf,quantityOf,signedMinor}from"./account-mapping";import{adminRequest}from"./admin-http";import{ACCOUNT_CREDENTIAL_HELP,credentialSecrets}from"./credentials";import{CatalogFetchError,normalizeStoreUrl}from"./http";import{currencyExponent,PriceFormatError}from"./money";import{cleanName,optionalString}from"./text";export const SHOPIFY_ADMIN_API_VERSION="2026-10";const PAGE_SIZE=250
|
|
1
|
+
import{addressLine,amountOrZero,currencyCode,isoTimestamp,normalizeEmail,personName,phoneOf,quantityOf,signedMinor}from"./account-mapping";import{adminRequest}from"./admin-http";import{ACCOUNT_CREDENTIAL_HELP,credentialSecrets}from"./credentials";import{CatalogFetchError,normalizeStoreUrl}from"./http";import{currencyExponent,PriceFormatError}from"./money";import{cleanName,optionalString}from"./text";export const SHOPIFY_ADMIN_API_VERSION="2026-10";const PAGE_SIZE=250;const MAX_PAGES=4000;const CUSTOMER_FIELDS=["id","email","first_name","last_name","phone","state","total_spent","currency","created_at","default_address"];const ORDER_FIELDS=["id","name","order_number","email","contact_email","created_at","processed_at","cancelled_at","currency","total_price","total_tax","total_discounts","total_shipping_price_set","shipping_lines","total_tip_received","financial_status","fulfillment_status","customer","billing_address","shipping_address","line_items","note"];const CREDENTIAL_HELP=`Check SHOPIFY_ADMIN_TOKEN, and that the app is installed on this store with the read_customers and read_orders scopes. ${ACCOUNT_CREDENTIAL_HELP.shopify}`;export function mapShopifyCustomer(raw){const externalId=raw?.id===undefined||raw.id===null?"":String(raw.id);const warnings=[];const email=normalizeEmail(raw?.email);if(!externalId||!email){warnings.push({externalId:externalId||undefined,message:"skipped: the customer has no valid email address, which Stacks customers are keyed by"});return{record:null,warnings}}const currency=currencyCode(raw.currency);let totalSpentMinor=null;try{totalSpentMinor=signedMinor(raw.total_spent,currencyExponent(currency))}catch(error){if(!(error instanceof PriceFormatError))throw error;warnings.push({externalId,message:`total_spent: ${error.message}; not imported`})}return{record:{source:"shopify",externalId,email,name:personName(raw.first_name,raw.last_name)??personName(raw.default_address?.first_name,raw.default_address?.last_name)??email,phone:phoneOf(raw.phone,raw.default_address?.phone),active:null,totalSpentMinor:totalSpentMinor!==null&&totalSpentMinor>=0?totalSpentMinor:null,currency,lastOrderAt:null,avatarUrl:null,createdAt:isoTimestamp(raw.created_at)},warnings}}export function shopifyOrderStatus(raw){const financial=(raw.financial_status??"").toLowerCase();const fulfillment=(raw.fulfillment_status??"").toLowerCase();if(financial==="refunded")return{status:"REFUNDED",mapped:true};if(raw.cancelled_at||financial==="voided"||fulfillment==="restocked")return{status:"CANCELLED",mapped:true};if(fulfillment==="fulfilled")return{status:"SHIPPED",mapped:true};if(fulfillment==="partial")return{status:"PROCESSING",mapped:true};if(["paid","partially_paid","partially_refunded","authorized"].includes(financial))return{status:"PROCESSING",mapped:true};if(financial==="pending"||financial==="expired"||financial==="")return{status:"PENDING",mapped:true};return{status:"PENDING",mapped:false}}function shippingAddressOf(address){if(!address)return null;return addressLine(personName(address.first_name,address.last_name)??address.name,address.address1,address.address2,address.city,[address.province_code??address.province,address.zip].map((part)=>cleanName(part)).filter(Boolean).join(" "),address.country_code??address.country)}export function mapShopifyOrder(raw,context={}){const externalId=raw?.id===undefined||raw.id===null?"":String(raw.id);const warnings=[];if(!externalId){warnings.push({message:"skipped: a Shopify order has no id"});return{record:null,warnings}}const currency=currencyCode(raw.currency)??currencyCode(context.currency);if(!currency){warnings.push({externalId,message:"skipped: the order names no currency; pass --currency"});return{record:null,warnings}}const exponent=currencyExponent(currency);const amount=(value,label)=>amountOrZero(value,exponent,label,externalId,warnings);const shippingSet=raw.total_shipping_price_set?.shop_money?.amount;const shippingMinor=shippingSet!==undefined&&shippingSet!==null?amount(shippingSet,"shipping"):(raw.shipping_lines??[]).reduce((sum,line)=>sum+amount(line?.price,"shipping line"),0);const lines=[];for(const item of raw.line_items??[]){const lineId=item?.id===undefined||item.id===null?"":String(item.id);const quantity=quantityOf(item?.quantity);const name=optionalString(item?.name)??personName(item?.title,item?.variant_title)??`Line ${lineId}`;if(!lineId||quantity===null){warnings.push({externalId,message:`line "${name}" has no id or quantity; left out`});continue}lines.push({externalId:lineId,productExternalId:item.product_id===undefined||item.product_id===null?null:String(item.product_id),variantExternalId:item.variant_id===undefined||item.variant_id===null?null:String(item.variant_id),name,sku:optionalString(item.sku),quantity,unitPriceMinor:amount(item.price,`line "${name}" price`)})}const{status,mapped}=shopifyOrderStatus(raw);const sourceStatus=[raw.financial_status??"no payment status",raw.fulfillment_status??"unfulfilled",raw.cancelled_at?"cancelled":null].filter(Boolean).join(", ");if(!mapped)warnings.push({externalId,message:`Shopify status "${sourceStatus}" has no Stacks equivalent; imported as ${status}`});const customerEmail=normalizeEmail(raw.customer?.email)??normalizeEmail(raw.email)??normalizeEmail(raw.contact_email);const customerId=raw.customer?.id===undefined||raw.customer?.id===null?null:String(raw.customer.id);return{record:{source:"shopify",externalId,number:optionalString(raw.name)??(raw.order_number?`#${raw.order_number}`:null),currency,status,sourceStatus,totalMinor:amount(raw.total_price,"total"),taxMinor:amount(raw.total_tax,"tax"),discountMinor:amount(raw.total_discounts,"discounts"),shippingMinor,tipMinor:amount(raw.total_tip_received,"tip"),customer:customerEmail||customerId?{externalId:customerId,email:customerEmail,name:personName(raw.customer?.first_name,raw.customer?.last_name)??personName(raw.billing_address?.first_name,raw.billing_address?.last_name),phone:phoneOf(raw.customer?.phone,raw.billing_address?.phone)}:null,shippingAddress:shippingAddressOf(raw.shipping_address),note:optionalString(raw.note),placedAt:isoTimestamp(raw.processed_at)??isoTimestamp(raw.created_at),lines},warnings}}export function nextPageInfo(link){if(!link)return null;for(const part of link.split(",")){const match=/<([^>]+)>\s*;\s*rel="?next"?/i.exec(part);if(!match)continue;try{return new URL(match[1]).searchParams.get("page_info")}catch{return null}}return null}export function shopifyAdminBase(storeUrl,adminUrl){const base=normalizeStoreUrl(adminUrl??storeUrl);if(!base.startsWith("https://"))throw new TypeError(`${base} is not HTTPS. The Shopify Admin API is HTTPS only, and the access token must never travel in plain text.`);return base}async function*shopifyResource(storeUrl,options,spec){if(options.credentials.source!=="shopify")throw new TypeError("The Shopify importer needs Shopify credentials (SHOPIFY_ADMIN_TOKEN).");const base=shopifyAdminBase(storeUrl,options.adminUrl);const fetcher=options.fetch??fetch;const limit=options.limit;const pageSize=limit&&limit>0?Math.min(PAGE_SIZE,limit):PAGE_SIZE;const endpoint=`${base}/admin/api/${SHOPIFY_ADMIN_API_VERSION}/${spec.resource}.json`;const fields=spec.fields.join(",");const request={fetch:fetcher,headers:{"X-Shopify-Access-Token":options.credentials.accessToken},secrets:credentialSecrets(options.credentials),credentialHelp:CREDENTIAL_HELP,hint:`Is ${base} the store's Admin API address? For a custom domain, pass --admin-url https://<store>.myshopify.com.`,sleep:options.sleep};const seen=new Set;let emitted=0;let url=`${endpoint}?limit=${pageSize}&fields=${fields}${spec.firstQuery}`;for(let page=1;page<=MAX_PAGES;page++){const{data,headers}=await adminRequest(url,request);const list=data?.[spec.resource];if(!Array.isArray(list))throw new CatalogFetchError(url,`${url} did not return a "${spec.resource}" list. Is this the Shopify Admin API?`);const raw=list;const ids=raw.map((entry)=>String(entry?.id));if(page>1&&ids.length>0&&ids.every((id)=>seen.has(id)))throw new CatalogFetchError(url,`${url} repeated ${spec.resource} from an earlier page; stopping rather than looping.`);ids.forEach((id)=>seen.add(id));const items=[];const warnings=[];for(const entry of raw){if(limit&&emitted>=limit)break;const mapped=spec.map(entry);warnings.push(...mapped.warnings);if(mapped.record){items.push(mapped.record);emitted++}}yield{url,items,warnings};const cursor=nextPageInfo(headers.get("link"));if(!cursor||raw.length===0||limit&&emitted>=limit)return;url=`${endpoint}?limit=${pageSize}&fields=${fields}&page_info=${encodeURIComponent(cursor)}`}throw new CatalogFetchError(endpoint,`Stopped after ${MAX_PAGES} pages of ${endpoint} without reaching the end.`)}export const shopifyAccountAdapter={name:"shopify",customers:(storeUrl,options)=>shopifyResource(storeUrl,options,{resource:"customers",fields:CUSTOMER_FIELDS,firstQuery:"",map:mapShopifyCustomer}),orders:(storeUrl,options)=>shopifyResource(storeUrl,options,{resource:"orders",fields:ORDER_FIELDS,firstQuery:"&status=any",map:(raw)=>mapShopifyOrder(raw,{currency:options.currency})})};
|
package/dist/imports/shopify.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{slugify}from"@stacksjs/slug";import{CatalogFetchError,fetchJson,normalizeStoreUrl}from"./http";import{currencyExponent,decimalToMinor,PriceFormatError}from"./money";import{optionalString}from"./text";const PAGE_SIZE=250
|
|
1
|
+
import{slugify}from"@stacksjs/slug";import{CatalogFetchError,fetchJson,normalizeStoreUrl}from"./http";import{currencyExponent,decimalToMinor,PriceFormatError}from"./money";import{optionalString}from"./text";const PAGE_SIZE=250;const MAX_PAGES=400;function isDefaultOptionSet(options){if(!options||options.length===0)return true;if(options.length!==1)return false;const[only]=options;return only?.name==="Title"&&(only.values?.length??0)<=1&&(only.values?.[0]??"Default Title")==="Default Title"}function tagsOf(tags){const list=Array.isArray(tags)?tags:typeof tags==="string"?tags.split(","):[];return list.map((tag)=>String(tag).trim()).filter(Boolean)}function price(value,exponent,label,externalId,warnings){try{return decimalToMinor(value,exponent)}catch(error){if(!(error instanceof PriceFormatError))throw error;warnings.push({externalId,message:`${label}: ${error.message}; left unpriced`});return null}}export function mapShopifyProduct(raw,context){if(raw?.id===undefined||raw.id===null||raw.id==="")throw new TypeError("Shopify product has no id");const externalId=String(raw.id);const warnings=[];const name=(optionalString(raw.title)??"").replace(/\s+/g," ");if(!name)throw new TypeError(`Shopify product ${externalId} has no title`);const handle=optionalString(raw.handle)??slugify(name);const exponent=currencyExponent(context.currency);const hasOptions=!isDefaultOptionSet(raw.options);const optionNames=hasOptions?(raw.options??[]).map((option)=>optionalString(option.name)??"").filter(Boolean):[];const variants=(raw.variants??[]).map((variant)=>{const variantId=String(variant.id);const compareAt=price(variant.compare_at_price,exponent,`variant ${variantId} compare-at price`,externalId,warnings);return{externalId:variantId,title:optionalString(variant.title)??name,sku:optionalString(variant.sku),priceMinor:price(variant.price,exponent,`variant ${variantId} price`,externalId,warnings),compareAtMinor:compareAt?compareAt:null,available:variant.available!==false,inventory:typeof variant.inventory_quantity==="number"?Math.max(0,Math.trunc(variant.inventory_quantity)):null,optionValues:hasOptions?[variant.option1,variant.option2,variant.option3].slice(0,optionNames.length).map((value)=>optionalString(value)??""):[]}});if(variants.length===0)warnings.push({externalId,message:`"${name}" has no variants; imported without a price`});const images=[...raw.images??[]].filter((image)=>optionalString(image?.src)).sort((a,b)=>(a.position??0)-(b.position??0)).map((image)=>({src:optionalString(image.src),alt:optionalString(image.alt)}));const productType=optionalString(raw.product_type);return{product:{source:"shopify",externalId,name,handle,descriptionHtml:optionalString(raw.body_html),vendor:optionalString(raw.vendor),categories:productType?[{name:productType,slug:slugify(productType)}]:[],tags:tagsOf(raw.tags),currency:context.currency,images,optionNames,variants,hasOptions,url:`${context.storeUrl}/products/${handle}`},warnings}}export async function detectShopifyCurrency(storeUrl,fetcher=fetch){try{const{data}=await fetchJson(`${storeUrl}/meta.json`,fetcher);const code=typeof data?.currency==="string"?data.currency.trim().toUpperCase():"";return/^[A-Z]{3}$/.test(code)?code:null}catch{return null}}async function*shopifyPages(storeUrl,options={}){const base=normalizeStoreUrl(storeUrl);const fetcher=options.fetch??fetch;const limit=options.limit;const pageSize=limit&&limit>0?Math.min(PAGE_SIZE,limit):PAGE_SIZE;const setupWarnings=[];let currency=options.currency?.toUpperCase()??null;if(!currency){currency=await detectShopifyCurrency(base,fetcher);if(!currency)setupWarnings.push({message:`${base}/meta.json did not report a currency; prices read as 2-decimal amounts. Pass --currency to be sure.`})}const seen=new Set;let emitted=0;for(let page=1;page<=MAX_PAGES;page++){const url=`${base}/products.json?limit=${pageSize}&page=${page}`;const{data}=await fetchJson(url,fetcher,"Is this a Shopify storefront, and is it public (no storefront password)?");if(!Array.isArray(data?.products))throw new CatalogFetchError(url,`${url} did not return a "products" list. Is this a Shopify storefront?`);const raw=data.products;if(raw.length===0)return;const ids=raw.map((product)=>String(product?.id));if(page>1&&ids.every((id)=>seen.has(id)))throw new CatalogFetchError(url,`${url} repeated products from an earlier page; the store is not paginating. Use --limit to import the first page only.`);ids.forEach((id)=>seen.add(id));const products=[];const warnings=page===1?setupWarnings:[];for(const entry of raw){if(limit&&emitted>=limit)break;try{const mapped=mapShopifyProduct(entry,{storeUrl:base,currency});products.push(mapped.product);warnings.push(...mapped.warnings);emitted++}catch(error){warnings.push({externalId:entry?.id===undefined?undefined:String(entry.id),message:`skipped: ${error.message}`})}}yield{url,products,warnings};if(limit&&emitted>=limit)return}throw new CatalogFetchError(base,`Stopped after ${MAX_PAGES} pages of ${base}/products.json without reaching the end.`)}export const shopifyAdapter={name:"shopify",pages:shopifyPages};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{addressLine,amountOrZero,currencyCode,isoTimestamp,normalizeEmail,personName,phoneOf,quantityOf,signedMinor}from"./account-mapping";import{AdminCredentialError,adminRequest}from"./admin-http";import{ACCOUNT_CREDENTIAL_HELP,credentialSecrets}from"./credentials";import{CatalogFetchError,normalizeStoreUrl}from"./http";import{currencyExponent,PriceFormatError}from"./money";import{cleanName,optionalString}from"./text";const PAGE_SIZE=100,MAX_PAGES=1e4,CREDENTIAL_HELP=`Check SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET, and that the integration's role may read customers and orders. ${ACCOUNT_CREDENTIAL_HELP.shopware}`,HINT="Is this a Shopware 6 store with the Admin API reachable at /api?";export function mapShopwareCustomer(raw,context={}){const externalId=optionalString(raw?.id)??"",warnings=[],email=normalizeEmail(raw?.email);if(!externalId||!email){warnings.push({externalId:externalId||void 0,message:"skipped: the customer has no valid email address, which Stacks customers are keyed by"});return{record:null,warnings}}const currency=currencyCode(context.currency);let totalSpentMinor=null;try{totalSpentMinor=signedMinor(raw.orderTotalAmount??null,currencyExponent(currency))}catch(error){if(!(error instanceof PriceFormatError))throw error;warnings.push({externalId,message:`orderTotalAmount: ${error.message}; not imported`})}return{record:{source:"shopware",externalId,email,name:personName(raw.firstName,raw.lastName)??optionalString(raw.company)??email,phone:phoneOf(raw.defaultBillingAddress?.phoneNumber),active:typeof raw.active==="boolean"?raw.active:null,totalSpentMinor:totalSpentMinor!==null&&totalSpentMinor>=0?totalSpentMinor:null,currency,lastOrderAt:isoTimestamp(raw.lastOrderDate),avatarUrl:null,createdAt:isoTimestamp(raw.createdAt)},warnings}}function stateOf(entity){return(entity?.stateMachineState?.technicalName??"").toLowerCase()}function paymentState(raw){const transactions=[...raw.transactions??[]].sort((a,b)=>String(a?.createdAt??"").localeCompare(String(b?.createdAt??"")));return stateOf(transactions.at(-1))}export function shopwareOrderStatus(raw){const order=stateOf(raw),delivery=stateOf(raw.deliveries?.[0]),payment=paymentState(raw),sourceStatus=`order ${order||"unknown"}, delivery ${delivery||"unknown"}, payment ${payment||"unknown"}`,result=(status,mapped=!0)=>({status,mapped,sourceStatus});if(payment==="refunded")return result("REFUNDED");if(order==="cancelled")return result("CANCELLED");if(order==="completed")return result("DELIVERED");if(order==="open"||order==="in_progress"){if(delivery==="shipped")return result("SHIPPED");if(order==="in_progress"||delivery==="shipped_partially"||["paid","paid_partially","authorized"].includes(payment))return result("PROCESSING");return result("PENDING")}return result("PENDING",!1)}function addressOf(address){if(!address||!optionalString(address.street))return null;return addressLine(personName(address.firstName,address.lastName),address.company,address.street,address.additionalAddressLine1,[address.zipcode,address.city].map((part)=>cleanName(part)).filter(Boolean).join(" "),address.country?.iso??address.country?.name)}function payloadOf(item){return item.payload&&typeof item.payload==="object"&&!Array.isArray(item.payload)?item.payload:{}}export function shopwareLineLabel(label,options){const values=Array.isArray(options)?options.map((option)=>cleanName(option?.option)).filter(Boolean):[];return values.length>0&&!values.every((value)=>label.includes(value))?`${label} - ${values.join(", ")}`:label}export function mapShopwareOrder(raw,context={}){const externalId=optionalString(raw?.id)??"",warnings=[];if(!externalId){warnings.push({message:"skipped: a Shopware order has no id"});return{record:null,warnings}}const currency=currencyCode(raw.currency?.isoCode)??currencyCode(context.currency);if(!currency){warnings.push({externalId,message:"skipped: the order names no currency; pass --currency"});return{record:null,warnings}}const exponent=currencyExponent(currency),amount=(value,label)=>amountOrZero(value,exponent,label,externalId,warnings),lines=[];let discountMinor=0;for(const item of raw.lineItems??[]){if(optionalString(item?.parentId))continue;const lineId=optionalString(item?.id)??"",name=cleanName(item?.label)||`Line ${lineId}`,type=(item?.type??"").toLowerCase();let total=null;try{total=signedMinor(item?.totalPrice??null,exponent)}catch(error){if(!(error instanceof PriceFormatError))throw error;warnings.push({externalId,message:`line "${name}": ${error.message}; left out`});continue}if(type==="promotion"||type==="credit"||total!==null&&total<0){discountMinor+=Math.abs(total??0);continue}const quantity=quantityOf(item?.quantity);if(!lineId||quantity===null){warnings.push({externalId,message:`line "${name}" has no id or quantity; left out`});continue}const deleted=type==="product"&&item.productId===null,productId=type==="product"&&!deleted?optionalString(item.productId)??optionalString(item.referencedId):null,payload=payloadOf(item);lines.push({externalId:lineId,productExternalId:optionalString(payload.parentId)??productId,variantExternalId:productId,name:shopwareLineLabel(name,payload.options),sku:optionalString(payload.productNumber),quantity,unitPriceMinor:amount(item.unitPrice,`line "${name}" unit price`)})}const totalMinor=amount(raw.amountTotal,"total"),netMinor=raw.amountNet===null||raw.amountNet===void 0?totalMinor:amount(raw.amountNet,"net total"),{status,mapped,sourceStatus}=shopwareOrderStatus(raw);if(!mapped)warnings.push({externalId,message:`Shopware state "${sourceStatus}" has no Stacks equivalent; imported as ${status}`});const billing=(raw.addresses??[]).find((address)=>address?.id&&address.id===raw.billingAddressId),shipping=raw.deliveries?.[0]?.shippingOrderAddress??(raw.addresses??[]).find((address)=>address?.id&&address.id!==raw.billingAddressId)??null,email=normalizeEmail(raw.orderCustomer?.email),customerId=optionalString(raw.orderCustomer?.customerId);return{record:{source:"shopware",externalId,number:optionalString(raw.orderNumber),currency,status,sourceStatus,totalMinor,taxMinor:Math.max(0,totalMinor-netMinor),discountMinor,shippingMinor:amount(raw.shippingTotal,"shipping"),tipMinor:0,customer:email||customerId?{externalId:customerId,email,name:personName(raw.orderCustomer?.firstName,raw.orderCustomer?.lastName),phone:phoneOf(billing?.phoneNumber)}:null,shippingAddress:addressOf(shipping),note:optionalString(raw.customerComment),placedAt:isoTimestamp(raw.orderDateTime),lines},warnings}}export function shopwareAdminBase(storeUrl,adminUrl){const base=normalizeStoreUrl(adminUrl??storeUrl).replace(/\/(?:store-)?api$/i,""),{protocol,hostname}=new URL(base),loopback=hostname==="localhost"||hostname==="127.0.0.1"||hostname==="[::1]"||hostname.endsWith(".localhost");if(protocol!=="https:"&&!loopback)throw TypeError(`${base} is not HTTPS. The Shopware integration secret and bearer token must never travel in plain text.`);return base}export function shopwareCustomerCriteria(page,limit){return{page,limit,"total-count-mode":1,sort:[{field:"id",order:"ASC"}],associations:{defaultBillingAddress:{}},includes:{customer:["id","customerNumber","email","firstName","lastName","company","active","guest","orderTotalAmount","lastOrderDate","createdAt","defaultBillingAddress"],customer_address:["phoneNumber"]}}}const ADDRESS_FIELDS=["id","firstName","lastName","company","street","additionalAddressLine1","zipcode","city","phoneNumber","country"];export function shopwareOrderCriteria(page,limit){return{page,limit,"total-count-mode":1,sort:[{field:"id",order:"ASC"}],associations:{lineItems:{},addresses:{associations:{country:{}}},currency:{},stateMachineState:{},orderCustomer:{},deliveries:{associations:{stateMachineState:{},shippingOrderAddress:{associations:{country:{}}}}},transactions:{associations:{stateMachineState:{}}}},includes:{order:["id","orderNumber","orderDateTime","amountTotal","amountNet","shippingTotal","customerComment","billingAddressId","currency","stateMachineState","orderCustomer","lineItems","addresses","deliveries","transactions"],order_line_item:["id","parentId","productId","referencedId","label","quantity","unitPrice","totalPrice","type","payload"],order_customer:["customerId","email","firstName","lastName"],order_address:ADDRESS_FIELDS,order_delivery:["shippingOrderAddress","stateMachineState"],order_transaction:["stateMachineState","createdAt"],currency:["isoCode"],country:["iso","name"],state_machine_state:["technicalName"]}}}export async function shopwareAccessToken(base,clientId,clientSecret,request){const url=`${base}/api/oauth/token`,{data}=await adminRequest(url,{...request,json:{grant_type:"client_credentials",client_id:clientId,client_secret:clientSecret}}),token=typeof data?.access_token==="string"?data.access_token.trim():"";if(!token)throw new CatalogFetchError(url,`${url} returned no access_token. ${HINT}`);return token}async function*shopwareResource(storeUrl,options,entity,criteria,map){if(options.credentials.source!=="shopware")throw TypeError("The Shopware importer needs Shopware credentials (SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET).");const base=shopwareAdminBase(storeUrl,options.adminUrl),{clientId,clientSecret}=options.credentials,secrets=credentialSecrets(options.credentials),shared={fetch:options.fetch??fetch,secrets,credentialHelp:CREDENTIAL_HELP,hint:HINT,sleep:options.sleep};let token=await shopwareAccessToken(base,clientId,clientSecret,shared);const search=async(url,body)=>{const call=()=>adminRequest(url,{...shared,secrets:[...secrets,token],headers:{authorization:`Bearer ${token}`},json:body});try{return await call()}catch(error){if(!(error instanceof AdminCredentialError)||error.status!==401)throw error;token=await shopwareAccessToken(base,clientId,clientSecret,shared);return await call()}},url=`${base}/api/search/${entity}`,limit=options.limit,pageSize=limit&&limit>0?Math.min(PAGE_SIZE,limit):PAGE_SIZE,seen=new Set;let emitted=0;for(let page=1;page<=MAX_PAGES;page++){const label=`${url} (page ${page})`,{data}=await search(url,criteria(page,pageSize));if(!Array.isArray(data?.data))throw new CatalogFetchError(url,`${label} did not return a "data" list. ${HINT}`);const raw=data.data;if(raw.length===0)return;const ids=raw.map((entry)=>String(entry?.id));if(page>1&&ids.every((id)=>seen.has(id)))throw new CatalogFetchError(url,`${label} repeated ${entity}s from an earlier page; the store is not paginating.`);ids.forEach((id)=>seen.add(id));const items=[],warnings=[];for(const entry of raw){if(limit&&emitted>=limit)break;const mapped=map(entry);warnings.push(...mapped.warnings);if(mapped.record){items.push(mapped.record);emitted++}}yield{url:label,items,warnings};if(limit&&emitted>=limit)return;const total=typeof data.total==="number"?data.total:Number.NaN;if(raw.length<pageSize||Number.isInteger(total)&&page*pageSize>=total)return}throw new CatalogFetchError(url,`Stopped after ${MAX_PAGES} pages of ${url} without reaching the end.`)}export const shopwareAccountAdapter={name:"shopware",customers:(storeUrl,options)=>shopwareResource(storeUrl,options,"customer",shopwareCustomerCriteria,(raw)=>mapShopwareCustomer(raw,{currency:options.currency})),orders:(storeUrl,options)=>shopwareResource(storeUrl,options,"order",shopwareOrderCriteria,(raw)=>mapShopwareOrder(raw,{currency:options.currency}))};
|
|
1
|
+
import{addressLine,amountOrZero,currencyCode,isoTimestamp,normalizeEmail,personName,phoneOf,quantityOf,signedMinor}from"./account-mapping";import{AdminCredentialError,adminRequest}from"./admin-http";import{ACCOUNT_CREDENTIAL_HELP,credentialSecrets}from"./credentials";import{CatalogFetchError,normalizeStoreUrl}from"./http";import{currencyExponent,PriceFormatError}from"./money";import{cleanName,optionalString}from"./text";const PAGE_SIZE=100;const MAX_PAGES=1e4;const CREDENTIAL_HELP=`Check SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET, and that the integration's role may read customers and orders. ${ACCOUNT_CREDENTIAL_HELP.shopware}`;const HINT="Is this a Shopware 6 store with the Admin API reachable at /api?";export function mapShopwareCustomer(raw,context={}){const externalId=optionalString(raw?.id)??"";const warnings=[];const email=normalizeEmail(raw?.email);if(!externalId||!email){warnings.push({externalId:externalId||undefined,message:"skipped: the customer has no valid email address, which Stacks customers are keyed by"});return{record:null,warnings}}const currency=currencyCode(context.currency);let totalSpentMinor=null;try{totalSpentMinor=signedMinor(raw.orderTotalAmount??null,currencyExponent(currency))}catch(error){if(!(error instanceof PriceFormatError))throw error;warnings.push({externalId,message:`orderTotalAmount: ${error.message}; not imported`})}return{record:{source:"shopware",externalId,email,name:personName(raw.firstName,raw.lastName)??optionalString(raw.company)??email,phone:phoneOf(raw.defaultBillingAddress?.phoneNumber),active:typeof raw.active==="boolean"?raw.active:null,totalSpentMinor:totalSpentMinor!==null&&totalSpentMinor>=0?totalSpentMinor:null,currency,lastOrderAt:isoTimestamp(raw.lastOrderDate),avatarUrl:null,createdAt:isoTimestamp(raw.createdAt)},warnings}}function stateOf(entity){return(entity?.stateMachineState?.technicalName??"").toLowerCase()}function paymentState(raw){const transactions=[...raw.transactions??[]].sort((a,b)=>String(a?.createdAt??"").localeCompare(String(b?.createdAt??"")));return stateOf(transactions.at(-1))}export function shopwareOrderStatus(raw){const order=stateOf(raw);const delivery=stateOf(raw.deliveries?.[0]);const payment=paymentState(raw);const sourceStatus=`order ${order||"unknown"}, delivery ${delivery||"unknown"}, payment ${payment||"unknown"}`;const result=(status,mapped=true)=>({status,mapped,sourceStatus});if(payment==="refunded")return result("REFUNDED");if(order==="cancelled")return result("CANCELLED");if(order==="completed")return result("DELIVERED");if(order==="open"||order==="in_progress"){if(delivery==="shipped")return result("SHIPPED");if(order==="in_progress"||delivery==="shipped_partially"||["paid","paid_partially","authorized"].includes(payment))return result("PROCESSING");return result("PENDING")}return result("PENDING",false)}function addressOf(address){if(!address||!optionalString(address.street))return null;return addressLine(personName(address.firstName,address.lastName),address.company,address.street,address.additionalAddressLine1,[address.zipcode,address.city].map((part)=>cleanName(part)).filter(Boolean).join(" "),address.country?.iso??address.country?.name)}function payloadOf(item){return item.payload&&typeof item.payload==="object"&&!Array.isArray(item.payload)?item.payload:{}}export function shopwareLineLabel(label,options){const values=Array.isArray(options)?options.map((option)=>cleanName(option?.option)).filter(Boolean):[];return values.length>0&&!values.every((value)=>label.includes(value))?`${label} - ${values.join(", ")}`:label}export function mapShopwareOrder(raw,context={}){const externalId=optionalString(raw?.id)??"";const warnings=[];if(!externalId){warnings.push({message:"skipped: a Shopware order has no id"});return{record:null,warnings}}const currency=currencyCode(raw.currency?.isoCode)??currencyCode(context.currency);if(!currency){warnings.push({externalId,message:"skipped: the order names no currency; pass --currency"});return{record:null,warnings}}const exponent=currencyExponent(currency);const amount=(value,label)=>amountOrZero(value,exponent,label,externalId,warnings);const lines=[];let discountMinor=0;for(const item of raw.lineItems??[]){if(optionalString(item?.parentId))continue;const lineId=optionalString(item?.id)??"";const name=cleanName(item?.label)||`Line ${lineId}`;const type=(item?.type??"").toLowerCase();let total=null;try{total=signedMinor(item?.totalPrice??null,exponent)}catch(error){if(!(error instanceof PriceFormatError))throw error;warnings.push({externalId,message:`line "${name}": ${error.message}; left out`});continue}if(type==="promotion"||type==="credit"||total!==null&&total<0){discountMinor+=Math.abs(total??0);continue}const quantity=quantityOf(item?.quantity);if(!lineId||quantity===null){warnings.push({externalId,message:`line "${name}" has no id or quantity; left out`});continue}const deleted=type==="product"&&item.productId===null;const productId=type==="product"&&!deleted?optionalString(item.productId)??optionalString(item.referencedId):null;const payload=payloadOf(item);lines.push({externalId:lineId,productExternalId:optionalString(payload.parentId)??productId,variantExternalId:productId,name:shopwareLineLabel(name,payload.options),sku:optionalString(payload.productNumber),quantity,unitPriceMinor:amount(item.unitPrice,`line "${name}" unit price`)})}const totalMinor=amount(raw.amountTotal,"total");const netMinor=raw.amountNet===null||raw.amountNet===undefined?totalMinor:amount(raw.amountNet,"net total");const{status,mapped,sourceStatus}=shopwareOrderStatus(raw);if(!mapped)warnings.push({externalId,message:`Shopware state "${sourceStatus}" has no Stacks equivalent; imported as ${status}`});const billing=(raw.addresses??[]).find((address)=>address?.id&&address.id===raw.billingAddressId);const shipping=raw.deliveries?.[0]?.shippingOrderAddress??(raw.addresses??[]).find((address)=>address?.id&&address.id!==raw.billingAddressId)??null;const email=normalizeEmail(raw.orderCustomer?.email);const customerId=optionalString(raw.orderCustomer?.customerId);return{record:{source:"shopware",externalId,number:optionalString(raw.orderNumber),currency,status,sourceStatus,totalMinor,taxMinor:Math.max(0,totalMinor-netMinor),discountMinor,shippingMinor:amount(raw.shippingTotal,"shipping"),tipMinor:0,customer:email||customerId?{externalId:customerId,email,name:personName(raw.orderCustomer?.firstName,raw.orderCustomer?.lastName),phone:phoneOf(billing?.phoneNumber)}:null,shippingAddress:addressOf(shipping),note:optionalString(raw.customerComment),placedAt:isoTimestamp(raw.orderDateTime),lines},warnings}}export function shopwareAdminBase(storeUrl,adminUrl){const base=normalizeStoreUrl(adminUrl??storeUrl).replace(/\/(?:store-)?api$/i,"");const{protocol,hostname}=new URL(base);const loopback=hostname==="localhost"||hostname==="127.0.0.1"||hostname==="[::1]"||hostname.endsWith(".localhost");if(protocol!=="https:"&&!loopback)throw new TypeError(`${base} is not HTTPS. The Shopware integration secret and bearer token must never travel in plain text.`);return base}export function shopwareCustomerCriteria(page,limit){return{page,limit,"total-count-mode":1,sort:[{field:"id",order:"ASC"}],associations:{defaultBillingAddress:{}},includes:{customer:["id","customerNumber","email","firstName","lastName","company","active","guest","orderTotalAmount","lastOrderDate","createdAt","defaultBillingAddress"],customer_address:["phoneNumber"]}}}const ADDRESS_FIELDS=["id","firstName","lastName","company","street","additionalAddressLine1","zipcode","city","phoneNumber","country"];export function shopwareOrderCriteria(page,limit){return{page,limit,"total-count-mode":1,sort:[{field:"id",order:"ASC"}],associations:{lineItems:{},addresses:{associations:{country:{}}},currency:{},stateMachineState:{},orderCustomer:{},deliveries:{associations:{stateMachineState:{},shippingOrderAddress:{associations:{country:{}}}}},transactions:{associations:{stateMachineState:{}}}},includes:{order:["id","orderNumber","orderDateTime","amountTotal","amountNet","shippingTotal","customerComment","billingAddressId","currency","stateMachineState","orderCustomer","lineItems","addresses","deliveries","transactions"],order_line_item:["id","parentId","productId","referencedId","label","quantity","unitPrice","totalPrice","type","payload"],order_customer:["customerId","email","firstName","lastName"],order_address:ADDRESS_FIELDS,order_delivery:["shippingOrderAddress","stateMachineState"],order_transaction:["stateMachineState","createdAt"],currency:["isoCode"],country:["iso","name"],state_machine_state:["technicalName"]}}}export async function shopwareAccessToken(base,clientId,clientSecret,request){const url=`${base}/api/oauth/token`;const{data}=await adminRequest(url,{...request,json:{grant_type:"client_credentials",client_id:clientId,client_secret:clientSecret}});const token=typeof data?.access_token==="string"?data.access_token.trim():"";if(!token)throw new CatalogFetchError(url,`${url} returned no access_token. ${HINT}`);return token}async function*shopwareResource(storeUrl,options,entity,criteria,map){if(options.credentials.source!=="shopware")throw new TypeError("The Shopware importer needs Shopware credentials (SHOPWARE_CLIENT_ID and SHOPWARE_CLIENT_SECRET).");const base=shopwareAdminBase(storeUrl,options.adminUrl);const{clientId,clientSecret}=options.credentials;const secrets=credentialSecrets(options.credentials);const fetcher=options.fetch??fetch;const shared={fetch:fetcher,secrets,credentialHelp:CREDENTIAL_HELP,hint:HINT,sleep:options.sleep};let token=await shopwareAccessToken(base,clientId,clientSecret,shared);const search=async(url,body)=>{const call=()=>adminRequest(url,{...shared,secrets:[...secrets,token],headers:{authorization:`Bearer ${token}`},json:body});try{return await call()}catch(error){if(!(error instanceof AdminCredentialError)||error.status!==401)throw error;token=await shopwareAccessToken(base,clientId,clientSecret,shared);return await call()}};const url=`${base}/api/search/${entity}`;const limit=options.limit;const pageSize=limit&&limit>0?Math.min(PAGE_SIZE,limit):PAGE_SIZE;const seen=new Set;let emitted=0;for(let page=1;page<=MAX_PAGES;page++){const label=`${url} (page ${page})`;const{data}=await search(url,criteria(page,pageSize));if(!Array.isArray(data?.data))throw new CatalogFetchError(url,`${label} did not return a "data" list. ${HINT}`);const raw=data.data;if(raw.length===0)return;const ids=raw.map((entry)=>String(entry?.id));if(page>1&&ids.every((id)=>seen.has(id)))throw new CatalogFetchError(url,`${label} repeated ${entity}s from an earlier page; the store is not paginating.`);ids.forEach((id)=>seen.add(id));const items=[];const warnings=[];for(const entry of raw){if(limit&&emitted>=limit)break;const mapped=map(entry);warnings.push(...mapped.warnings);if(mapped.record){items.push(mapped.record);emitted++}}yield{url:label,items,warnings};if(limit&&emitted>=limit)return;const total=typeof data.total==="number"?data.total:Number.NaN;if(raw.length<pageSize||Number.isInteger(total)&&page*pageSize>=total)return}throw new CatalogFetchError(url,`Stopped after ${MAX_PAGES} pages of ${url} without reaching the end.`)}export const shopwareAccountAdapter={name:"shopware",customers:(storeUrl,options)=>shopwareResource(storeUrl,options,"customer",shopwareCustomerCriteria,(raw)=>mapShopwareCustomer(raw,{currency:options.currency})),orders:(storeUrl,options)=>shopwareResource(storeUrl,options,"order",shopwareOrderCriteria,(raw)=>mapShopwareOrder(raw,{currency:options.currency}))};
|
package/dist/imports/shopware.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{slugify}from"@stacksjs/slug";import{CatalogFetchError,fetchJson,normalizeStoreUrl}from"./http";import{currencyExponent,numberToMinor,PriceFormatError}from"./money";import{optionalString}from"./text";const PAGE_SIZE=100,MAX_PAGES=1000,API_PREFIX="/store-api",HINT="Is this a Shopware 6 store with the Store API reachable at /store-api?";export const SHOPWARE_ACCESS_KEY_HELP='Find it in the Shopware Administration under Sales Channels: open the storefront or headless sales channel and copy the key from its "API access" card. A headless storefront also ships it in its page source.';function translated(entity,field){if(!entity)return null;const record=entity,bag=record.translated;return(bag&&typeof bag==="object"&&!Array.isArray(bag)?optionalString(bag[field]):null)??optionalString(record[field])}function nameOf(entity){return translated(entity,"name")?.replace(/\s+/g," ")??null}function stockOf(raw){const value=typeof raw.availableStock==="number"?raw.availableStock:raw.stock;return typeof value==="number"&&Number.isFinite(value)?Math.max(0,Math.trunc(value)):null}function availableOf(raw){return raw.available!==!1&&raw.active!==!1}function pricesOf(raw,label,externalId,context,warnings){const exponent=currencyExponent(context.currency),unit=raw.calculatedPrice?.unitPrice;if(unit===null||unit===void 0||unit===""){warnings.push({externalId,message:`${label} has no price in ${context.currency??"the sales channel currency"}; left unpriced`});return{priceMinor:null,compareAtMinor:null}}try{const priceMinor=numberToMinor(unit,exponent),listMinor=numberToMinor(raw.calculatedPrice?.listPrice?.price??null,exponent);return{priceMinor,compareAtMinor:listMinor!==null&&priceMinor!==null&&listMinor>priceMinor?listMinor:null}}catch(error){if(!(error instanceof PriceFormatError))throw error;warnings.push({externalId,message:`${label}: ${error.message}; left unpriced`});return{priceMinor:null,compareAtMinor:null}}}function imagesOf(raw){const entries=[...raw.media??[]].sort((a,b)=>(a?.position??0)-(b?.position??0));if(raw.cover)entries.unshift(raw.cover);const seen=new Set,images=[];for(const entry of entries){const src=optionalString(entry?.media?.url);if(!src||seen.has(src))continue;seen.add(src);const media=entry.media;images.push({src,alt:translated(media,"alt")??translated(media,"title")})}return images}function categoriesOf(raw){const seen=new Set,categories=[];for(const entry of[raw.seoCategory,...raw.categories??[]]){const name=nameOf(entry),key=name?slugify(name):"";if(!name||!key||seen.has(key))continue;seen.add(key);categories.push({name,slug:key})}return categories}function optionAxes(children){const axes=new Map;for(const child of children)for(const option of child.options??[]){const name=nameOf(option.group),key=optionalString(option.groupId)??optionalString(option.group?.id)??name;if(!key||!name||axes.has(key))continue;axes.set(key,{key,name,position:option.group?.position??0,order:axes.size})}return[...axes.values()].sort((a,b)=>a.position-b.position||a.order-b.order)}function optionFor(child,axis){return(child.options??[]).find((option)=>(optionalString(option.groupId)??optionalString(option.group?.id)??nameOf(option.group))===axis.key)}export function mapShopwareProduct(raw,context){if(!optionalString(raw?.id))throw TypeError("Shopware product has no id");const externalId=raw.id,warnings=[],name=nameOf(raw);if(!name)throw TypeError(`Shopware product ${externalId} has no name`);const children=context.children??[],childCount=typeof raw.childCount==="number"?raw.childCount:0,hasOptions=children.length>0;let variants,optionNames=[];if(hasOptions){const axes=optionAxes(children);optionNames=axes.map((axis)=>axis.name);const rows=children.map((child)=>{const picked=axes.map((axis)=>optionFor(child,axis)),optionValues=picked.map((option)=>nameOf(option)??""),productNumber=optionalString(child.productNumber),label=`variant ${productNumber??child.id}`,prices=pricesOf(child,label,externalId,context,warnings);return{variant:{externalId:String(child.id),title:optionValues.filter(Boolean).join(" / ")||nameOf(child)||productNumber||name,sku:productNumber,priceMinor:prices.priceMinor,compareAtMinor:prices.compareAtMinor,available:availableOf(child),inventory:stockOf(child),optionValues},sortKey:picked.map((option)=>option?.position??0),productNumber:productNumber??""}});rows.sort((a,b)=>{for(let i=0;i<a.sortKey.length;i++){const delta=(a.sortKey[i]??0)-(b.sortKey[i]??0);if(delta!==0)return delta}return a.productNumber.localeCompare(b.productNumber)});variants=rows.map((row)=>row.variant)}else if(childCount>0){warnings.push({externalId,message:`"${name}" has ${childCount} variant${childCount===1?"":"s"} in Shopware, none visible to this sales channel; imported without a price`});variants=[]}else{const prices=pricesOf(raw,`"${name}"`,externalId,context,warnings);variants=[{externalId,title:name,sku:optionalString(raw.productNumber),priceMinor:prices.priceMinor,compareAtMinor:prices.compareAtMinor,available:availableOf(raw),inventory:stockOf(raw),optionValues:[]}]}return{product:{source:"shopware",externalId,name,handle:slugify(name),descriptionHtml:translated(raw,"description"),vendor:nameOf(raw.manufacturer),categories:categoriesOf(raw),tags:(raw.tags??[]).map((tag)=>optionalString(tag?.name)).filter((tag)=>tag!==null),currency:context.currency,images:imagesOf(raw),optionNames,variants,hasOptions,url:`${context.storeUrl}/detail/${externalId}`},warnings}}export function shopwareBaseUrl(storeUrl){return normalizeStoreUrl(storeUrl).replace(/\/store-api$/i,"")}export function missingAccessKeyMessage(){return`Shopware's Store API needs the sales channel access key: pass --access-key <key> or set SHOPWARE_ACCESS_KEY. It is public by design and not a secret. ${SHOPWARE_ACCESS_KEY_HELP}`}function shopwareErrorDetail(body){if(!body)return null;try{const first=JSON.parse(body)?.errors?.[0];return optionalString(first?.detail)??optionalString(first?.title)}catch{return null}}function explain(error){const detail=shopwareErrorDetail(error.body),said=detail?` Shopware said: "${detail}"`:"";if(error.status===401||error.status===403||error.status===412)return new CatalogFetchError(error.url,`${error.message}${said} The sales channel access key looks wrong: check --access-key or SHOPWARE_ACCESS_KEY. ${SHOPWARE_ACCESS_KEY_HELP}`,error.status,error.body);return new CatalogFetchError(error.url,`${error.message}${said} ${HINT}`,error.status,error.body)}async function storeApi(url,accessKey,fetcher,json){try{const{data}=await fetchJson(url,fetcher,"",{headers:{"sw-access-key":accessKey},json});return data}catch(error){if(!(error instanceof CatalogFetchError))throw error;throw explain(error)}}function isKeyError(error){return error instanceof CatalogFetchError&&(error.status===401||error.status===403||error.status===412)}export async function detectShopwareCurrency(base,accessKey,fetcher=fetch){try{const data=await storeApi(`${base}${API_PREFIX}/context`,accessKey,fetcher),code=typeof data?.currency?.isoCode==="string"?data.currency.isoCode.trim().toUpperCase():"";return/^[A-Z]{3}$/.test(code)?code:null}catch(error){if(isKeyError(error))throw error;return null}}const INCLUDES={product:["id","parentId","productNumber","name","description","translated","calculatedPrice","stock","availableStock","available","active","childCount","manufacturer","seoCategory","categories","tags","cover","media","options"],calculated_price:["unitPrice","quantity","listPrice"],cart_list_price:["price"],product_media:["position","media"],media:["url","alt","title","translated"],product_manufacturer:["name","translated"],category:["name","translated"],tag:["name"],property_group_option:["id","name","translated","position","groupId","group"],property_group:["id","name","translated","position"]};export function shopwareProductCriteria(page,limit){return{page,limit,"total-count-mode":"exact",filter:[{type:"equals",field:"parentId",value:null}],sort:[{field:"id",order:"ASC"}],associations:{cover:{},media:{associations:{media:{}}},manufacturer:{},categories:{},tags:{}},includes:INCLUDES}}export function shopwareVariantCriteria(parentIds,page){return{page,limit:PAGE_SIZE,"total-count-mode":"exact",filter:[{type:"equalsAny",field:"parentId",value:parentIds}],sort:[{field:"id",order:"ASC"}],associations:{options:{associations:{group:{}}}},includes:INCLUDES}}function isLastPage(data,page,pageSize,received){if(received<pageSize)return!0;const total=typeof data.total==="number"?data.total:Number.NaN;return Number.isInteger(total)&&page*pageSize>=total}async function fetchChildren(base,accessKey,parentIds,fetcher){const found=new Map;if(parentIds.length===0)return found;const url=`${base}${API_PREFIX}/product`;for(let page=1;page<=MAX_PAGES;page++){const data=await storeApi(url,accessKey,fetcher,shopwareVariantCriteria(parentIds,page));if(!Array.isArray(data?.elements))throw new CatalogFetchError(url,`${url} did not return a product list for the variants. ${HINT}`);const elements=data.elements;for(const child of elements){const parent=optionalString(child?.parentId);if(!parent)continue;const list=found.get(parent)??[];list.push(child);found.set(parent,list)}if(elements.length===0||isLastPage(data,page,PAGE_SIZE,elements.length))return found}throw new CatalogFetchError(url,`Stopped after ${MAX_PAGES} pages of variants from ${url} without reaching the end.`)}async function*shopwarePages(storeUrl,options={}){const accessKey=options.accessKey?.trim();if(!accessKey)throw TypeError(missingAccessKeyMessage());const base=shopwareBaseUrl(storeUrl),fetcher=options.fetch??fetch,limit=options.limit,pageSize=limit&&limit>0?Math.min(PAGE_SIZE,limit):PAGE_SIZE,url=`${base}${API_PREFIX}/product`,setupWarnings=[],override=options.currency?.trim().toUpperCase()||null,detected=await detectShopwareCurrency(base,accessKey,fetcher),currency=detected??override;if(detected&&override&&detected!==override)setupWarnings.push({message:`--currency ${override} ignored: this sales channel prices in ${detected}, and the Store API does not convert.`});if(!currency)setupWarnings.push({message:`${base}${API_PREFIX}/context did not report a currency; prices read as 2-decimal amounts. Pass --currency to be sure.`});const seen=new Set;let emitted=0;for(let page=1;page<=MAX_PAGES;page++){const label=`${url} (page ${page})`;let data;try{data=await storeApi(url,accessKey,fetcher,shopwareProductCriteria(page,pageSize))}catch(error){if(error instanceof CatalogFetchError)throw new CatalogFetchError(error.url,error.message.replace(error.url,label),error.status,error.body);throw error}if(!Array.isArray(data?.elements))throw new CatalogFetchError(url,`${label} did not return a product list. ${HINT}`);const elements=data.elements;if(elements.length===0)return;const ids=elements.map((element)=>String(element?.id));if(page>1&&ids.every((id)=>seen.has(id)))throw new CatalogFetchError(url,`${label} repeated products from an earlier page; the store is not paginating. Use --limit to import the first page only.`);ids.forEach((id)=>seen.add(id));const take=limit?elements.slice(0,Math.max(0,limit-emitted)):elements,warnings=page===1?setupWarnings:[],parents=take.filter((item)=>typeof item?.childCount==="number"&&item.childCount>0).map((item)=>String(item.id)),children=await fetchChildren(base,accessKey,parents,fetcher),products=[];for(const entry of take)try{const mapped=mapShopwareProduct(entry,{storeUrl:base,currency,children:children.get(String(entry?.id))});products.push(mapped.product);warnings.push(...mapped.warnings);emitted++}catch(error){warnings.push({externalId:entry?.id===void 0?void 0:String(entry.id),message:`skipped: ${error.message}`})}yield{url:label,products,warnings};if(limit&&emitted>=limit)return;if(isLastPage(data,page,pageSize,elements.length))return}throw new CatalogFetchError(url,`Stopped after ${MAX_PAGES} pages of ${url} without reaching the end.`)}export const shopwareAdapter={name:"shopware",pages:shopwarePages};
|
|
1
|
+
import{slugify}from"@stacksjs/slug";import{CatalogFetchError,fetchJson,normalizeStoreUrl}from"./http";import{currencyExponent,numberToMinor,PriceFormatError}from"./money";import{optionalString}from"./text";const PAGE_SIZE=100;const MAX_PAGES=1000;const API_PREFIX="/store-api";const HINT="Is this a Shopware 6 store with the Store API reachable at /store-api?";export const SHOPWARE_ACCESS_KEY_HELP='Find it in the Shopware Administration under Sales Channels: open the storefront or headless sales channel and copy the key from its "API access" card. A headless storefront also ships it in its page source.';function translated(entity,field){if(!entity)return null;const record=entity;const bag=record.translated;const own=bag&&typeof bag==="object"&&!Array.isArray(bag)?optionalString(bag[field]):null;return own??optionalString(record[field])}function nameOf(entity){return translated(entity,"name")?.replace(/\s+/g," ")??null}function stockOf(raw){const value=typeof raw.availableStock==="number"?raw.availableStock:raw.stock;return typeof value==="number"&&Number.isFinite(value)?Math.max(0,Math.trunc(value)):null}function availableOf(raw){return raw.available!==false&&raw.active!==false}function pricesOf(raw,label,externalId,context,warnings){const exponent=currencyExponent(context.currency);const unit=raw.calculatedPrice?.unitPrice;if(unit===null||unit===undefined||unit===""){warnings.push({externalId,message:`${label} has no price in ${context.currency??"the sales channel currency"}; left unpriced`});return{priceMinor:null,compareAtMinor:null}}try{const priceMinor=numberToMinor(unit,exponent);const listMinor=numberToMinor(raw.calculatedPrice?.listPrice?.price??null,exponent);return{priceMinor,compareAtMinor:listMinor!==null&&priceMinor!==null&&listMinor>priceMinor?listMinor:null}}catch(error){if(!(error instanceof PriceFormatError))throw error;warnings.push({externalId,message:`${label}: ${error.message}; left unpriced`});return{priceMinor:null,compareAtMinor:null}}}function imagesOf(raw){const entries=[...raw.media??[]].sort((a,b)=>(a?.position??0)-(b?.position??0));if(raw.cover)entries.unshift(raw.cover);const seen=new Set;const images=[];for(const entry of entries){const src=optionalString(entry?.media?.url);if(!src||seen.has(src))continue;seen.add(src);const media=entry.media;images.push({src,alt:translated(media,"alt")??translated(media,"title")})}return images}function categoriesOf(raw){const seen=new Set;const categories=[];for(const entry of[raw.seoCategory,...raw.categories??[]]){const name=nameOf(entry);const key=name?slugify(name):"";if(!name||!key||seen.has(key))continue;seen.add(key);categories.push({name,slug:key})}return categories}function optionAxes(children){const axes=new Map;for(const child of children){for(const option of child.options??[]){const name=nameOf(option.group);const key=optionalString(option.groupId)??optionalString(option.group?.id)??name;if(!key||!name||axes.has(key))continue;axes.set(key,{key,name,position:option.group?.position??0,order:axes.size})}}return[...axes.values()].sort((a,b)=>a.position-b.position||a.order-b.order)}function optionFor(child,axis){return(child.options??[]).find((option)=>(optionalString(option.groupId)??optionalString(option.group?.id)??nameOf(option.group))===axis.key)}export function mapShopwareProduct(raw,context){if(!optionalString(raw?.id))throw new TypeError("Shopware product has no id");const externalId=raw.id;const warnings=[];const name=nameOf(raw);if(!name)throw new TypeError(`Shopware product ${externalId} has no name`);const children=context.children??[];const childCount=typeof raw.childCount==="number"?raw.childCount:0;const hasOptions=children.length>0;let variants;let optionNames=[];if(hasOptions){const axes=optionAxes(children);optionNames=axes.map((axis)=>axis.name);const rows=children.map((child)=>{const picked=axes.map((axis)=>optionFor(child,axis));const optionValues=picked.map((option)=>nameOf(option)??"");const productNumber=optionalString(child.productNumber);const label=`variant ${productNumber??child.id}`;const prices=pricesOf(child,label,externalId,context,warnings);const variant={externalId:String(child.id),title:optionValues.filter(Boolean).join(" / ")||nameOf(child)||productNumber||name,sku:productNumber,priceMinor:prices.priceMinor,compareAtMinor:prices.compareAtMinor,available:availableOf(child),inventory:stockOf(child),optionValues};return{variant,sortKey:picked.map((option)=>option?.position??0),productNumber:productNumber??""}});rows.sort((a,b)=>{for(let i=0;i<a.sortKey.length;i++){const delta=(a.sortKey[i]??0)-(b.sortKey[i]??0);if(delta!==0)return delta}return a.productNumber.localeCompare(b.productNumber)});variants=rows.map((row)=>row.variant)}else if(childCount>0){warnings.push({externalId,message:`"${name}" has ${childCount} variant${childCount===1?"":"s"} in Shopware, none visible to this sales channel; imported without a price`});variants=[]}else{const prices=pricesOf(raw,`"${name}"`,externalId,context,warnings);variants=[{externalId,title:name,sku:optionalString(raw.productNumber),priceMinor:prices.priceMinor,compareAtMinor:prices.compareAtMinor,available:availableOf(raw),inventory:stockOf(raw),optionValues:[]}]}return{product:{source:"shopware",externalId,name,handle:slugify(name),descriptionHtml:translated(raw,"description"),vendor:nameOf(raw.manufacturer),categories:categoriesOf(raw),tags:(raw.tags??[]).map((tag)=>optionalString(tag?.name)).filter((tag)=>tag!==null),currency:context.currency,images:imagesOf(raw),optionNames,variants,hasOptions,url:`${context.storeUrl}/detail/${externalId}`},warnings}}export function shopwareBaseUrl(storeUrl){return normalizeStoreUrl(storeUrl).replace(/\/store-api$/i,"")}export function missingAccessKeyMessage(){return`Shopware's Store API needs the sales channel access key: pass --access-key <key> or set SHOPWARE_ACCESS_KEY. It is public by design and not a secret. ${SHOPWARE_ACCESS_KEY_HELP}`}function shopwareErrorDetail(body){if(!body)return null;try{const parsed=JSON.parse(body);const first=parsed?.errors?.[0];return optionalString(first?.detail)??optionalString(first?.title)}catch{return null}}function explain(error){const detail=shopwareErrorDetail(error.body);const said=detail?` Shopware said: "${detail}"`:"";if(error.status===401||error.status===403||error.status===412)return new CatalogFetchError(error.url,`${error.message}${said} The sales channel access key looks wrong: check --access-key or SHOPWARE_ACCESS_KEY. ${SHOPWARE_ACCESS_KEY_HELP}`,error.status,error.body);return new CatalogFetchError(error.url,`${error.message}${said} ${HINT}`,error.status,error.body)}async function storeApi(url,accessKey,fetcher,json){try{const{data}=await fetchJson(url,fetcher,"",{headers:{"sw-access-key":accessKey},json});return data}catch(error){if(!(error instanceof CatalogFetchError))throw error;throw explain(error)}}function isKeyError(error){return error instanceof CatalogFetchError&&(error.status===401||error.status===403||error.status===412)}export async function detectShopwareCurrency(base,accessKey,fetcher=fetch){try{const data=await storeApi(`${base}${API_PREFIX}/context`,accessKey,fetcher);const code=typeof data?.currency?.isoCode==="string"?data.currency.isoCode.trim().toUpperCase():"";return/^[A-Z]{3}$/.test(code)?code:null}catch(error){if(isKeyError(error))throw error;return null}}const INCLUDES={product:["id","parentId","productNumber","name","description","translated","calculatedPrice","stock","availableStock","available","active","childCount","manufacturer","seoCategory","categories","tags","cover","media","options"],calculated_price:["unitPrice","quantity","listPrice"],cart_list_price:["price"],product_media:["position","media"],media:["url","alt","title","translated"],product_manufacturer:["name","translated"],category:["name","translated"],tag:["name"],property_group_option:["id","name","translated","position","groupId","group"],property_group:["id","name","translated","position"]};export function shopwareProductCriteria(page,limit){return{page,limit,"total-count-mode":"exact",filter:[{type:"equals",field:"parentId",value:null}],sort:[{field:"id",order:"ASC"}],associations:{cover:{},media:{associations:{media:{}}},manufacturer:{},categories:{},tags:{}},includes:INCLUDES}}export function shopwareVariantCriteria(parentIds,page){return{page,limit:PAGE_SIZE,"total-count-mode":"exact",filter:[{type:"equalsAny",field:"parentId",value:parentIds}],sort:[{field:"id",order:"ASC"}],associations:{options:{associations:{group:{}}}},includes:INCLUDES}}function isLastPage(data,page,pageSize,received){if(received<pageSize)return true;const total=typeof data.total==="number"?data.total:Number.NaN;return Number.isInteger(total)&&page*pageSize>=total}async function fetchChildren(base,accessKey,parentIds,fetcher){const found=new Map;if(parentIds.length===0)return found;const url=`${base}${API_PREFIX}/product`;for(let page=1;page<=MAX_PAGES;page++){const data=await storeApi(url,accessKey,fetcher,shopwareVariantCriteria(parentIds,page));if(!Array.isArray(data?.elements))throw new CatalogFetchError(url,`${url} did not return a product list for the variants. ${HINT}`);const elements=data.elements;for(const child of elements){const parent=optionalString(child?.parentId);if(!parent)continue;const list=found.get(parent)??[];list.push(child);found.set(parent,list)}if(elements.length===0||isLastPage(data,page,PAGE_SIZE,elements.length))return found}throw new CatalogFetchError(url,`Stopped after ${MAX_PAGES} pages of variants from ${url} without reaching the end.`)}async function*shopwarePages(storeUrl,options={}){const accessKey=options.accessKey?.trim();if(!accessKey)throw new TypeError(missingAccessKeyMessage());const base=shopwareBaseUrl(storeUrl);const fetcher=options.fetch??fetch;const limit=options.limit;const pageSize=limit&&limit>0?Math.min(PAGE_SIZE,limit):PAGE_SIZE;const url=`${base}${API_PREFIX}/product`;const setupWarnings=[];const override=options.currency?.trim().toUpperCase()||null;const detected=await detectShopwareCurrency(base,accessKey,fetcher);const currency=detected??override;if(detected&&override&&detected!==override)setupWarnings.push({message:`--currency ${override} ignored: this sales channel prices in ${detected}, and the Store API does not convert.`});if(!currency)setupWarnings.push({message:`${base}${API_PREFIX}/context did not report a currency; prices read as 2-decimal amounts. Pass --currency to be sure.`});const seen=new Set;let emitted=0;for(let page=1;page<=MAX_PAGES;page++){const label=`${url} (page ${page})`;let data;try{data=await storeApi(url,accessKey,fetcher,shopwareProductCriteria(page,pageSize))}catch(error){if(error instanceof CatalogFetchError)throw new CatalogFetchError(error.url,error.message.replace(error.url,label),error.status,error.body);throw error}if(!Array.isArray(data?.elements))throw new CatalogFetchError(url,`${label} did not return a product list. ${HINT}`);const elements=data.elements;if(elements.length===0)return;const ids=elements.map((element)=>String(element?.id));if(page>1&&ids.every((id)=>seen.has(id)))throw new CatalogFetchError(url,`${label} repeated products from an earlier page; the store is not paginating. Use --limit to import the first page only.`);ids.forEach((id)=>seen.add(id));const take=limit?elements.slice(0,Math.max(0,limit-emitted)):elements;const warnings=page===1?setupWarnings:[];const parents=take.filter((item)=>typeof item?.childCount==="number"&&item.childCount>0).map((item)=>String(item.id));const children=await fetchChildren(base,accessKey,parents,fetcher);const products=[];for(const entry of take){try{const mapped=mapShopwareProduct(entry,{storeUrl:base,currency,children:children.get(String(entry?.id))});products.push(mapped.product);warnings.push(...mapped.warnings);emitted++}catch(error){warnings.push({externalId:entry?.id===undefined?undefined:String(entry.id),message:`skipped: ${error.message}`})}}yield{url:label,products,warnings};if(limit&&emitted>=limit)return;if(isLastPage(data,page,pageSize,elements.length))return}throw new CatalogFetchError(url,`Stopped after ${MAX_PAGES} pages of ${url} without reaching the end.`)}export const shopwareAdapter={name:"shopware",pages:shopwarePages};
|