top of page

import wixData from 'wix-data'; import { orders } from 'wix-ecom-backend'; import { fetch } from 'wix-fetch'; import { secrets } from 'wix-secrets-backend.v2'; import { elevate } from 'wix-auth'; import { processOrder } from 'backend/quantity'; const ledger = 'RazrInventoryReceipts'; const options = {suppressAuth:true}; const readOptions = {...options,consistentRead:true}; async function receipt(id) { return (await wixData.query(ledger).eq('_id',id).limit(1).find(readOptions)).items[0]; } const secret = async name => { const result = await elevate(secrets.getSecretValue)(name); return typeof result === 'string' ? result : result.value; }; async function servicesForOrder() { const config = await Promise.all(['CLIENT_ID','CLIENT_SECRET','REFRESH_TOKEN'].map(k=>secret('RAZR_ZOHO_'+k))); const form = new URLSearchParams({client_id:config[0],client_secret:config[1],refresh_token:config[2],grant_type:'refresh_token'}); const tokenResponse = await fetch('https://accounts.zoho.com/oauth/v2/token',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:form.toString()}); const token = await tokenResponse.json(); if (!tokenResponse.ok || !token.access_token) throw Error('Zoho authorization unavailable'); const request = async(path,method='GET',body)=>{ const url='https://www.zohoapis.com/inventory/v1/'+path+(path.includes('?')?'&':'?')+'organization_id=793142637'; const response=await fetch(url,{method,headers:{Authorization:'Zoho-oauthtoken '+token.access_token,'Content-Type':'application/json'},...(body?{body:JSON.stringify(body)}:{})}); const data=await response.json(); if (!response.ok || data.code!==0) throw Error('Zoho Inventory request failed ('+response.status+', '+data.code+')'); return data; }; return { recorded:receipt, findActiveItem:async sku=>{ const matches=[]; for(let page=1;;page++){ const data=await request('items?search_text='+encodeURIComponent(sku)+'&per_page=200&page='+page); matches.push(...data.items.filter(i=>i.sku===sku && i.status==='active')); if (!data.page_context?.has_more_page) break; } return matches.length===1 ? matches[0].item_id : null; }, claim:async(id,reference)=>{ try { await wixData.insert(ledger,{_id:id,reference,status:'posting'},options);return true; } catch(error){if(await receipt(id))return false;throw error;} }, finish:(id,reference,status,zohoId)=>wixData.update(ledger,{_id:id,reference,status,zohoId},options), post:async(reference,line_items)=>{ // A matching pre-existing reference also requires reconciliation, even without a Wix receipt. for(let page=1;;page++){ const data=await request('inventoryadjustments?per_page=200&page='+page); if(data.inventory_adjustments.some(a=>a.reference_number===reference))throw Error(reference+' already exists in Zoho'); if(!data.page_context?.has_more_page)break; } const date=new Intl.DateTimeFormat('sv-SE',{timeZone:'America/Chicago',year:'numeric',month:'2-digit',day:'2-digit'}).format(new Date()); const data=await request('inventoryadjustments','POST',{date,reason:'WIX retail sale',reference_number:reference,adjustment_type:'quantity',line_items}); const adj=data.inventory_adjustment; if(!adj?.inventory_adjustment_id)throw Error('Zoho adjustment needs verification'); return {id:adj.inventory_adjustment_id,status:adj.status==='adjusted'?'adjusted':'verify_in_zoho'}; } }; } async function handle(event) { const start=await receipt('activation'); if(!start || start.status!=='enabled')return; const orderId=event.metadata.entityId; if(!orderId || await receipt(orderId))return; const order=await elevate(orders.getOrder)(orderId); if(order.status!=='APPROVED'||order.paymentStatus!=='PAID'||new Date(order._createdDate??order.createdDate)<new Date(start._createdDate))return; try { await processOrder(order,new Date(start._createdDate).toISOString(),await servicesForOrder()); } catch (error) { const issue=String(error.message || error); if (!issue.includes(': review SKU ') && !issue.includes(': invalid order line')) throw error; try { await wixData.insert(ledger,{_id:orderId,reference:'WIX-'+order.number,status:issue},options); } catch(recordError) { if (!await receipt(orderId)) throw recordError; } } } export async function wixEcom_onOrderApproved(event){return handle(event);} export async function wixEcom_onOrderPaymentStatusUpdated(event){return handle(event);}

TRUSTED BY ICE ANGLERS EVERYWHERE

Manufacturing ice augers for more than 30 years.

​

​

bottom of page