PageSourceSearch

https://getstoked.web.app/_next/static/chunks/0bjcejwf95ul~.js

js getstoked.web.app collected 2026-10-03 12:25:55 UTC 29,926 bytes, 1 lines download raw bytes

1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,297185,e=>{"use strict";var t=e.i(824004),a=e.i(576014),i=e.i(333310),n=e.i(4927),o=e.i(189824),r=e.i(304669),l=e.i(227489),u=e.i(742397),s=e.i(353533);let d=e=>"string"==typeof e&&e.trim().length>0;async function c(e,a){let c;if(e.materialProductRef)return e.materialProductRef.id;if(e.bundleRef){let t=await n.materialBundleService.getBundleForMaterial(e.id,e.getLocation());if(t&&t.primaryMaterialRef.path!==e.docRef.path)return null}if(d(e.brand)&&d(e.model))return(await o.materialProductService.createProductFromMaterialRefs(e.brand,e.model,e.type,[e.docRef],{status:"draft",isActive:!1,autoCreatedFromInventorySale:!0,createdBy:a})).productId;let m=`material-${e.id}`,y=await i.default.getByProductKey(m);c=y?y.id:await i.default.create({productKey:m,slug:m,brand:e.brand??"",model:d(e.model)?e.model:e.id,year:e.year,type:e.type,materialType:e.materialType,priceFrom:e.salesPrice>0?e.salesPrice:void 0,priceTo:e.salesPrice>0?e.salesPrice:void 0,msrp:e.listPrice>0?e.listPrice:void 0,availableSizes:d(e.size)?[e.size]:[],availableConditions:e.condition?[e.condition]:[],totalAvailable:1,images:e.images??[],status:"draft",isActive:!1,isFeatured:!1,autoCreatedFromInventorySale:!0,createdBy:a});let S=await (0,s.getDocRef)(u.COLLECTIONS.MATERIAL_PRODUCTS,c,l.SHOP_GLOBAL_LOCATION_ID);return await t.default.updateMaterial({shopStatus:r.MaterialShopStatus.Linked,materialProductRef:S},e.id,e.getLocation()),c}async function m(e,t){let a=new Map;for(let i of e)try{let e=await c(i,t);e&&a.set(i.id,e)}catch(e){console.error(`[InventorySaleArticle] Failed to ensure shop article for material ${i.id}:`,e)}return a}var y=e.i(707720),S=e.i(427757);e.i(581516);var I=e.i(310339),p=e.i(492025),f=e.i(207742),D=e.i(581356),w=e.i(615351),v=e.i(337153),T=e.i(125765),E=e.i(808984),P=e.i(448042),b=e.i(182257);class g extends b.BaseInvoiceService{buildFulfillmentProps(e){return e.fulfillmentMethod?{fulfillmentMethod:e.fulfillmentMethod,fulfillmentLocationId:e.fulfillmentLocationId,fulfillmentLocationName:e.fulfillmentLocationName}:{}}async createQuote(e,t,i,n){let o,r=await y.invoiceNumberService.generateInvoiceNumber(y.InvoiceCircle.QUOTE,void 0,n.locationId),l=n.vatRate??await this.resolveVatRate(),u=await (0,b.getCompanyDetails)(),s=(0,b.getCustomerDetails)(t),d=this.buildDocumentItems(e,n.sellingPrices,l,n.bundleLabels,n.priceInputMode),c=this.calculateTotals(d),m=n.validUntil?I.Timestamp.fromDate(n.validUntil):I.Timestamp.fromDate(new Date(Date.now()+2592e6)),S={documentNumber:r,documentType:P.SalesDocumentType.QUOTE,status:P.SalesDocumentStatus.ISSUED,sellerId:i.id,sellerName:`${i.firstName} ${i.lastName}`,buyerId:t.id,buyerName:s.name,buyer:s,company:u,items:d,...c,currency:n.currency||"EUR",materialIds:e.map(e=>e.id),bundleData:this.extractBundleData(e,n.bundleLabels),...this.buildFulfillmentProps(n),validUntil:m,language:n.language,notes:n.notes,createdAt:I.Timestamp.now(),createdBy:n.createdBy},p=await a.default.create(S),f=await a.default.getById(p);return await this.updateMaterialsSalesStatus(e,P.MaterialSalesStatus.QUOTED,p),n.createLinkedPayment&&(await this.createLinkedPayment(p,f.total,t,i,n.paymentMethod||E.PaymentTypes.Request,n.currency||"EUR",f.documentType,f.documentNumber,n.locationId),f=await a.default.getById(p)),!1!==n.generatePdf&&(o=await this.generateDocumentPdf(f)),{document:f,pdfUrl:o}}async createOrder(e,t,i,n){let o,r=await y.invoiceNumberService.generateInvoiceNumber(y.InvoiceCircle.ORDER,void 0,n.locationId),l=n.vatRate??await this.resolveVatRate(),u=await (0,b.getCompanyDetails)(),s=(0,b.getCustomerDetails)(t),d=this.buildDocumentItems(e,n.sellingPrices,l,n.bundleLabels,n.priceInputMode),c=this.calculateTotals(d),m={documentNumber:r,documentType:P.SalesDocumentType.ORDER,status:P.SalesDocumentStatus.ISSUED,sellerId:i.id,sellerName:`${i.firstName} ${i.lastName}`,buyerId:t.id,buyerName:s.name,buyer:s,company:u,items:d,...c,currency:n.currency||"EUR",materialIds:e.map(e=>e.id),bundleData:this.extractBundleData(e,n.bundleLabels),...this.buildFulfillmentProps(n),paymentMethod:n.paymentMethod,language:n.language,notes:n.notes,createdAt:I.Timestamp.now(),createdBy:n.createdBy},S=await a.default.create(m),p=await a.default.getById(S);return await this.updateMaterialsSalesStatus(e,P.MaterialSalesStatus.ORDERED,S),n.createLinkedPayment&&(await this.createLinkedPayment(S,p.total,t,i,n.paymentMethod||E.PaymentTypes.Request,n.currency||"EUR",p.documentType,p.documentNumber,n.locationId),p=await a.default.getById(S)),!1!==n.generatePdf&&(o=await this.generateDocumentPdf(p)),{document:p,pdfUrl:o}}async createSale(e,t,a,i){return this.completeSaleWithInvoice(e,t,a,i,{documentType:P.SalesDocumentType.SALE,circle:y.InvoiceCircle.SHOP,pdfDocumentType:"invoice",allowCustomNumber:!0})}async createReceipt(e,t,a,i){return this.completeSaleWithInvoice(e,t,a,{...i,paymentStatus:i.paymentStatus??E.PaymentStatusTypes.Paid},{documentType:P.SalesDocumentType.RECEIPT,circle:y.InvoiceCircle.RECEIPT,pdfDocumentType:"receipt",allowCustomNumber:!1})}async createDirectSale(e,t,i,n){await m(e,n.createdBy);let o=n.vatRate??await this.resolveVatRate(),r=await (0,b.getCompanyDetails)(),l=(0,b.getCustomerDetails)(t),u=this.buildDocumentItems(e,n.sellingPrices,o,n.bundleLabels,n.priceInputMode),s=this.calculateTotals(u),d=await y.invoiceNumberService.generateInvoiceNumber(y.InvoiceCircle.INTERNAL_SALE,void 0,n.locationId),c={documentNumber:d,documentType:P.SalesDocumentType.DIRECT_SALE,status:P.SalesDocumentStatus.CONVERTED,paymentStatus:n.paymentStatus??E.PaymentStatusTypes.Paid,sellerId:i.id,sellerName:`${i.firstName} ${i.lastName}`,buyerId:t.id,buyerName:l.name,buyer:l,company:r,items:u,...s,currency:n.currency||"EUR",materialIds:e.map(e=>e.id),bundleData:this.extractBundleData(e,n.bundleLabels),...this.buildFulfillmentProps(n),paymentMethod:n.paymentMethod,language:n.language,notes:n.notes,createdAt:I.Timestamp.now(),createdBy:n.createdBy},S=await a.default.create(c);return n.paymentMethod&&await this.createLinkedPayment(S,s.total,t,i,n.paymentMethod,n.currency||"EUR",P.SalesDocumentType.DIRECT_SALE,d,n.locationId,n.paymentStatus??E.PaymentStatusTypes.Paid),await this.markMaterialsSold(e,t,i,n,S),{document:await a.default.getById(S)}}async completeSaleWithInvoice(e,t,i,n,o){let r;await m(e,n.createdBy);let l=n.vatRate??await this.resolveVatRate(),u=await (0,b.getCompanyDetails)(),s=(0,b.getCustomerDetails)(t),d=this.buildDocumentItems(e,n.sellingPrices,l,n.bundleLabels,n.priceInputMode),c=this.calculateTotals(d),S="customInvoiceNumber"in n?n.customInvoiceNumber?.trim():void 0,p=o.allowCustomNumber&&!!S,f=p?S:await y.invoiceNumberService.generateInvoiceNumber(o.circle,void 0,n.locationId),D=n.paymentStatus===E.PaymentStatusTypes.Paid,w=I.Timestamp.now(),v={documentNumber:f,documentType:o.documentType,status:P.SalesDocumentStatus.CONVERTED,sellerId:i.id,sellerName:`${i.firstName} ${i.lastName}`,buyerId:t.id,buyerName:s.name,buyer:s,company:u,items:d,...c,currency:n.currency||"EUR",materialIds:e.map(e=>e.id),bundleData:this.extractBundleData(e,n.bundleLabels),...this.buildFulfillmentProps(n),invoiceId:f,invoiceNumber:f,paymentMethod:n.paymentMethod,paymentStatus:n.paymentStatus??E.PaymentStatusTypes.Open,language:n.language,notes:n.notes,createdAt:w,createdBy:n.createdBy},g="sourceDocumentId"in n?n.sourceDocumentId:void 0;if(g){let e=await a.default.getById(g);e&&(v.sourceDocumentId=e.id,v.sourceDocumentType=e.documentType,v.sourceDocumentNumber=e.documentNumber)}let h=await a.default.create(v),N=d.map(e=>(0,T.createInvoiceItem)({description:e.bundleLabel?`[${e.bundleLabel}] ${e.description}`:e.description,quantity:e.quantity,unitPrice:e.unitPrice,vatRate:e.vatRate,category:"other",referenceId:e.materialId,referenceType:"material"})),C=(0,T.calculateInvoiceTotalsWithBreakdown)(N),L={invoiceNumber:f,invoiceCircle:o.circle,date:w,company:u,customer:s,items:N,subtotal:C.subtotal,vatRate:C.primaryVatRate,vatAmount:C.vatAmou
1nt,total:C.total,vatBreakdown:C.vatBreakdown,currency:n.currency||"EUR",status:D?T.PaymentInvoiceStatus.PAID:T.PaymentInvoiceStatus.ISSUED,notes:n.notes,createdBy:n.createdBy,createdAt:w,isCustomInvoiceNumber:p,sellerName:`${i.firstName} ${i.lastName}`,sellerId:i.id,locationId:n.locationId,...D?{paidAt:w,paymentDate:w}:{}},A=new T.PaymentInvoice(f,L);if(await this.saveInvoice(A,t.id,n.locationId),await a.default.update(h,{invoiceId:A.id,invoiceNumber:A.invoiceNumber}),await this.markMaterialsSold(e,t,i,n,h),!1!==n.generatePdf)try{let e=await this.generateAndStorePdf(A,{language:n.language,documentType:o.pdfDocumentType});r=e.pdfUrl,await this.updateInvoicePdfUrl(A.id,e.pdfUrl,e.storagePath,n.locationId)}catch(e){console.error("Error generating sale PDF:",e)}return{document:await a.default.getById(h),invoice:A,pdfUrl:r}}async markMaterialsSold(e,a,i,n,o){for(let r of(await this.updateMaterialsSalesStatus(e,P.MaterialSalesStatus.SOLD,o),e))await t.default.updateMaterial({archived:!0,soldBy:i.id,soledTo:a.id,soldAt:I.Timestamp.now(),soldPrice:n.sellingPrices[r.id]??r.salesPrice},r.id)}async convertQuoteToOrder(e,i,n){let o=await a.default.getById(e);if(!o)throw Error("Quote not found");if(!o.isQuote())throw Error("Document is not a quote");if(!o.canConvert())throw Error("Quote cannot be converted");let r=await y.invoiceNumberService.generateInvoiceNumber(y.InvoiceCircle.ORDER,void 0,n),l={documentNumber:r,documentType:P.SalesDocumentType.ORDER,status:P.SalesDocumentStatus.ISSUED,sellerId:o.sellerId,sellerName:o.sellerName,buyerId:o.buyerId,buyerName:o.buyerName,buyer:o.buyer,company:o.company,items:o.items,subtotal:o.subtotal,vatRate:o.vatRate,vatAmount:o.vatAmount,total:o.total,vatBreakdown:o.vatBreakdown,currency:o.currency,materialIds:o.materialIds,bundleData:o.bundleData,fulfillmentMethod:o.fulfillmentMethod,fulfillmentLocationId:o.fulfillmentLocationId,fulfillmentLocationName:o.fulfillmentLocationName,sourceDocumentId:o.id,sourceDocumentType:P.SalesDocumentType.QUOTE,sourceDocumentNumber:o.documentNumber,linkedPaymentId:o.linkedPaymentId,linkedPaymentStatus:o.linkedPaymentStatus,paymentMethod:o.paymentMethod,language:o.language,notes:o.notes,createdAt:I.Timestamp.now(),createdBy:i},d=await a.default.create(l);await a.default.update(e,{status:P.SalesDocumentStatus.CONVERTED,convertedToId:d,convertedToType:P.SalesDocumentType.ORDER,convertedToNumber:r,updatedBy:i});let c=await (0,s.getDocRef)(u.COLLECTIONS.SALES_DOCUMENTS,d);for(let e of o.materialIds)await t.default.updateMaterial({salesStatus:P.MaterialSalesStatus.ORDERED,salesDocumentRef:c},e);return await a.default.getById(d)}async convertOrderToSale(e,i,n){let o,r=await a.default.getById(e);if(!r)throw Error("Order not found");if(!r.isOrder())throw Error("Document is not an order");if(!r.canConvert())throw Error("Order cannot be converted");r.vatRate;let l=!!n.customInvoiceNumber?.trim(),d=l?n.customInvoiceNumber.trim():await y.invoiceNumberService.generateInvoiceNumber(y.InvoiceCircle.SHOP,void 0,n.locationId),c=r.items.map(e=>(0,T.createInvoiceItem)({description:e.bundleLabel?`[${e.bundleLabel}] ${e.description}`:e.description,quantity:e.quantity,unitPrice:e.unitPrice,vatRate:e.vatRate,category:"other",referenceId:e.materialId,referenceType:"material"})),m=(0,T.calculateInvoiceTotalsWithBreakdown)(c),S=await (0,b.getCompanyDetails)(),p=I.Timestamp.now(),D={invoiceNumber:d,invoiceCircle:y.InvoiceCircle.SHOP,date:p,company:S,customer:r.buyer,items:c,subtotal:m.subtotal,vatRate:m.primaryVatRate,vatAmount:m.vatAmount,total:m.total,vatBreakdown:m.vatBreakdown,currency:r.currency,status:n.markAsPaid?T.PaymentInvoiceStatus.PAID:T.PaymentInvoiceStatus.ISSUED,notes:r.notes,createdBy:i,createdAt:p,isCustomInvoiceNumber:l,sellerName:r.sellerName,sellerId:r.sellerId,locationId:n.locationId,...n.markAsPaid?{paidAt:p,paymentDate:p}:{}},v=new T.PaymentInvoice(d,D);await this.saveInvoice(v,r.buyerId,n.locationId);let g={documentNumber:d,documentType:P.SalesDocumentType.SALE,status:P.SalesDocumentStatus.CONVERTED,sellerId:r.sellerId,sellerName:r.sellerName,buyerId:r.buyerId,buyerName:r.buyerName,buyer:r.buyer,company:S,items:r.items,subtotal:r.subtotal,vatRate:r.vatRate,vatAmount:r.vatAmount,total:r.total,vatBreakdown:r.vatBreakdown,currency:r.currency,materialIds:r.materialIds,bundleData:r.bundleData,fulfillmentMethod:r.fulfillmentMethod,fulfillmentLocationId:r.fulfillmentLocationId,fulfillmentLocationName:r.fulfillmentLocationName,sourceDocumentId:r.id,sourceDocumentType:P.SalesDocumentType.ORDER,sourceDocumentNumber:r.documentNumber,invoiceId:v.id,invoiceNumber:v.invoiceNumber,paymentMethod:n.paymentMethod,paymentStatus:n.markAsPaid?E.PaymentStatusTypes.Paid:E.PaymentStatusTypes.Open,language:n.language||r.language,notes:r.notes,createdAt:I.Timestamp.now(),createdBy:i},h=await a.default.create(g);await a.default.update(e,{status:P.SalesDocumentStatus.CONVERTED,convertedToId:h,c
1onvertedToType:P.SalesDocumentType.SALE,convertedToNumber:d,invoiceId:v.id,invoiceNumber:v.invoiceNumber,updatedBy:i});let N=r.linkedPaymentId?await (0,f.getDoc)((0,w.doc)(await (0,s.getCollection)(u.COLLECTIONS.PAYMENTS,n.locationId),r.linkedPaymentId)):null;if(r.linkedPaymentId&&N?.exists()){let e=N.data()?.status===E.PaymentStatusTypes.Paid;await (0,f.updateDoc)(N.ref,{salesDocumentId:h,salesDocumentType:P.SalesDocumentType.SALE,salesDocumentNumber:d,invoiceId:v.id,...n.markAsPaid&&!e?{status:E.PaymentStatusTypes.Paid,paidAt:I.Timestamp.now()}:{}});let t=e||n.markAsPaid?E.PaymentStatusTypes.Paid:r.linkedPaymentStatus??E.PaymentStatusTypes.Open;await a.default.update(h,{linkedPaymentId:r.linkedPaymentId,linkedPaymentStatus:t,paymentStatus:t}),o={id:r.linkedPaymentId,created:!1,previousStatus:r.linkedPaymentStatus}}else o={id:await this.createLinkedPayment(h,r.total,{id:r.buyerId},{id:r.sellerId},n.paymentMethod,r.currency,P.SalesDocumentType.SALE,d,n.locationId,n.markAsPaid?E.PaymentStatusTypes.Paid:E.PaymentStatusTypes.Open,v.id),created:!0};for(let e of r.materialIds)await t.default.updateMaterial({salesStatus:P.MaterialSalesStatus.SOLD,archived:!0,soldBy:r.sellerId,soledTo:r.buyerId,soldAt:I.Timestamp.now()},e);try{let e=await this.generateAndStorePdf(v,{language:n.language||r.language});await this.updateInvoicePdfUrl(v.id,e.pdfUrl,e.storagePath,n.locationId)}catch(e){console.error("Error generating conversion PDF:",e)}return{document:await a.default.getById(h),invoice:v,linkedPayment:o}}async finalizeToSale(e,t,i){let n,o,r=await a.default.getById(e);if(!r)throw Error("Sales document not found");if(!r.isQuote()&&!r.isOrder())throw Error("Only quotes and orders can be completed as a sale");if(!r.canConvert())throw Error("Document cannot be converted");let l=r.status,u=e;if(r.isQuote()){let a=await this.convertQuoteToOrder(e,t,i.locationId);u=a.id,n=a.id,o=a.documentNumber}let{document:s,invoice:d,linkedPayment:c}=await this.convertOrderToSale(u,t,i);return{invoice:d,conversion:{saleDocumentId:s.id,saleInvoiceId:d.id,saleInvoiceNumber:d.invoiceNumber,buyerId:r.buyerId,sourceDocumentId:e,sourceDocumentType:r.isQuote()?P.SalesDocumentType.QUOTE:P.SalesDocumentType.ORDER,sourceDocumentNumber:r.documentNumber,previousStatus:l,materialIds:r.materialIds,intermediateOrderId:n,intermediateOrderNumber:o,paymentId:c?.id,paymentCreated:c?.created,previousPaymentStatus:c?.previousStatus,convertedAtIso:new Date().toISOString()}}}async undoSaleConversion(e,t){let i,{saleDocumentId:n,saleInvoiceId:o,saleInvoiceNumber:r,buyerId:l,sourceDocumentId:d,sourceDocumentType:c,sourceDocumentNumber:m,previousStatus:S,materialIds:I,intermediateOrderId:b,intermediateOrderNumber:g,paymentId:h,paymentCreated:N,previousPaymentStatus:C}=e,L=await (0,s.getDocRef)(u.COLLECTIONS.SALES_DOCUMENTS,d);if(!(await (0,f.getDoc)(L)).exists())throw Error("Source document no longer exists — cannot undo");await (0,f.updateDoc)(L,{status:S,convertedToId:(0,D.deleteField)(),convertedToType:(0,D.deleteField)(),convertedToNumber:(0,D.deleteField)(),invoiceId:(0,D.deleteField)(),invoiceNumber:(0,D.deleteField)()});let A=c===P.SalesDocumentType.QUOTE?P.MaterialSalesStatus.QUOTED:P.MaterialSalesStatus.ORDERED;for(let e of I){let a=await (0,s.getDocRef)(u.COLLECTIONS.MATERIAL,e,t);await (0,f.updateDoc)(a,{archived:!1,salesStatus:A,salesDocumentRef:L,soldBy:(0,D.deleteField)(),soledTo:(0,D.deleteField)(),soldAt:(0,D.deleteField)(),soldPrice:(0,D.deleteField)()})}if(h){let e=await (0,s.getDocRef)(u.COLLECTIONS.PAYMENTS,h,t);(await (0,f.getDoc)(e)).exists()&&(N?await (0,f.deleteDoc)(e):await (0,f.updateDoc)(e,{salesDocumentId:d,salesDocumentType:c,salesDocumentNumber:m,invoiceId:(0,D.deleteField)(),status:C??E.PaymentStatusTypes.Open,...C!==E.PaymentStatusTypes.Paid?{paidAt:(0,D.deleteField)()}:{}}))}await a.default.getById(n)&&(await a.default.update(n,{status:P.SalesDocumentStatus.CANCELLED}),await a.default.delete(n)),b&&await a.default.getById(b)&&await a.default.delete(b);let R=await (0,s.getDocRef)(u.COLLECTIONS.PAYMENT_INVOICES,o,t),O=await (0,f.getDoc)(R);O.exists()&&(i=T.PaymentInvoice.fromFirestore(O)?.numberAllocation,await (0,f.deleteDoc)(R));try{let e=(0,p.collection)(R,u.COLLECTIONS.PAYMENT_INVOICE_CHANGE_LOG),t=await (0,f.getDocs)(e);await Promise.all(t.docs.map(e=>(0,f.deleteDoc)(e.ref)))}catch(e){console.error("[undoSaleConversion] Failed to purge changeLog:",e)}try{let e=(0,w.doc)(v.db,u.COLLECTIONS.USER_METADATA.PUBLIC,l,u.COLLECTIONS.USER_METADATA.PAYMENT_INVOICES,o);(await (0,f.getDoc)(e)).exists()&&await (0,f.deleteDoc)(e)}catch(e){console.error("[undoSaleConversion] Failed to delete user mirror:",e)}if(await y.invoiceNumberService.releaseInvoiceNumber(r,{locationId:t,releaseMarkerKey:`undo-sale:${o}:${r}`,allocation:i}),b&&g)try{await y.invoiceNumberService.releaseInvoiceNumber(g,{locationId:t,releaseMarkerKey:`undo-sale:${b}:${g}`})}catch(e){console.error("[undoSaleConversion] Failed to release order number:",e)}}async sendSalePaymentLink(t,i={}){let n=await a.default.getById(t,i.locationId);if(!n)throw Error("Sales document not found");if(!n.buyerId)throw Error("Sales document has no buyer");let o=n.linkedPaymentId;o||(o=await this.createLinkedPayment(t,n.total,{id:n.buyerId},{id:n.sellerId},n.paymentMethod??E.PaymentTypes.Mollie,n.currency,n.documentType,n.documentNumber,i.locationId,E.PaymentStatusTypes.Open,n.invoiceId));let r=i.locationId??await (0,s.getLocation)();if(!r)return{success:!1,error:"missing-location"};let{sendStandalonePaymentNotification:l}=await e.A(643138),d=await l(n.buyerId,n.total,"mollie",r,n.invoiceNumber??n.documentNumber,o,i.language??n.language);if(!d.success||!d.paymentUrl)return{success:!1,error:d.error??"Payment link creation failed"};if(n.invoiceId){let e={paymentLinkUrl:d.paymentUrl,updatedAt:I.Timestamp.now()};try{let t=await (0,s.getDocRef)(u.COLLECTIONS.PAYMENT_INVOICES,n.invoiceId,i.locationId);await (0,f.updateDoc)(t,e);let a=(0,w.doc)(v.db,u.COLLECTIONS.USER_METADATA.PUBLIC,n.buyerId,u.COLLECTIONS.USER_METADATA.PAYMENT_INVOICES,n.invoiceId);(await (0,f.getDoc)(a)).exists()&&await (0,f.updateDoc)(a,e)}catch(e){console.error("[sendSalePaymentLink] Failed to persist link on invoice:",e)}}return{success:!0,paymentUrl:d.paymentUrl}}
1async acceptQuote(e,t){let i=await a.default.getById(e);if(!i)throw Error("Quote not found");if(!i.isQuote())throw Error("Document is not a quote");await a.default.update(e,{status:P.SalesDocumentStatus.ACCEPTED,updatedBy:t})}async declineQuote(e,t){let i=await a.default.getById(e);if(!i)throw Error("Quote not found");if(!i.isQuote())throw Error("Document is not a quote");await a.default.update(e,{status:P.SalesDocumentStatus.DECLINED,updatedBy:t}),await this.resetMaterialsSalesStatus(i.materialIds)}async updateDocumentNumber(e,t,i,n){let o=t.trim();if(!o)throw Error("Document number cannot be empty");let r=await a.default.getById(e);if(!r)throw Error("Sales document not found");let l=await a.default.getByDocumentNumber(o);if(l&&l.id!==e)throw Error(`Document number ${o} already exists`);let u=await this.getInvoiceByInvoiceNumber(o,{locationId:n});if(u&&u.id!==e)throw Error(`Invoice number ${o} already exists`);await a.default.update(e,{documentNumber:o,updatedBy:i}),await this.updateLinkedPaymentForDocument(r,{salesDocumentNumber:o,note:this.buildLinkedPaymentNote(r,o)},n);let s=await a.default.getById(e);s&&await this.generateDocumentPdf(s)}async updateDocumentDate(e,t,i){if(!await a.default.getById(e))throw Error("Sales document not found");await a.default.update(e,{createdAt:t,updatedBy:i});let n=await a.default.getById(e);n&&await this.generateDocumentPdf(n)}async updateDocumentCustomer(e,t,i){if(!await a.default.getById(e))throw Error("Sales document not found");await a.default.update(e,{buyer:t,buyerId:t.id,buyerName:t.name,updatedBy:i});let n=await a.default.getById(e);n&&await this.generateDocumentPdf(n)}async updateDocumentItems(e,t,i,n,o){let r=await a.default.getById(e);if(!r)throw Error("Sales document not found");let l=this.buildSalesDocumentItemsFromInvoiceItems(t,r.items),u=(0,T.calculateInvoiceTotalsWithBreakdown)(t);await a.default.update(e,{items:l,subtotal:u.subtotal,vatRate:u.primaryVatRate,vatAmount:u.vatAmount,total:u.total,vatBreakdown:u.vatBreakdown,notes:n?.notes,updatedBy:i}),await this.updateLinkedPaymentForDocument(r,{amount:u.total},o);let s=await a.default.getById(e);s&&await this.generateDocumentPdf(s)}async cancelDocument(e,t,i){let n=await a.default.getById(e);if(!n)throw Error("Document not found");if(!n.canCancel())throw Error("Document cannot be cancelled");await a.default.update(e,{status:P.SalesDocumentStatus.CANCELLED,updatedBy:t}),await this.updateLinkedPaymentForDocument(n,{status:E.PaymentStatusTypes.Canceled},i),n.linkedPaymentId&&await a.default.update(e,{linkedPaymentStatus:E.PaymentStatusTypes.Canceled,updatedBy:t}),await this.resetMaterialsSalesStatus(n.materialIds,i)}async undoDocument(e,t){let i=await a.default.getById(e);if(!i)throw Error("Sales document not found");return await this.resetMaterialsSalesStatus(i.materialIds,t),i.linkedPaymentId&&await this.updateLinkedPaymentForDocument(i,{status:E.PaymentStatusTypes.Canceled},t),await a.default.delete(e),i}async updateDocumentStatus(e,t,i,n){let o=await a.default.getById(e);if(!o)throw Error("Sales document not found");if(o.isFinalSale())throw Error("Completed sales cannot change status from the document UI — 
1cancel via the invoice flow");let r=this.mapInvoiceStatusToDocumentStatus(t);if(!r)throw Error(`Unsupported status for sales document: ${t}`);if(r===o.status)return;let l=o.status;if(await a.default.update(e,{status:r,updatedBy:i}),r===P.SalesDocumentStatus.CANCELLED?(await this.updateLinkedPaymentForDocument(o,{status:E.PaymentStatusTypes.Canceled},n),o.linkedPaymentId&&await a.default.update(e,{linkedPaymentStatus:E.PaymentStatusTypes.Canceled,updatedBy:i})):l===P.SalesDocumentStatus.CANCELLED&&(r===P.SalesDocumentStatus.ISSUED||r===P.SalesDocumentStatus.DRAFT)&&(await this.updateLinkedPaymentForDocument(o,{status:E.PaymentStatusTypes.Open},n),o.linkedPaymentId&&await a.default.update(e,{linkedPaymentStatus:E.PaymentStatusTypes.Open,updatedBy:i})),[P.SalesDocumentStatus.CANCELLED,P.SalesDocumentStatus.DECLINED,P.SalesDocumentStatus.EXPIRED,P.SalesDocumentStatus.DRAFT].includes(r))await this.resetMaterialsSalesStatus(o.materialIds,n);else if(r===P.SalesDocumentStatus.ISSUED){let t=o.isQuote()?P.MaterialSalesStatus.QUOTED:P.MaterialSalesStatus.ORDERED,a=await (0,s.getDocRef)(u.COLLECTIONS.SALES_DOCUMENTS,e);for(let e of o.materialIds){let i=await (0,s.getDocRef)(u.COLLECTIONS.MATERIAL,e,n);await (0,f.updateDoc)(i,{salesStatus:t,salesDocumentRef:a})}}let d=await a.default.getById(e);d&&await this.generateDocumentPdf(d)}mapInvoiceStatusToDocumentStatus(e){switch(e){case T.PaymentInvoiceStatus.DRAFT:return P.SalesDocumentStatus.DRAFT;case T.PaymentInvoiceStatus.ISSUED:return P.SalesDocumentStatus.ISSUED;case T.PaymentInvoiceStatus.CANCELLED:return P.SalesDocumentStatus.CANCELLED;default:return}}async cancelSaleInvoice(e,t,i){await this.cancelInvoice(e,t,i);let n=(await a.default.getAllByInvoiceId(e)).find(e=>e.isSale()||e.isReceipt());n&&(await a.default.update(n.id,{status:P.SalesDocumentStatus.CANCELLED,updatedBy:t}),await this.resetSoldMaterials(n.materialIds,i))}async checkExpiredQuotes(){for(let e of(await a.default.getByType(P.SalesDocumentType.QUOTE)).filter(e=>e.status===P.SalesDocumentStatus.ISSUED||e.status===P.SalesDocumentStatus.ACCEPTED))e.isExpired()&&(await a.default.update(e.id,{status:P.SalesDocumentStatus.EXPIRED}),await this.resetMaterialsSalesStatus(e.materialIds))}async getDocumentsForMaterial(e){return a.default.getByMaterialId(e)}async getDocumentChain(e){return a.default.getDocumentChain(e)}async getBusinessCaseHistory(e,t){if(t)return a.default.getDocumentChain(e);let i=await a.default.getByInvoiceId(e);return i?a.default.getDocumentChain(i.id):[]}async getActiveDocuments(){let[e,t,i]=await Promise.all([a.default.getByStatus(P.SalesDocumentStatus.DRAFT),a.default.getByStatus(P.SalesDocumentStatus.ISSUED),a.default.getByStatus(P.SalesDocumentStatus.ACCEPTED)]);return[...e,...t,...i]}async getActiveDocumentForMaterial(e){return a.default.getActiveForMaterial(e)}async createLinkedPayment(e,t,a,i,n,o,r,l,d,c=E.PaymentStatusTypes.Open,m){let y=await (0,s.getCollection)(u.COLLECTIONS.PAYMENTS,d),S=(0,w.doc)(y),p=await (0,s.getDocRef)(u.COLLECTIONS.USER_METADATA.PUBLIC,a.id),D=await (0,s.getDocRef)(u.COLLECTIONS.USER_METADATA.PUBLIC,i.id),v=r?r.charAt(0).toUpperCase()+r.slice(1):"Document",T=l?`Linked to ${v} ${l}`:`Linked to ${v} ${e}`,P=c===E.PaymentStatusTypes.Paid;await (0,f.setDoc)(S,{id:S.id,amount:t,date:I.Timestamp.now(),paymentType:n,status:c,mainCategory:E.PaymentMainCategory.Income,processingStatus:E.PaymentProcessingStatus.Open,currency:o,registeredBy:D,paidBy:p,check:!1,note:T,bookingId:null,salesDocumentId:e,...r&&{salesDocumentType:r},...l&&{salesDocumentNumber:l},...m&&{invoiceId:m},...P&&{paidAt:I.Timestamp.now()}});let b=await (0,s.getDocRef)(u.COLLECTIONS.SALES_DOCUMENTS,e,d);return await (0,f.updateDoc)(b,{linkedPaymentId:S.id,linkedPaymentStatus:c}),S.id}async markPaymentPaidAndConvert(e,t,i){let n=await a.default.getById(e);if(!n)throw Error("Sales document not found");if(!n.linkedPaymentId)throw Error("No linked payment on this document");let o=await (0,s.getCollection)(u.COLLECTIONS.PAYMENTS,i.locationId),r=(0,w.doc)(o,n.linkedPaymentId);if(!(await (0,f.getDoc)(r)).exists())throw Error("Linked payment not found");await (0,f.updateDoc)(r,{status:E.PaymentStatusTypes.Paid,paidAt:I.Timestamp.now()}),await a.default.update(e,{linkedPaymentStatus:E.PaymentStatusTypes.Paid});let l={...i,markAsPaid:!0};if(n.isQuote()){let a=await this.convertQuoteToOrder(e,t,i.locationId);return this.convertOrderToSale(a.id,t,l)}return this.convertOrderToSale(e,t,l)}buildLinkedPaymentNote(e,t){let a=e.documentType?e.documentType.charAt(0).toUpperCase()+e.documentType.slice(1):"Document";return`Linked to ${a} ${t}`}async updateLinkedPaymentForDocument(e,t,a){if(!e.linkedPaymentId)return;let i=await (0,s.getCollection)(u.COLLECTIONS.PAYMENTS,a),n=(0,w.doc)(i,e.linkedPaymentId);await (0,f.updateDoc)(n,t)}async resetSoldMaterials(e,t){for(let a of e){let e=await (0,s.getDocRef)(u.COLLECTIONS.MATERIAL,a,t);await (0,f.updateDoc)(e,{archived:!1,salesStatus:P.MaterialSalesStatus.AVAILABLE,salesDocumentRef:(0,D.deleteField)(),soldBy:(0,D.deleteField)(),soledTo:(0,D.deleteField)(),soldAt:(0,D.deleteField)(),soldPrice:(0,D.deleteField)()})}}async resolveVatRate(){return S.taxConfigService.resolveVatRate({circle:y.InvoiceCircle.SHOP,isShopItem:!0})}buildDocumentItems(e,t,a,i,n="net"){return e.map(e=>{let o=t[e.id]??e.salesPrice,r=o,l=o,u=a/100*l,s=l+u;"gross"===n&&(r=(l=(s=+o)/(1+a/100))/1,u=s-l);let d=[e.brand,e.model,e.size,`(${e.year}
1)`].filter(Boolean).join(" "),c=e.bundleRef?.id,m=c?i?.[c]:void 0;return{materialId:e.id,description:e.serialNr?`${d} (SN: ${e.serialNr})`:d,quantity:1,unitPrice:r,totalPrice:l,vatRate:a,vatAmount:u,grossPrice:s,...m?{bundleLabel:m}:{},referenceType:"material"}})}calculateTotals(e){let t=e.reduce((e,t)=>e+t.totalPrice,0),a=e.reduce((e,t)=>e+t.vatAmount,0);return{subtotal:t,vatRate:e.length>0?e[0].vatRate:0,vatAmount:a,total:t+a}}extractBundleData(e,t){let a={};for(let i of e)if(i.bundleRef){let e=i.bundleRef.id;a[e]||(a[e]={bundleId:e,label:t?.[e]??e,materialIds:[]}),a[e].materialIds.push(i.id)}return Object.keys(a).length>0?a:void 0}async updateMaterialsSalesStatus(e,a,i){let n=await (0,s.getDocRef)(u.COLLECTIONS.SALES_DOCUMENTS,i);for(let i of e)await t.default.updateMaterial({salesStatus:a,salesDocumentRef:n},i.id)}async resetMaterialsSalesStatus(e,t){for(let a of e){let e=await (0,s.getDocRef)(u.COLLECTIONS.MATERIAL,a,t);await (0,f.updateDoc)(e,{salesStatus:P.MaterialSalesStatus.AVAILABLE,salesDocumentRef:(0,D.deleteField)()})}}async generateDocumentPdf(e){if(e.isQuote()||e.isOrder())try{let t={invoiceNumber:e.documentNumber,invoiceCircle:e.isQuote()?y.InvoiceCircle.QUOTE:y.InvoiceCircle.ORDER,date:e.createdAt,company:e.company,customer:e.buyer,items:e.items.map(e=>(0,T.createInvoiceItem)({description:e.bundleLabel?`[${e.bundleLabel}] ${e.description}`:e.description,quantity:e.quantity,unitPrice:e.unitPrice,vatRate:e.vatRate,category:"other",referenceId:e.materialId,referenceType:"material"})),subtotal:e.subtotal,vatRate:e.vatRate,vatAmount:e.vatAmount,total:e.total,vatBreakdown:e.vatBreakdown,currency:e.currency,status:T.PaymentInvoiceStatus.ISSUED,notes:e.notes,createdBy:e.createdBy,createdAt:e.createdAt},i=new T.PaymentInvoice(e.documentNumber,t),n=e.isQuote()?"quote":"order",o=await this.generateAndStorePdf(i,{language:e.language,documentType:n});return await a.default.update(e.id,{pdfUrl:o.pdfUrl,pdfStoragePath:o.storagePath}),o.pdfUrl}catch(e){console.error("Error generating document PDF:",e);return}}}let h=new g;e.s(["salesDocumentService",0,h],297185)}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.