@posx/core 5.5.623 → 5.5.624
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/build/index.d.ts +8 -1
- package/build/index.js +4 -4
- package/package.json +1 -1
package/build/index.d.ts
CHANGED
|
@@ -4175,6 +4175,11 @@ declare class CashDrawerConfig implements ICashDrawerConfig {
|
|
|
4175
4175
|
}
|
|
4176
4176
|
//#endregion
|
|
4177
4177
|
//#region src/types/report.type.d.ts
|
|
4178
|
+
type IOrderTypeSummary = {
|
|
4179
|
+
type: InvoiceType;
|
|
4180
|
+
count: number;
|
|
4181
|
+
total: number;
|
|
4182
|
+
};
|
|
4178
4183
|
type IReportCategory = IAppBase & {
|
|
4179
4184
|
reports: IReport[];
|
|
4180
4185
|
};
|
|
@@ -4261,6 +4266,7 @@ type IReportData = {
|
|
|
4261
4266
|
config: IConfig;
|
|
4262
4267
|
invoice_discount_summary: IDiscountSummaryEntry[];
|
|
4263
4268
|
item_discount_summary: IDiscountSummaryEntry[];
|
|
4269
|
+
order_type_summary: IOrderTypeSummary[];
|
|
4264
4270
|
};
|
|
4265
4271
|
declare class ReportData implements IReportData {
|
|
4266
4272
|
start_datetime: string;
|
|
@@ -4282,6 +4288,7 @@ declare class ReportData implements IReportData {
|
|
|
4282
4288
|
config: IConfig;
|
|
4283
4289
|
invoice_discount_summary: IDiscountSummaryEntry[];
|
|
4284
4290
|
item_discount_summary: IDiscountSummaryEntry[];
|
|
4291
|
+
order_type_summary: IOrderTypeSummary[];
|
|
4285
4292
|
}
|
|
4286
4293
|
type ISalesSummary = {
|
|
4287
4294
|
sales_total: number;
|
|
@@ -6511,5 +6518,5 @@ interface ValidationResult {
|
|
|
6511
6518
|
}
|
|
6512
6519
|
declare function validateSTTemplate(jsonStr: string): ValidationResult;
|
|
6513
6520
|
//#endregion
|
|
6514
|
-
export { Address, AlipayMethod, AppBaseModel, AppConfig, AppCoreModel, AppCoreService, AppExtraModel, AppLocalService, AppMiscService, AppRemoteService, AppReport, AppReportService, Applying, Appointment, AppointmentService, AppointmentServiceLine, AppointmentSource, AppointmentStatus, AssetItem, AssetTags, AssetType, Between, Cache, CalcFlow, CalcType, CancelInvoiceOptions, CardPaymentCode, CashDrawerConfig, Category, CategoryButtonShape, CategorySalesSummary, CategoryService, CategoryType, Charge, ChargeConfig, CheckInvoiceOptions, Codepages, ComboGroup, ComboGroupItem, Condition, Config, ConfigService, CoreCategory, CoreItem, Coupon, CouponItemized, CouponUsage, CreateInvoiceOptions, CrmConfig, CurrencyConfig, CustomResponse, Customer, CustomerDisplaySystemConfig, DayOfWeek, DeployChannel, Device, DeviceEtc, DeviceType, DirectPayInvoiceOptions, DiscountType, DrawerSummary, ElectronSocket, Employee, EmployeeRole, EmployeeRoleService, EmployeeService, ErrorMsgs, EscPosCompatibility, EscPosPrinter, FileUploadRequest, GTOConfig, GeneralConfig, GetManyResult, Holiday, IAddress, IAppBase, IAppBaseModel, IAppConfig, IAppCore, IAppCoreModel, IAppCoreService, IAppExtra, IAppExtraModel, IAppLocalService, IAppMiscService, IAppModelSequence, IAppRemoteService, IAppReport, IAppReportService, IApplying, IAppointment, IAppointmentService, IAppointmentServiceLine, ICache, ICashDrawerConfig, ICategory, ICategoryService, IChangePaymentMethodOption, ICharge, IChargeConfig, IComboGroup, IComboGroupItem, IConfig, IConfigService, ICoreCategory, ICoreItem, ICoupon, ICouponItemized, ICouponUsage, ICredit, ICrmConfig, ICurrencyConfig, ICustomer, ICustomerDisplaySystemConfig, IDevice, IDiscount, IDiscountSummaryEntry, IDrawerSummary, IEmployee, IEmployeeRole, IEmployeeRoleService, IEmployeeService, IEscPosPrinter, IEtc, IExportRow, IFileUploadRequest, IFileUploadResponse, IFontSize, IGeneralConfig, IGtoConfig, IInventoryConfig, IInvoice, IInvoiceActivity, IInvoiceBaseService, IInvoiceCharge, IInvoiceCoreLine, IInvoiceDiscount, IInvoiceLine, IInvoiceOperationService, IInvoiceService, IItem, IItemService, IKdsConfig, IKioskSystemConfig, IKitchenConfig, ILabelConfig, ILineOperationService, ILoyaltyProgram, ILoyaltyProgramSummary, IMarketing, IMenu, IMenuService, IMerchant, IMerchantAsset, INode, INodePrinter, INote, INoteEntity, INoteGroup, INoteGroupEntity, INoteGroupService, INoteService, IOnlineOrderConfig, IOrderConfig, IOrderDisplay, IOrderDisplayService, IOrderDisplaySystemConfig, IPaxConfig, IPayment, IPaymentConfig, IPaymentMethod, IPaymentMethodHistory, IPaymentMethodService, IPaymentService, IPaymentSummary, IPoint, IPrice, IPrintBarcode, IPrintCommand, IPrintCommandLine, IPrintImage, IPrintJob, IPrintJobService, IPrintQrcode, IPrintTable, IPrintTableRowItem, IPrintTemplate, IPrintTemplateCore, IPrintTemplateService, IPrintText, IPrinter, IPrinterService, IProductBase, IProductConfig, IProductService, IPushData, IReceiptConfig, IRenderPrintTemplateOptions, IReport, IReportCategory, IReportConfig, IReportData, IReportRequest, IRoundingConfig, ISalesSummary, ISalesperson, ISection, ISectionItem, ISectionItemService, ISectionService, IServiceOptions, IShift, IShiftService, IStandardPaymentMethod, IStockLog, IStockLogService, IStorage, ISubcategory, ISubcategoryService, ISystemConfig, ITaxConfig, ITemplateData, ITill, ITillConfig, ITillService, IUser, IUserConfig, IVisibility, In, Include, InventoryConfig, Invoice, InvoiceAction, InvoiceActivity, InvoiceBaseService, InvoiceCharge, InvoiceCoreLine, InvoiceDiscount, InvoiceLine, InvoiceOperationService, InvoiceService, InvoiceStatus, InvoiceType, Item, ItemSalesSummary, ItemService, KdsConfig, KioskSystemConfig, KitchenConfig, LabelConfig, LineOperationService, LineOptions, LoyaltyProgram, LoyaltyProgramSummary, MarketingConfig, Menu, MenuService, Merchant, MessageType, ModelPrefix, ModelType, ModifierSalesSummary, Node, NodePrinter, Not, Note, NoteEntity, NoteGroup, NoteGroupEntity, OnlineOrderConfig, OpenHours, OrderConfig, OrderDisplay, OrderDisplayService, OrderDisplayStatus, OrderDisplaySystemConfig, OrderFlow, PaxConfig, PayInvoiceOptions, Payment, PaymentConfig, PaymentMethod, PaymentMethodHistory, PaymentMethodService, PaymentService, PaymentStatus, PaymentSummary, PaynowMethod, Price, PrintAlign, PrintBarcode, PrintCommand, PrintImage, PrintJob, PrintJobService, PrintJobStatus, PrintQrcode, PrintSize, PrintStyle, PrintTemplate, PrintTemplateCore, PrintTemplateService, PrintType, Printer, PrinterConnections, PrinterProtocols, PrinterService, PrinterStatus, PrinterType, ProductBase, ProductConfig, ProductPartialAssets, ProductPartialConfig, ProductService, ProductType, PushData, Raw, Receipt, RenderPrintTemplateOptions, Report, ReportCategory, ReportConfig, ReportData, ReportType, RoundingConfig, SalesSummary, Schedule, Section, SectionItem, SectionItemService, SectionItemStatus, SectionService, ServiceFactory, ServiceMode, ServiceOptions, Shift, ShiftService, ShiftStatus, SpecialDay, StandardPaymentMethod, StockChange, StockLog, StockLogEntityType, StockLogRefType, StockLogService, StockLogType, Storage, StorageService, Subcategory, SwitchInvoiceOptions, System, SystemConfig, SystemError, TCategorySalesSummary, TDynamicOrderQR, TItemCoreSalesSummary, TItemSalesSummary, TModifierSalesSummary, TStockChange, TStockChangeItem, TStorageService, TaxConfig, TaxMethod, TemplateData, Till, TillConfig, TillService, TillType, UomType, UpdateGeneralConfigOptions, UpdateInvoiceOptions, User, UserConfig, type ValidationError, type ValidationResult, Visibility, VoidInvoiceOptions, WechatPayMethod, WeeklyHours, createCSVExport, createCSVExportWithHash, dbSchemas, filterByParams, getCategoryButtonShape, humanizedData, importFromCSV, normalizedDate, transformer, validateSTTemplate };
|
|
6521
|
+
export { Address, AlipayMethod, AppBaseModel, AppConfig, AppCoreModel, AppCoreService, AppExtraModel, AppLocalService, AppMiscService, AppRemoteService, AppReport, AppReportService, Applying, Appointment, AppointmentService, AppointmentServiceLine, AppointmentSource, AppointmentStatus, AssetItem, AssetTags, AssetType, Between, Cache, CalcFlow, CalcType, CancelInvoiceOptions, CardPaymentCode, CashDrawerConfig, Category, CategoryButtonShape, CategorySalesSummary, CategoryService, CategoryType, Charge, ChargeConfig, CheckInvoiceOptions, Codepages, ComboGroup, ComboGroupItem, Condition, Config, ConfigService, CoreCategory, CoreItem, Coupon, CouponItemized, CouponUsage, CreateInvoiceOptions, CrmConfig, CurrencyConfig, CustomResponse, Customer, CustomerDisplaySystemConfig, DayOfWeek, DeployChannel, Device, DeviceEtc, DeviceType, DirectPayInvoiceOptions, DiscountType, DrawerSummary, ElectronSocket, Employee, EmployeeRole, EmployeeRoleService, EmployeeService, ErrorMsgs, EscPosCompatibility, EscPosPrinter, FileUploadRequest, GTOConfig, GeneralConfig, GetManyResult, Holiday, IAddress, IAppBase, IAppBaseModel, IAppConfig, IAppCore, IAppCoreModel, IAppCoreService, IAppExtra, IAppExtraModel, IAppLocalService, IAppMiscService, IAppModelSequence, IAppRemoteService, IAppReport, IAppReportService, IApplying, IAppointment, IAppointmentService, IAppointmentServiceLine, ICache, ICashDrawerConfig, ICategory, ICategoryService, IChangePaymentMethodOption, ICharge, IChargeConfig, IComboGroup, IComboGroupItem, IConfig, IConfigService, ICoreCategory, ICoreItem, ICoupon, ICouponItemized, ICouponUsage, ICredit, ICrmConfig, ICurrencyConfig, ICustomer, ICustomerDisplaySystemConfig, IDevice, IDiscount, IDiscountSummaryEntry, IDrawerSummary, IEmployee, IEmployeeRole, IEmployeeRoleService, IEmployeeService, IEscPosPrinter, IEtc, IExportRow, IFileUploadRequest, IFileUploadResponse, IFontSize, IGeneralConfig, IGtoConfig, IInventoryConfig, IInvoice, IInvoiceActivity, IInvoiceBaseService, IInvoiceCharge, IInvoiceCoreLine, IInvoiceDiscount, IInvoiceLine, IInvoiceOperationService, IInvoiceService, IItem, IItemService, IKdsConfig, IKioskSystemConfig, IKitchenConfig, ILabelConfig, ILineOperationService, ILoyaltyProgram, ILoyaltyProgramSummary, IMarketing, IMenu, IMenuService, IMerchant, IMerchantAsset, INode, INodePrinter, INote, INoteEntity, INoteGroup, INoteGroupEntity, INoteGroupService, INoteService, IOnlineOrderConfig, IOrderConfig, IOrderDisplay, IOrderDisplayService, IOrderDisplaySystemConfig, IOrderTypeSummary, IPaxConfig, IPayment, IPaymentConfig, IPaymentMethod, IPaymentMethodHistory, IPaymentMethodService, IPaymentService, IPaymentSummary, IPoint, IPrice, IPrintBarcode, IPrintCommand, IPrintCommandLine, IPrintImage, IPrintJob, IPrintJobService, IPrintQrcode, IPrintTable, IPrintTableRowItem, IPrintTemplate, IPrintTemplateCore, IPrintTemplateService, IPrintText, IPrinter, IPrinterService, IProductBase, IProductConfig, IProductService, IPushData, IReceiptConfig, IRenderPrintTemplateOptions, IReport, IReportCategory, IReportConfig, IReportData, IReportRequest, IRoundingConfig, ISalesSummary, ISalesperson, ISection, ISectionItem, ISectionItemService, ISectionService, IServiceOptions, IShift, IShiftService, IStandardPaymentMethod, IStockLog, IStockLogService, IStorage, ISubcategory, ISubcategoryService, ISystemConfig, ITaxConfig, ITemplateData, ITill, ITillConfig, ITillService, IUser, IUserConfig, IVisibility, In, Include, InventoryConfig, Invoice, InvoiceAction, InvoiceActivity, InvoiceBaseService, InvoiceCharge, InvoiceCoreLine, InvoiceDiscount, InvoiceLine, InvoiceOperationService, InvoiceService, InvoiceStatus, InvoiceType, Item, ItemSalesSummary, ItemService, KdsConfig, KioskSystemConfig, KitchenConfig, LabelConfig, LineOperationService, LineOptions, LoyaltyProgram, LoyaltyProgramSummary, MarketingConfig, Menu, MenuService, Merchant, MessageType, ModelPrefix, ModelType, ModifierSalesSummary, Node, NodePrinter, Not, Note, NoteEntity, NoteGroup, NoteGroupEntity, OnlineOrderConfig, OpenHours, OrderConfig, OrderDisplay, OrderDisplayService, OrderDisplayStatus, OrderDisplaySystemConfig, OrderFlow, PaxConfig, PayInvoiceOptions, Payment, PaymentConfig, PaymentMethod, PaymentMethodHistory, PaymentMethodService, PaymentService, PaymentStatus, PaymentSummary, PaynowMethod, Price, PrintAlign, PrintBarcode, PrintCommand, PrintImage, PrintJob, PrintJobService, PrintJobStatus, PrintQrcode, PrintSize, PrintStyle, PrintTemplate, PrintTemplateCore, PrintTemplateService, PrintType, Printer, PrinterConnections, PrinterProtocols, PrinterService, PrinterStatus, PrinterType, ProductBase, ProductConfig, ProductPartialAssets, ProductPartialConfig, ProductService, ProductType, PushData, Raw, Receipt, RenderPrintTemplateOptions, Report, ReportCategory, ReportConfig, ReportData, ReportType, RoundingConfig, SalesSummary, Schedule, Section, SectionItem, SectionItemService, SectionItemStatus, SectionService, ServiceFactory, ServiceMode, ServiceOptions, Shift, ShiftService, ShiftStatus, SpecialDay, StandardPaymentMethod, StockChange, StockLog, StockLogEntityType, StockLogRefType, StockLogService, StockLogType, Storage, StorageService, Subcategory, SwitchInvoiceOptions, System, SystemConfig, SystemError, TCategorySalesSummary, TDynamicOrderQR, TItemCoreSalesSummary, TItemSalesSummary, TModifierSalesSummary, TStockChange, TStockChangeItem, TStorageService, TaxConfig, TaxMethod, TemplateData, Till, TillConfig, TillService, TillType, UomType, UpdateGeneralConfigOptions, UpdateInvoiceOptions, User, UserConfig, type ValidationError, type ValidationResult, Visibility, VoidInvoiceOptions, WechatPayMethod, WeeklyHours, createCSVExport, createCSVExportWithHash, dbSchemas, filterByParams, getCategoryButtonShape, humanizedData, importFromCSV, normalizedDate, transformer, validateSTTemplate };
|
|
6515
6522
|
//# sourceMappingURL=index.d.ts.map
|
package/build/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import e from"dayjs";import{nanoid as t}from"nanoid";import n from"wcwidth";import{Dexie as r,liveQuery as i}from"dexie";import{v4 as a}from"uuid";import*as o from"lodash";import s from"axios";import c from"crypto-js";import{SelectTransform as l}from"selecttransform";import{NetworkInterface as u}from"@awesome-cordova-plugins/network-interface";import d from"handlebars";import{QueryBuilder as f}from"@litepos/autoquery";import p from"bcryptjs";var m=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){if(typeof require<`u`)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function.")});function h(e){"@babel/helpers - typeof";return h=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},h(e)}function g(e,t){if(h(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(h(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function _(e){var t=g(e,`string`);return h(t)==`symbol`?t:t+``}function v(e,t,n){return(t=_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var y=class{constructor(){v(this,`address1`,``),v(this,`address2`,``),v(this,`lat`,``),v(this,`lng`,``),v(this,`postcode`,``),v(this,`note`,``),v(this,`is_default`,!1),v(this,`name`,``),v(this,`salute`,``),v(this,`phone_number`,``)}},b=class{constructor(){v(this,`id`,0),v(this,`ref_id`,``),v(this,`image_url`,``),v(this,`stripe_token`,``),v(this,`stripe_customer_id`,``),v(this,`username`,``),v(this,`normalized_username`,``),v(this,`company`,``),v(this,`ic`,``),v(this,`display_name`,``),v(this,`full_name`,``),v(this,`birth_date`,``),v(this,`gender`,``),v(this,`address`,``),v(this,`postcode`,``),v(this,`note`,``),v(this,`language`,``),v(this,`time_zone`,``),v(this,`created_at`,new Date),v(this,`updated_at`,new Date),v(this,`license_ids`,``),v(this,`security_stamp`,``),v(this,`phone_number`,``)}},x=class extends b{constructor(){super(),v(this,`license_id`,0),v(this,`credit`,0),v(this,`point`,0),v(this,`transaction_total`,0),v(this,`transaction_time`,0),v(this,`user_group_id`,0),v(this,`user_group_name`,``),v(this,`group_expires_at`,null),v(this,`error`,``)}},S=function(e){return e[e.All=1]=`All`,e[e.Inclusive=2]=`Inclusive`,e[e.Exclusive=3]=`Exclusive`,e}(S||{}),C=function(e){return e[e.Flat=1]=`Flat`,e[e.Percent=2]=`Percent`,e}(C||{}),ee=class{constructor(){v(this,`applying_type`,S.Inclusive),v(this,`applying_items`,[])}},te=class{constructor(e){v(this,`guid`,``),v(this,`promo_code`,``),v(this,`is_multi_stores`,!1),v(this,`name`,``),v(this,`alias`,void 0),v(this,`description`,void 0),v(this,`description_alias`,void 0),v(this,`applying_plus`,void 0),v(this,`applying_user_tags`,void 0),v(this,`applying_user_groups`,void 0),v(this,`discount_calc_type`,C.Flat),v(this,`discount_amount`,void 0),v(this,`discount_percent`,void 0),v(this,`duration`,30),v(this,`usage_count`,0),v(this,`usage_limit_per_invoice`,1),v(this,`above_invoice_amount`,void 0),v(this,`below_invoice_amount`,void 0),v(this,`is_delivery_free`,!1),v(this,`is_individual_use`,!0),v(this,`price_in_points`,void 0),v(this,`styles`,{}),v(this,`expired_at`,void 0),v(this,`auto_gen`,!1),v(this,`can_sell`,!0),v(this,`can_redeem`,!0),e&&(this.guid=e.guid,this.promo_code=e.promo_code,this.is_multi_stores=e.is_multi_stores,this.name=e.name,this.alias=e.alias,this.description=e.description,this.description_alias=e.description_alias,this.applying_plus=e.applying_plus,this.applying_user_tags=e.applying_user_tags,this.applying_user_groups=e.applying_user_groups,this.discount_calc_type=e.discount_calc_type,this.discount_amount=e.discount_amount,this.discount_percent=e.discount_percent,this.duration=e.duration,this.usage_count=e.usage_count,this.usage_limit_per_invoice=e.usage_limit_per_invoice,this.above_invoice_amount=e.above_invoice_amount,this.below_invoice_amount=e.below_invoice_amount,this.is_delivery_free=e.is_delivery_free,this.is_individual_use=e.is_individual_use,this.price_in_points=e.price_in_points,this.styles={...e.styles},this.expired_at=e.expired_at,this.auto_gen=e.auto_gen,this.can_sell=e.can_sell,this.can_redeem=e.can_redeem)}},ne=class{constructor(e){v(this,`invoice_uid`,``),e&&(this.invoice_uid=e.invoice_uid)}},re=class{constructor(e){v(this,`guid`,``),v(this,`coupon`,new te),v(this,`is_multi_stores`,!1),v(this,`usage`,new ne),v(this,`employee_uid`,``),v(this,`promo_code`,``),v(this,`is_expired`,!1),v(this,`is_redeemed`,!1),v(this,`is_generated`,!1),e&&(this.guid=e.guid,this.coupon=new te(e.coupon),this.is_multi_stores=e.is_multi_stores,this.usage=new ne(e.usage),this.employee_uid=e.employee_uid,this.promo_code=e.promo_code,this.is_expired=e.is_expired,this.is_redeemed=e.is_redeemed,this.is_generated=e.is_generated)}};const ie={from(t){return e(t).format(`YYYY-MM-DD HH:mm:ss`)},to(e){return e}};var w=class{constructor(){v(this,`uid`,void 0),v(this,`updated_at`,new Date),v(this,`created_at`,new Date),v(this,`created_at_timestamp`,new Date().getTime()),v(this,`deleted_at`,null),v(this,`_timestamp`,void 0),v(this,`id_in_server`,void 0)}},T=class extends w{constructor(){super(),v(this,`name`,void 0),v(this,`name_translations`,{})}},ae=class extends T{constructor(...e){super(...e),v(this,`description`,void 0),v(this,`description_translations`,{})}};let E=function(e){return e.Merchant=`mnt_`,e.Section=`sec_`,e.SectionItem=`sit_`,e.Category=`cat_`,e.Subcategory=`sat_`,e.Item=`itm_`,e.ItemModifier=`iod_`,e.ItemModifierCategory=`imc_`,e.Config=`cfg_`,e.Device=`dev_`,e.Invoice=`inv_`,e.InvoiceLine=`iln_`,e.InvoiceCharge=`ich_`,e.Payment=`pay_`,e.Employee=`emp_`,e.Shift=`shf_`,e.Till=`til_`,e.ReportCategory=`rpc_`,e.Report=`rpt_`,e.AppReport=`apr_`,e.PaymentMethod=`pmd_`,e.PrintTemplate=`ptl_`,e.PrintJob=`pjb_`,e.Printer=`prt_`,e.InvoiceDiscount=`ind_`,e.EmployeeRole=`emr_`,e.OrderDisplaySystem=`ods_`,e.Charge=`chr_`,e.Price=`prc_`,e.ComboGroup=`cbo_`,e.Storage=`sto_`,e.Menu=`men_`,e.StockLog=`stl_`,e.Appointment=`apt_`,e.AppointmentServiceLine=`asl_`,e}({}),oe=function(e){return e.Merchant=`mnt`,e.Section=`sec`,e.SectionItem=`sit`,e.Category=`cat`,e.Subcategory=`sat`,e.Item=`itm`,e.Config=`cfg`,e.Device=`dev`,e.Invoice=`inv`,e}({}),se=function(e){return e.LOCAL=`local`,e.CLOUD=`cloud`,e}({});var ce=class{constructor(){v(this,`mode`,void 0),v(this,`base_url`,void 0),v(this,`device_uid`,void 0),v(this,`merchant_uid`,void 0),v(this,`token`,void 0),v(this,`database`,void 0)}};let le=function(e){return e.Data=`DataMessage`,e.Event=`EventMessage`,e}({});var ue=class{constructor(){v(this,`model`,``),v(this,`data`,``),v(this,`has_many`,!1),v(this,`type`,le.Data)}},D=class extends Error{constructor(e){super(e),this.name=`system_error`}};let O=function(e){return e.outdatedInvoice=`outdated invoice`,e.outdatedSectionItem=`outdated section item`,e.outdatedSourceSectionItem=`outdated source section item`,e.outdatedTargetSectionItem=`outdated target section item`,e}({}),k=function(e){return e.Open=`opened`,e.Closed=`closed`,e}({});var de=class extends w{constructor(){super(),v(this,`user_uid`,``),v(this,`started_at`,new Date),v(this,`ended_at`,new Date),v(this,`declared_amount`,0),v(this,`drawer_amount`,0),v(this,`first_invoice_number`,0),v(this,`status`,k.Open),v(this,`uid`,E.Shift+t())}};let A=function(e){return e.OpenDeposit=`open_deposit`,e.CashDeposit=`cash_deposit`,e.CashIn=`cash_in`,e.CashOut=`cash_out`,e.CashInvoice=`cash_invoice`,e}({});var j=class extends w{constructor(){super(),v(this,`user_uid`,``),v(this,`shift_uid`,``),v(this,`invoice_uid`,``),v(this,`type`,A.CashDeposit),v(this,`amount`,0),v(this,`note`,``),v(this,`uid`,E.Till+t())}};let M=function(e){return e.CLOSED=`closed`,e.OPENED=`opened`,e.PAYMENT=`payment`,e}({});var fe=class extends T{constructor(){super(),v(this,`printer_id_order_list`,[]),v(this,`order_printer_uids`,[]),v(this,`receipt_printer_uid`,``),v(this,`check_printer_uid`,``),v(this,`qr_printer_uid`,``),v(this,`total`,0),v(this,`time`,0),v(this,`pax`,0),v(this,`invoice_created_at`,new Date),v(this,`child_pax`,0),v(this,`baby_pax`,0),v(this,`uid`,E.SectionItem+t()),v(this,`invoice_uid`,``),v(this,`section_uid`,``),v(this,`status`,M.CLOSED),v(this,`size_x`,0),v(this,`size_y`,0),v(this,`row`,0),v(this,`col`,0),v(this,`is_take_out`,!1),v(this,`is_delivery`,!1),v(this,`is_locked`,!1),v(this,`soup_base_quota`,0),v(this,`soup_base_type`,0),v(this,`is_delete`,!1),v(this,`meta`,{}),v(this,`customer`,{}),v(this,`etc`,{})}},pe=class extends T{constructor(){super(),v(this,`sequence`,0),v(this,`disable_auto_print_receipt`,!1),v(this,`uid`,E.Section+t())}},me=class extends T{constructor(){super(),v(this,`permissions`,[]),v(this,`is_default`,!1),v(this,`uid`,E.EmployeeRole+t())}},he=class{constructor(e){v(this,`item_uid`,``),v(this,`quantity`,0),v(this,`modifiers`,[]),this.item_uid=e,this.quantity=0,this.modifiers=[]}},N=class extends ae{constructor(){super(),v(this,`meta`,{}),v(this,`etc`,{}),v(this,`assets`,{}),v(this,`config`,{online_order_display_large_image:!1}),v(this,`is_internal`,!1),v(this,`color`,``),v(this,`icon`,``),v(this,`sequence`,0)}},ge=class{constructor(){v(this,`system`,_e.POS),v(this,`visible`,!1),v(this,`sequence`,0)}};let _e=function(e){return e.POS=`pos`,e.QrCodeOrder=`qr_code_order`,e}({}),ve=function(e){return e.Product=`product`,e.Modifier=`modifier`,e}({});var ye=class extends N{constructor(){super(),v(this,`type`,ve.Modifier),v(this,`visibility`,[]),v(this,`uid`,E.ItemModifierCategory+t()),v(this,`max_order`,0),v(this,`min_order`,0),v(this,`is_delisted`,!1),v(this,`code`,void 0),v(this,`printing_sequence`,0),v(this,`allow_custom_modifier`,void 0)}},be=class extends N{constructor(){super(),v(this,`image_url`,``),v(this,`image_file_path`,``),v(this,`image_thumbnail_url`,``),v(this,`image_thumbnail_file_path`,``),v(this,`has_subcategory`,!1),v(this,`name_translations`,{}),v(this,`visibility`,void 0),v(this,`printing_sequence`,0),v(this,`type`,ve.Product),v(this,`is_delisted`,!1),v(this,`subcategories`,[]),v(this,`uid`,E.Category+t()),v(this,`max_order`,0),v(this,`min_order`,0),v(this,`code`,void 0),v(this,`non_searchable`,!1)}},xe=class extends N{constructor(){super(),v(this,`category_uid`,``),v(this,`uid`,E.Subcategory+t())}};let P=function(e){return e.ByQuantity=`by_quantity`,e.ByWeight=`by_weight`,e.Service=`service`,e.Combo=`combo`,e.Modifier=`modifier`,e.Package=`package`,e}({});var Se=class extends N{constructor(){super(),v(this,`image_url`,``),v(this,`image_file_path`,``),v(this,`image_thumbnail_url`,``),v(this,`image_thumbnail_file_path`,``),v(this,`visibility`,[]),v(this,`sku`,``),v(this,`type`,P.Modifier),v(this,`barcode`,``),v(this,`plu`,void 0),v(this,`category_uid`,``),v(this,`price`,0),v(this,`original_price`,0),v(this,`prices`,[]),v(this,`stock`,1e3),v(this,`print_on_receipt`,!0),v(this,`price_adjustable`,!1),v(this,`is_sold_out`,!1),v(this,`recipe`,``),v(this,`is_remark_disabled`,!1),v(this,`auto_select_first_modifier`,!1),v(this,`is_auto_applied`,!1),v(this,`uid`,E.ItemModifier+t())}},Ce=class extends Se{constructor(){super(),v(this,`codename`,``),v(this,`sku`,``),v(this,`recipe`,``),v(this,`barcode`,``),v(this,`type`,P.ByQuantity),v(this,`add_credit`,0),v(this,`add_point`,0),v(this,`category_uid`,``),v(this,`subcategory_uid`,``),v(this,`unit`,0),v(this,`stock`,0),v(this,`is_sold_out`,!1),v(this,`sold`,0),v(this,`print_on_receipt`,!0),v(this,`price`,0),v(this,`open_editor`,!0),v(this,`price_adjustable`,!1),v(this,`minus_point`,0),v(this,`cost`,0),v(this,`discountable`,!0),v(this,`printing_sequence`,0),v(this,`recommended`,!1),v(this,`likes`,0),v(this,`dislikes`,0),v(this,`is_tax_exempt`,!1),v(this,`is_service_charge_exempt`,!1),v(this,`is_point_reward_exempt`,!1),v(this,`is_credit_reward_exempt`,!1),v(this,`is_internal`,!1),v(this,`is_delisted`,!1),v(this,`uid`,E.Item+t()),v(this,`modifiers`,void 0),v(this,`modifier_categories`,void 0),v(this,`kitchen_printers_uids`,[]),v(this,`order_printers_uids`,[]),v(this,`label_printers_uids`,[]),v(this,`open_editor_panel`,!1),v(this,`open_price_editor`,!1),v(this,`combo_groups`,[]),v(this,`non_searchable`,!1)}},we=class extends w{constructor(){super(),v(this,`lookup_keys`,[]),v(this,`product_uid`,``),v(this,`uid`,E.Price+t()),v(this,`amount`,0),v(this,`name`,``),v(this,`name_translations`,{})}},Te=class{constructor(){v(this,`item_uid`,``),v(this,`combo_item`,void 0),v(this,`price`,0),v(this,`sequence`,0),v(this,`meta`,{})}},Ee=class{constructor(){v(this,`uid`,E.ComboGroup+t()),v(this,`name`,``),v(this,`name_translations`,{}),v(this,`min_order`,1),v(this,`max_order`,1),v(this,`combo_items`,[]),v(this,`sequence`,0),v(this,`meta`,{})}},De=class e{constructor(){v(this,`_state`,e.State.CLOSED),v(this,`cleanup`,void 0),v(this,`onData`,null),v(this,`onClose`,null),v(this,`onError`,null)}get state(){return this._state}static setWindow(t){e.electronSocket=t.electronSocket}setupListeners(){this.cleanup?.(),this.cleanup=window.electronSocket.onEvent(t=>{switch(t.type){case`DataReceived`:this.onData?.(new Uint8Array(t.data));break;case`Close`:this._state=e.State.CLOSED,this.onClose?.(t.hasError),this.cleanup?.();break;case`Error`:this.onError?.(t.errorMessage);break}})}async open(t,n,r,i){try{if(this._state!==e.State.CLOSED){i?.(`Invalid state: ${this._state}`);return}this._state=e.State.OPENING,this.setupListeners(),await e.electronSocket.open(t,n)?(this._state=e.State.OPENED,r?.()):i?.(`Open failed`)}catch(t){this._state=e.State.CLOSED,this.cleanup?.(),i?.(`Open failed: ${t}`)}}async write(t,n,r){try{this._state!==e.State.OPENED&&r?.(`Socket not opened`),await e.electronSocket.write(Array.from(t))?n?.():r?.(`Write failed`)}catch(e){r?.(`Write failed: ${e}`)}}async close(t,n){if(this._state!==e.State.OPENED){n?.(`Invalid state: ${this._state}`);return}try{this._state=e.State.CLOSING,await e.electronSocket.close()?(this._state=e.State.CLOSED,this.cleanup?.(),t?.()):n?.(`Close socket failed`)}catch(t){this._state=e.State.CLOSED,this.cleanup?.(),n?.(`Close socket failed: ${t}`)}}};v(De,`State`,{CLOSED:0,OPENING:1,OPENED:2,CLOSING:3}),v(De,`electronSocket`,null);function Oe(e){return e===`69`}const ke={Ẳ:2,Ẵ:5,Ẫ:6,Ỷ:20,Ỹ:25,Ỵ:30,Ạ:128,Ắ:129,Ằ:130,Ặ:131,Ấ:132,Ầ:133,Ẩ:134,Ậ:135,Ẽ:136,Ẹ:137,Ế:138,Ề:139,Ể:140,Ễ:141,Ệ:142,Ố:143,Ồ:144,Ổ:145,Ỗ:146,Ộ:147,Ợ:148,Ớ:149,Ờ:150,Ở:151,Ị:152,Ỏ:153,Ọ:154,Ỉ:155,Ủ:156,Ũ:157,Ụ:158,Ỳ:159,Õ:160,ắ:161,ằ:162,ặ:163,ấ:164,ầ:165,ẩ:166,ậ:167,ẽ:168,ẹ:169,ế:170,ề:171,ể:172,ễ:173,ệ:174,ố:175,ồ:176,ổ:177,ỗ:178,Ỡ:179,Ơ:180,ộ:181,ờ:182,ở:183,ị:184,Ự:185,Ứ:186,Ừ:187,Ử:188,ơ:189,ớ:190,Ư:191,À:192,Á:193,Â:194,Ã:195,Ả:196,Ă:197,ẳ:198,ẵ:199,È:200,É:201,Ê:202,Ẻ:203,Ì:204,Í:205,Ĩ:206,ỳ:207,Đ:208,ứ:209,Ò:210,Ó:211,Ô:212,ạ:213,ỷ:214,ừ:215,ử:216,Ù:217,Ú:218,ỹ:219,ỵ:220,Ý:221,ỡ:222,ư:223,à:224,á:225,â:226,ã:227,ả:228,ă:229,ữ:230,ẫ:231,è:232,é:233,ê:234,ẻ:235,ì:236,í:237,ĩ:238,ỉ:239,đ:240,ự:241,ò:242,ó:243,ô:244,õ:245,ỏ:246,ọ:247,ụ:248,ù:249,ú:250,ũ:251,ủ:252,ý:253,ợ:254,Ữ:255};function Ae(e,t=63){let n=[];for(let r of e)if(ke[r]!==void 0)n.push(ke[r]);else{let e=r.charCodeAt(0);e<=127?n.push(e):n.push(t)}return Uint8Array.from(n)}function je(){return typeof Socket>`u`?new De:new Socket}var Me=class{constructor(){v(this,`socket`,void 0),this.socket=je(),console.log(`this.socket`,JSON.stringify(this.socket)),this.socket.onData=function(e){console.log(`event - receive: `,e)},this.socket.onClose=function(e){console.log(`event - socket closed`)},this.socket.onError=function(e){console.error(`event - socket error:`,e)}}async testPrint(e){await this.connect(`192.168.1.253`);let t=await this.interpret(e);console.log(`escpos commands:`,JSON.stringify(t));let n=await this.write(t);return await this.disconnect(),n}async connect(e,t=9100,n=5e3){return new Promise((r,i)=>{let a,o,s=()=>{a&&window.clearTimeout(a),o&&window.clearInterval(o)};o=window.setInterval(()=>{this.socket.state===2&&(s(),r(!0))},100),a=window.setTimeout(()=>{s(),r(!1)},n),this.socket.open(e,t,()=>{},e=>{s(),r(!1)})}).catch(async e=>!1)}async write(e,t=1e4){return new Promise((n,r)=>{let i;this.socket.write(e,()=>{console.log(`write success`),clearTimeout(i),n(!0)}),i=window.setTimeout(()=>{console.error(`socket write timed out`),n(!1)},t)}).catch(e=>(console.error(`socket write exception: `,e),!1))}async interpret(e){let{default:t}=await import(`esc-pos-encoder-ionic`),n=new t,r=n.initialize();if(e.codepage&&!Object.values(F).includes(e.codepage)){let t=parseInt(e.codepage,10);r.raw([31,27,31,255,t,10,0])}else e.codepage&&Object.values(F).includes(e.codepage)?n.codepage(e.codepage):n.codepage(F.SimplifiedChinese);for(let t of e.items){if(!t)throw Error(`Item is undefined or null`);switch(t.style){case Pe.Bold:r.bold(!0);break;case Pe.Italic:r.italic(!0);break;case Pe.Underline:r.underline(!0);break;default:r.bold(!1),r.italic(!1),r.underline(!1);break}switch(t.align&&r.align(t.align),t.type){case I.Text:if(t.item?.text){if(t.item.size===Fe.Custom&&t.item.height&&t.item.width){if(t.item.width<0||t.item.width>7||t.item.height<0||t.item.height>7)throw Error(`font_width and font_height must be between 0 and 7`);let e=t.item.height<<4|t.item.width;r.raw([29,33,e])}else t.item.size&&r.size(t.item.size);if(Oe(e.codepage)){let e=Ae(t.item.text);r.raw(Array.from(e))}else r.text(t.item.text,t.item.line_width??48);t.item.size===Fe.Custom&&r.raw([29,33,0])}break;case I.Table:if(t.table){if(t.table.size===Fe.Custom&&t.table.height&&t.table.width){if(t.table.width<0||t.table.width>7||t.table.height<0||t.table.height>7)throw Error(`font_width and font_height must be between 0 and 7`);let e=t.table.height<<4|t.table.width;r.raw([29,33,e])}else t.table.size&&r.size(t.table.size);this.formatTable(t.table.items,t.table.line_width??48).forEach(t=>{if(Oe(e.codepage)){let e=Ae(t);r.raw(Array.from(e))}else r.text(t);r.newline()}),t.table.size===Fe.Custom&&r.raw([29,33,0])}break;case I.Line:r.line(t.item?.text?.repeat(48)??`-`.repeat(48),t.item?.line_width??48);break;case I.NewLine:t.repeat=t.repeat??1;for(let e=0;e<t.repeat;e++)r.newline();break;case I.Image:if(t.image){let e=await this.base64ToImageBitmap(t.image.base64_data);r.image(e,t.image.width,t.image.height,t.image.algorithm,t.image.threshold)}break;case I.QRCode:t.qrcode&&r.qrcode(t.qrcode.data,t.qrcode.model,t.qrcode.size,t.qrcode.errorlevel);break;case I.Barcode:t.barcode&&r.barcode(t.barcode.data,t.barcode.symbology,t.barcode.height);break;case I.Cut:r.cut(t.item?.text??`full`);break;case I.Beeper:r.beeper();break;case I.OpenCashDrawer:r.openCashDrawer();break;default:throw Error(`Unsupported item type: ${t.type}`)}}return r.encode()}formatTable(e,t=48){let n=e.map(e=>Math.floor(t*(e.column_width/100))),r=e.map((e,t)=>this.wrapText(e.text,n[t])),i=[],a=Math.max(...r.map(e=>e.length));for(let t=0;t<a;t++){let a=``;for(let i=0;i<e.length;i++){let e=r[i][t]||``;a+=this.padEnd(e,n[i])}i.push(a)}return i}padEnd(e,t){let r=Array.from(e).reduce((e,t)=>e+n(t),0);return e+` `.repeat(Math.max(0,t-r))}padStart(e,t){let r=Array.from(e).reduce((e,t)=>e+n(t),0);return` `.repeat(Math.max(0,t-r))+e}wrapText(e,t){if(typeof e!=`string`&&(e=e.toString()),!e)return[``];let r=[],i=``,a=0;for(let o of e){if(o===`
|
|
2
|
-
`){r.push(i),i=``,a=0;continue}let e=n(o);a+e>t&&(r.push(i),i=``,a=0),i+=o,a+=e}return i&&r.push(i),r}async disconnect(){if(!this.socket||this.socket.state!==2)return!0;try{return await this.close(),!0}catch(e){throw Error(e)}}close(e=5e3){return new Promise((t,n)=>{let r=this.socket.onClose,i;this.socket.onClose=e=>{clearTimeout(i),this.socket.onClose=r,e?n(Error(`Socket closed with error: ${e}`)):t(),typeof r==`function`&&r(e)},i=window.setTimeout(()=>{this.socket.onClose=r,n(Error(`Socket close operation timed out`))},e),this.socket.close(()=>console.log(`Close initiated successfully`),e=>{clearTimeout(i),this.socket.onClose=r,n(e)})})}async base64ToImageBitmap(e){let t=e.match(/^data:(image\/(?:jpeg|png));base64,(.+)$/i);if(!t)throw Error(`base64_data format is invalid or image type is not supported (only jpeg/png allowed)`);let[,n,r]=t,i=new Blob([Uint8Array.from(atob(r),e=>e.charCodeAt(0))],{type:n});return await createImageBitmap(i)}};let F=function(e){return e.English=`cp437`,e.Greek=`cp737`,e.WesternEurope=`cp850`,e.BalticRim=`cp775`,e.CentralEurope=`cp852`,e.Cyrillic=`cp855`,e.Turkish=`cp857`,e.MultilingualLatin1WithEuro=`cp858`,e.Portuguese=`cp860`,e.Icelandic=`cp861`,e.Hebrew=`cp862`,e.FrenchCanadian=`cp863`,e.Arabic=`cp864`,e.Nordic=`cp865`,e.Russian=`cp866`,e.ModernGreek=`cp869`,e.SimplifiedChinese=`cp936`,e.Korean=`cp949`,e.TraditionalChinese=`cp950`,e.WesternEuropeanLatin=`cp1252`,e.ArabicISO=`iso88596`,e.Japanese=`shiftjis`,e.CentralEuropeanLatinWindows=`windows1250`,e.CyrillicWindows=`windows1251`,e.WesternEuropeanLatinWindows=`windows1252`,e.GreekWindows=`windows1253`,e.TurkishWindows=`windows1254`,e.HebrewWindows=`windows1255`,e.ArabicWindows=`windows1256`,e.BalticWindows=`windows1257`,e.Vietnamese=`windows1258`,e}({}),Ne=function(e){return e.Left=`left`,e.Center=`center`,e.Right=`right`,e}({}),Pe=function(e){return e.Normal=`normal`,e.Bold=`bold`,e.Italic=`italic`,e.Underline=`underline`,e}({}),Fe=function(e){return e.Custom=`custom`,e.Normal=`normal`,e.Small=`small`,e}({}),I=function(e){return e.Text=`text`,e.Table=`table`,e.Line=`line`,e.Image=`image`,e.QRCode=`qrcode`,e.NewLine=`newline`,e.Barcode=`barcode`,e.Cut=`cut`,e.Beeper=`beeper`,e.OpenCashDrawer=`open_cash_drawer`,e}({});var Ie=class{constructor(){v(this,`data`,``),v(this,`symbology`,`ean13`),v(this,`height`,0)}},Le=class{constructor(){v(this,`data`,``),v(this,`model`,2),v(this,`size`,6),v(this,`errorlevel`,`m`)}},Re=class{constructor(){v(this,`base64_data`,``),v(this,`width`,0),v(this,`height`,0),v(this,`algorithm`,`threshold`),v(this,`threshold`,128)}};let ze=function(e){return e[e.SunmiPrinter=0]=`SunmiPrinter`,e}({});var L=class{constructor(){v(this,`codepage`,F.WesternEuropeanLatin),v(this,`items`,[])}};function R(t,n){return e(t).format(n||`YYYY-MMM-DD HH:mm:ss`)}function Be(e){return`${e.getFullYear()}-${(e.getMonth()+1).toString().padStart(2,`0`)}-${e.getDate().toString().padStart(2,`0`)} ${e.getHours().toString().padStart(2,`0`)}:${e.getMinutes().toString().padStart(2,`0`)}:${e.getSeconds().toString().padStart(2,`0`)}`}var Ve=class extends T{constructor(){super(),v(this,`machine_name`,``),v(this,`connection_id`,``),v(this,`type`,Ue.Client),v(this,`etc`,{fomopay_terminal_id:``,hirector_public_key:``,hirector_private_key:``,yeahpay_app_id:``,yeahpay_device_sn:``,yeahpay_server_public_key:``,yeahpay_client_private_key:``,yeahpay_signature_key:``,yeahpay_async_url:``,sync_to_specific_cds:``})}},He=class extends T{constructor(){super(),v(this,`type`,Ue.Node),v(this,`machine_name`,``),v(this,`connection_id`,``),v(this,`etc`,{fomopay_terminal_id:``,hirector_public_key:``,hirector_private_key:``,yeahpay_app_id:``,yeahpay_device_sn:``,yeahpay_server_public_key:``,yeahpay_client_private_key:``,yeahpay_signature_key:``,yeahpay_async_url:``,sync_to_specific_cds:``})}};let Ue=function(e){return e.Client=`client`,e.Node=`node`,e}({}),z=function(e){return e.ReceiptPrinter=`receipt_printer`,e.CheckPrinter=`check_printer`,e.OrderPrinter=`order_printer`,e.KitchenPrinter=`kitchen_printer`,e.KioskPrinter=`kiosk_printer`,e.LabelPrinter=`label_printer`,e.QrCodePrinter=`qr_code_printer`,e.KitchenDisplayPrinter=`kitchen_display_printer`,e}({});var We=class{constructor(){v(this,`printer_name`,``),v(this,`status`,``),v(this,`port_name`,``),v(this,`error`,``)}};let Ge=function(e){return e.ESCPOS=`ESC/POS`,e.TSPL=`TSPL`,e}({}),Ke=function(e){return e.USB=`USB`,e.WINDOWS_DRIVER=`WINDOWS_DRIVER`,e.ETHERNET=`ETHERNET`,e.BLUETOOTH=`BLUETOOTH`,e.BUILTIN=`BUILTIN`,e.IMIN_BUILT_IN=`IMIN_BUILT_IN`,e}({});var qe=class{constructor(){v(this,`header`,``),v(this,`body`,``),v(this,`footer`,``),v(this,`commands`,``),v(this,`type`,z.ReceiptPrinter)}},B=class extends T{constructor(){super(),v(this,`header`,``),v(this,`body`,``),v(this,`footer`,``),v(this,`commands`,``),v(this,`printer_type`,z.ReceiptPrinter),v(this,`codepage`,void 0),v(this,`uid`,E.PrintTemplate+t()),v(this,`report_code_name`,``)}};let Je=function(e){return e.Queued=`queued`,e.Printed=`printed`,e.Failed=`failed`,e.Expired=`expired`,e}({});var V=class extends T{constructor(e,n,r=!1,i=1){super(),v(this,`printer_name`,``),v(this,`driver_printer_name`,``),v(this,`printer_ip`,``),v(this,`printer_uid`,``),v(this,`printer_type`,z.ReceiptPrinter),v(this,`protocol`,Ge.ESCPOS),v(this,`connection_type`,Ke.ETHERNET),v(this,`data`,new L),v(this,`status`,Je.Queued),v(this,`retries`,0),v(this,`commands`,``),v(this,`uid`,E.PrintJob+t()),v(this,`save_only`,!1),v(this,`print_times`,1),v(this,`printed`,0),v(this,`device_uid_to_print`,``),v(this,`designated_table_section_uids`,[]),v(this,`job_id`,0),v(this,`print_sequence`,void 0),v(this,`meta`,{}),this.driver_printer_name=e.driver_printer_name,e.protocol&&(this.protocol=e.protocol),e.connection_type&&(this.connection_type=e.connection_type),this.printer_name=e.name,this.printer_ip=e.ip_address,e.type&&(this.printer_type=e.type),this.data=n,this.printer_uid=e.uid,this.save_only=r,this.print_times=i,e.print_sequence!==void 0&&(this.print_sequence=e.print_sequence)}};let Ye=function(e){return e.Online=`online`,e.Offline=`offline`,e}({});var Xe=class extends T{constructor(){super(),v(this,`device_uid`,``),v(this,`terminal_device_uids`,[]),v(this,`type`,z.ReceiptPrinter),v(this,`is_not_default`,!1),v(this,`driver_printer_name`,``),v(this,`fallback_printer_uid`,0),v(this,`protocol`,Ge.ESCPOS),v(this,`connection_type`,Ke.ETHERNET),v(this,`print_template_uid`,``),v(this,`uid`,E.Printer+t()),v(this,`ip_address`,``),v(this,`status`,Ye.Online),v(this,`kitchen_itemized_print`,!1),v(this,`print_times`,1),v(this,`retries`,1),v(this,`use_device_name`,!1),v(this,`usb_device_name`,``)}},Ze=class{constructor(){v(this,`config`,{}),v(this,`invoice`,{}),v(this,`report_data`,{}),v(this,`section_item`,{}),v(this,`printer_name`,``),v(this,`printed_at`,new Date),v(this,`normalized_printed_at`,``),v(this,`meta`,{}),v(this,`is_cancel`,!1),this.normalized_printed_at=R(this.printed_at)}},H=class{constructor(){v(this,`printer_name`,``),v(this,`kitchen_itemized_print`,!1),v(this,`is_cancel`,!1)}},Qe=class extends w{constructor(){super(),v(this,`invoice_uid`,``),v(this,`tender_amount`,0),v(this,`change_amount`,0),v(this,`payment_method_uid`,``),v(this,`payment_method_code`,``),v(this,`payment_method_name`,``),v(this,`payment_method`,new $e),v(this,`payment_method_history`,void 0),v(this,`uid`,E.Payment+t()),v(this,`updated_at`,new Date)}},$e=class extends T{constructor(){super(),v(this,`sequence`,0),v(this,`payment_currency_id`,0),v(this,`currency_code`,``),v(this,`currency_symbol`,`$`),v(this,`payment_method_code`,``),v(this,`name`,``),v(this,`codename`,``),v(this,`name_abbrev`,``),v(this,`enable_drawer`,!1),v(this,`enable_receipt`,!1),v(this,`image_url`,``),v(this,`custom_image_url`,``),v(this,`is_cash`,!1),v(this,`is_integrated`,!1),v(this,`is_disabled`,!0),v(this,`type`,0),v(this,`api_id`,``),v(this,`api_key`,``),v(this,`is_sales_exclusive`,!1),v(this,`enable_credit_validation`,!1),v(this,`enable_customer_validation`,!1),v(this,`is_cancellable`,!1),v(this,`require_zero_balance`,!1),v(this,`allow_custom_amount`,!1),v(this,`uid`,E.PaymentMethod+t())}},et=class extends $e{constructor(){super(),v(this,`changed_at`,new Date),v(this,`changed_by`,``)}},tt=class{toPaymentMethod(){let e=new $e;return e.currency_code=this.currency_code||``,e.payment_method_code=this.payment_method_code||``,e.codename=this.codename||``,e.name=this.name||``,e.name_abbrev=this.name_abbrev||``,e.enable_drawer=this.enable_drawer,e.enable_receipt=this.enable_receipt,e.image_url=this.image_url||``,e.is_cash=this.is_cash,e.is_integrated=this.is_integrated,e.is_disabled=this.is_disabled,e.type=this.type,e.api_id=this.api_id||``,e.api_key=this.api_key||``,e}constructor(e){v(this,`access_token`,null),v(this,`image_base64`,null),v(this,`error`,null),v(this,`currency_code`,null),v(this,`payment_method_code`,``),v(this,`codename`,null),v(this,`name_abbrev`,null),v(this,`name`,``),v(this,`enable_drawer`,!1),v(this,`enable_receipt`,!0),v(this,`image_url`,``),v(this,`is_cash`,!1),v(this,`is_integrated`,!1),v(this,`is_disabled`,!1),v(this,`type`,0),v(this,`api_id`,null),v(this,`api_key`,null),v(this,`timestamp_create`,Date.now()),v(this,`timestamp_update`,Date.now()),e&&Object.assign(this,e)}};let nt=function(e){return e.STARTED=`payment_started`,e.COMPLETED=`payment_completed`,e.FAILED=`payment_failed`,e.CANCELLED=`payment_cancelled`,e}({});var rt=class extends T{constructor(){super()}},it=class extends rt{constructor(){super()}},at=class extends T{constructor(){super(),v(this,`note_group_uid`,``),v(this,`related_model`,oe.Invoice),v(this,`usage`,0)}},ot=class extends at{constructor(){super()}};let st=function(e){return e.DineIn=`dine_in`,e.TakeOut=`take_out`,e.Delivery=`delivery`,e}({}),ct=function(e){return e.PayToOrder=`pay_to_order`,e.OrderFirstAndPayLater=`order_first_and_pay_later`,e.OnSelection=`on_selection`,e}({}),lt=function(e){return e.Inclusive=`inclusive`,e.Exclusive=`exclusive`,e}({}),U=function(e){return e.Open=`open`,e.OnHold=`on_hold`,e.Paying=`paying`,e.Paid=`paid`,e.Void=`void`,e.PayAtCounter=`pay_at_counter`,e}({}),ut=function(e){return e.Calibration=`calibration`,e.Create=`create`,e.Update=`update`,e.Cancel=`cancel`,e.Hold=`hold`,e.PaymentAsync=`payment_async`,e.Check=`check`,e.Void=`void`,e.Switch=`switch`,e.Reprint=`reprint`,e.Display=`display`,e.Merge=`merge`,e.Calculate=`calculate`,e.Delivery=`delivery`,e.Payment=`payment`,e.ChangePayment=`change_payment`,e.AddCustomer=`add_customer`,e.VoidAndDuplicate=`void_and_duplicate`,e.Duplicate=`duplicate`,e.PayAtCounter=`pay_at_counter`,e.PayInvoice=`pay_invoice`,e.SettleOnlineDeliveryOrder=`settle_online_delivery_order`,e}({}),dt=function(e){return e.quantity=`quantity`,e.weight=`weight`,e}({}),W=function(e){return e.Flat=`flat`,e.Percent=`percent`,e}({}),G=function(e){return e.AfterSubtotal=`after_subtotal`,e.AfterServiceCharge=`after_service_charge`,e.AfterGrantTotal=`after_grant_total`,e}({}),ft=function(e){return e.Custom=`custom`,e.Voucher=`voucher`,e.Coupon=`coupon`,e}({});var pt=class{constructor(){v(this,`uid`,E.InvoiceCharge+t()),v(this,`name`,``),v(this,`percentage`,0),v(this,`amount`,0),v(this,`calc_flow`,G.AfterSubtotal)}},mt=class{constructor(){v(this,`action`,ut.Create),v(this,`action_by`,``),v(this,`device_uid`,``),v(this,`action_at`,new Date)}},ht=class{constructor(){v(this,`uid`,E.Charge+t()),v(this,`name`,``),v(this,`percent`,0),v(this,`calc_flow`,G.AfterSubtotal),v(this,`trigger_condition`,``)}},gt=class{constructor(){v(this,`calc_type`,W.Flat),v(this,`amount`,0),v(this,`percent`,0),v(this,`percent_amount`,0),v(this,`type`,ft.Custom),v(this,`calc_flow`,G.AfterSubtotal),v(this,`applying_item_uids`,[]),v(this,`name`,``),v(this,`name_translation`,{}),v(this,`voucher_uid`,``),v(this,`coupon_uid`,``),v(this,`uid`,E.InvoiceDiscount+t())}},_t=class{constructor(){v(this,`item_uid`,``),v(this,`item`,new Se),v(this,`price`,0),v(this,`unit_of_measure`,dt.quantity),v(this,`quantity`,0),v(this,`sent`,0),v(this,`kds_done`,0),v(this,`kds_prepared`,0),v(this,`kds_batch`,0),v(this,`is_cancel_printed`,!1),v(this,`is_cancel_slip_printed`,!1),v(this,`selected`,!1),v(this,`sales_user_uid`,``),v(this,`salespersons`,void 0),v(this,`is_auto_applied`,!1)}},vt=class extends w{constructor(){super(),v(this,`item_uid`,``),v(this,`price`,0),v(this,`unit_of_measure`,dt.quantity),v(this,`quantity`,0),v(this,`remark`,``),v(this,`invoice_uid`,``),v(this,`discount_calc_type`,W.Flat),v(this,`discount_amount`,0),v(this,`discount_percent`,0),v(this,`subtotal`,0),v(this,`subtotal_before_discount`,0),v(this,`item`,new Ce),v(this,`point`,0),v(this,`point_subtotal`,0),v(this,`up_size`,!1),v(this,`is_take_out`,!1),v(this,`is_duplicate`,!1),v(this,`is_combo`,!1),v(this,`is_combo_item`,!1),v(this,`combo_group_uid`,``),v(this,`combo_line_uid`,``),v(this,`modifiers`,[]),v(this,`duplicated_from_uid`,``),v(this,`sent`,0),v(this,`kds_done`,0),v(this,`kds_prepared`,0),v(this,`kds_batch`,0),v(this,`is_cancel_printed`,!1),v(this,`is_cancel_slip_printed`,!1),v(this,`selected`,!1),v(this,`sales_user_uid`,``),v(this,`salespersons`,void 0),v(this,`meta`,{}),v(this,`attached_to_line_uid`,void 0)}},yt=class extends w{constructor(){super(),v(this,`ref_id`,``),v(this,`call_num`,``),v(this,`table_uid`,``),v(this,`table_name`,``),v(this,`type`,st.DineIn),v(this,`pax`,0),v(this,`adult_pax`,0),v(this,`child_pax`,0),v(this,`baby_pax`,0),v(this,`subtotal`,0),v(this,`point_subtotal`,0),v(this,`service_chargeable_subtotal`,0),v(this,`discountable_subtotal`,0),v(this,`service_charge`,0),v(this,`delivery_id`,0),v(this,`delivery_charge`,0),v(this,`delivery_type`,``),v(this,`delivery_by`,``),v(this,`use_customer_point`,!1),v(this,`add_point`,0),v(this,`minus_point`,0),v(this,`rewarded_point_rate`,0),v(this,`rewarded_point`,0),v(this,`use_customer_balance`,!1),v(this,`add_credit`,0),v(this,`minus_credit`,0),v(this,`rewarded_credit_rate`,0),v(this,`rewarded_credit`,0),v(this,`discounts`,[]),v(this,`discount_amount`,0),v(this,`tax`,0),v(this,`rounding`,0),v(this,`tip`,0),v(this,`grand_total`,0),v(this,`customer_id`,0),v(this,`remark`,``),v(this,`sales_user_uid`,``),v(this,`salespersons`,void 0),v(this,`status`,U.Open),v(this,`paid_at`,new Date(0)),v(this,`voided_at`,new Date(0)),v(this,`humanized_paid_at`,``),v(this,`humanized_voided_at`,``),v(this,`humanized_created_at`,``),v(this,`order_id`,0),v(this,`to_address`,new y),v(this,`payment_source_method`,``),v(this,`payment_source_last4`,``),v(this,`payment_source_charge_ref`,``),v(this,`is_sales_exclusive`,!1),v(this,`etc`,{}),v(this,`action`,void 0),v(this,`lines`,[]),v(this,`deleted_lines`,[]),v(this,`payment_has_cash`,!1),v(this,`payments`,[]),v(this,`table_switch_id`,0),v(this,`employee_uid`,``),v(this,`employee_name`,``),v(this,`receipt_print_override`,!1),v(this,`customer`,new x),v(this,`is_duplicate`,!1),v(this,`kitchen_print_override`,!1),v(this,`otp`,``),v(this,`activities`,[]),v(this,`receipt_print_job_uid`,``),v(this,`kitchen_print_job_uids`,[]),v(this,`label_print_job_uids`,[]),v(this,`order_print_job_uids`,[]),v(this,`charges`,[]),v(this,`is_charge_triggered`,!1),v(this,`uid`,E.Invoice+t()),v(this,`meta`,{}),v(this,`price_lookup_key`,``)}},bt=class extends w{constructor(){super(),v(this,`user_uid`,void 0),v(this,`name`,void 0),v(this,`email`,void 0),v(this,`password`,void 0),v(this,`uid`,E.Employee+t()),v(this,`role_uid`,``),v(this,`language`,`en`),v(this,`can_login`,!0)}},xt=class extends w{constructor(){super(),v(this,`config`,new Mt),v(this,`cache`,new St),v(this,`storage`,{pricing_lookup_keys:[],pay_in_reasons:[],pay_out_reasons:[]})}},St=class{constructor(){v(this,`printers`,[])}},Ct=class{constructor(){}},wt=class{constructor(){v(this,`enable_appointment_module`,!1)}},Tt=class{constructor(){v(this,`enable_price_tiers`,!1),v(this,`rewarded_credit_rate`,0),v(this,`rewarded_point_rate`,0),v(this,`inclusive_service_charge`,!1),v(this,`inclusive_tax`,!1),v(this,`default_country_code`,`+65`),v(this,`disable_member_price_prompt`,!1),v(this,`disable_member_price_on_credit_payment`,!1)}},Et=class{constructor(){v(this,`enabled`,!1),v(this,`full_screen_assets`,[]),v(this,`half_screen_assets`,[]),v(this,`is_logo_hidden`,!1),v(this,`order_list_font_size`,`1.875rem`),v(this,`order_modifier_font_size`,`1.25rem`),v(this,`screen_width`,1024),v(this,`screen_height`,768),v(this,`order_display_duration`,60),v(this,`language`,`en`)}};let Dt=function(e){return e.SmoochPay=`SPCD`,e.YeahPay=`YEAP`,e.Shouqianba=`CRES`,e}({}),Ot=function(e){return e.YeahPayWechat=`YPWP`,e.YeahPayWechatOnline=`YPWO`,e.Shouqianba=`WCPH`,e}({}),kt=function(e){return e.YeahPayAlipay=`YPAP`,e.YeahPayAlipayOnline=`YPAO`,e.Shouqianba=`ALPH`,e}({});var At=class{constructor(){v(this,`takeaway_only`,!1),v(this,`guest_order_only`,!1),v(this,`disable_paynow_payment`,!1),v(this,`disable_card_payment`,!1),v(this,`disable_wechat_payment`,!1),v(this,`disable_alipay_payment`,!1),v(this,`disable_receipt_printer_receipt`,!1),v(this,`enable_grabfood_dinein`,!1),v(this,`landing_image`,``),v(this,`menu_banner_image`,``),v(this,`home_page_images`,[]),v(this,`paynow_method`,Nt.WyoPaynow),v(this,`card_payment_code`,Dt.SmoochPay),v(this,`wechat_method`,Ot.YeahPayWechat),v(this,`alipay_method`,kt.YeahPayAlipay)}},jt=class{constructor(){v(this,`point`,{sms_notification:!1,above_invoice_amount:0,conversion_rate:0,inclusive_service_charge:!1,inclusive_tax:!1}),v(this,`credit`,{sms_notification:!1,above_invoice_amount:0,conversion_rate:0,inclusive_service_charge:!1,inclusive_tax:!1})}},Mt=class{constructor(){v(this,`general`,new Rt),v(this,`product`,new Lt),v(this,`till`,new zt),v(this,`report`,new Bt),v(this,`receipt`,new Vt),v(this,`kitchen`,new Ht),v(this,`kds`,new Ut),v(this,`label`,new Wt),v(this,`order`,new Gt),v(this,`ods`,new Kt),v(this,`payment`,new qt),v(this,`user`,new Jt),v(this,`tax`,new Yt),v(this,`rounding`,new Qt),v(this,`inventory`,new $t),v(this,`pax_config`,new en),v(this,`gto`,new tn),v(this,`cash_drawer`,new nn),v(this,`marketing`,new jt),v(this,`charges`,new Xt),v(this,`currency`,new Zt),v(this,`cds`,new Et),v(this,`kiosk`,new At),v(this,`online_order`,new Pt),v(this,`loyalty_program`,new Tt),v(this,`crm`,new Ct),v(this,`system`,new wt)}};let Nt=function(e){return e.FomoOnlinePaynow=`PNWO`,e.WyoPaynow=`WPPN`,e.YeahPayPaynow=`YPPN`,e}({});var Pt=class{constructor(){v(this,`enable_membership`,!1),v(this,`login_call_to_action_text`,``),v(this,`menu_banner_image_url`,``),v(this,`menu_popup_image_url`,``),v(this,`paynow_method`,void 0),v(this,`disable_pay_at_counter`,!1),v(this,`disable_verify_at_counter`,!1),v(this,`disable_paynow_payment`,!1),v(this,`default_language`,`en`),v(this,`category_selector_mode`,`photo_mode`),v(this,`dynamic_order_qr`,{default_order_flow:ct.OrderFirstAndPayLater,select_order_flow:!1,select_menus:!1,expiry_in_minutes:0}),v(this,`max_dining_time`,0),v(this,`disable_logo_for_item_photo_fallback`,!1),v(this,`whatsapp_login_only`,!1),v(this,`enable_whatsapp_login`,!1),v(this,`assets`,{}),v(this,`disable_order_remark`,!1),v(this,`disable_order_now_when_closed`,!1)}};let Ft=function(e){return e.PROD=`prod`,e.DEV=`dev`,e}({});const It=e=>e===`compact`||e===`rectangle`?e:`square`;var Lt=class{constructor(){v(this,`enable_codename_search`,!1),v(this,`item_name_font_size`,14),v(this,`item_name_bg_opacity`,75),v(this,`category_button_shape`,`square`)}},Rt=class{constructor(){v(this,`company_name`,``),v(this,`company_name_alias`,``),v(this,`company_logo`,``),v(this,`company_tax_reg_no`,``),v(this,`company_postcode`,``),v(this,`company_address`,``),v(this,`company_country`,``),v(this,`company_tel`,``),v(this,`business_day_cutoff_hour`,0),v(this,`floor_plan_table_name`,`table`),v(this,`deploy_channel`,Ft.PROD),v(this,`language`,`en`),v(this,`debug`,!1),v(this,`logging`,!1),v(this,`offline_mode`,!1),v(this,`opening_schedules`,[{opening_hours:{open:`10:00`,close:`22:00`}}])}},zt=class{constructor(){v(this,`control`,!0),v(this,`slip`,!0),v(this,`auto_start_shift`,!1),v(this,`auto_shift_amount`,0)}},Bt=class{constructor(){v(this,`itemized_consolidated`,!0),v(this,`itemized_separated`,``),v(this,`shift_itemized`,!0),v(this,`start_time`,`09:00:01`),v(this,`end_time`,`23:59:59`),v(this,`shift_print_time`,1),v(this,`shift_disable`,!1),v(this,`email`,!1),v(this,`day_boundary_offset`,0)}},Vt=class{constructor(){v(this,`enabled`,!0),v(this,`show_print_dialog`,!1),v(this,`print_docket`,!1),v(this,`print_cancel_slip`,!1),v(this,`print_cancel_whole_invoice`,!1),v(this,`hide_non_price_item`,!1),v(this,`receipt_no_reset_daily`,!1),v(this,`language`,`en`),v(this,`disable_persistent_tcp`,!1)}},Ht=class{constructor(){v(this,`enabled`,!0),v(this,`print_item_price`,!1),v(this,`print_cancel_slip`,!1),v(this,`print_cancel_whole_invoice`,!1),v(this,`language`,`en`)}},Ut=class{constructor(){v(this,`enabled`,!0),v(this,`display_order_after_payment`,!1),v(this,`print_slip_upon_completed`,!1),v(this,`warn_mins`,30),v(this,`over_mins`,45),v(this,`color_normal`,`#409CD5`),v(this,`color_warning`,`#CB8336`),v(this,`color_overdue`,`#E53030`),v(this,`color_completed`,`#538235`),v(this,`enable_kds_status_on_pos`,!1)}},Wt=class{constructor(){v(this,`print`,!1),v(this,`text_to_raster`,!1)}},Gt=class{constructor(){v(this,`separation_line`,!1),v(this,`slip`,!0),v(this,`slip_font_size_ratio`,1),v(this,`max_dinning`,0),v(this,`exit_menu_after_payment`,!1),v(this,`hide_combo_item_on_receipt`,!1),v(this,`hide_combo_item_on_interactive_view`,!1),v(this,`hide_categories_when_ordering`,!1),v(this,`end_shift_with_open_tables`,!1),v(this,`datetime_format`,`YYYY-MMM-DD HH:mm:ss`),v(this,`ref_prefix`,`01`),v(this,`always_show_modifier`,!0),v(this,`enable_quick_check_button`,!1),v(this,`clear_order_note_on_add_item`,!1),v(this,`order_font_size`,14),v(this,`booking_slot_limit`,0),v(this,`booking_use_real_table`,!1),v(this,`booking_simple_mode`,!1)}},Kt=class{constructor(){v(this,`enabled`,!1),v(this,`language`,`en`)}},qt=class{constructor(){v(this,`quick_cash_payment`,!1),v(this,`notification`,!0),v(this,`quick`,!1),v(this,`payment_auto_redirect_seconds`,5)}},Jt=class{constructor(){v(this,`control`,!0)}},Yt=class{constructor(){v(this,`enabled`,!0),v(this,`method`,lt.Inclusive),v(this,`rate`,7),v(this,`name`,`GST`)}},Xt=class{constructor(){v(this,`service_charge`,!1),v(this,`service_charge_rate`,10)}},Zt=class{constructor(){v(this,`currency_symbol`,`$`),v(this,`is_symbol_after_amount`,!1)}},Qt=class{constructor(){v(this,`base`,.1),v(this,`up`,!0),v(this,`cashless`,!1),v(this,`prepayment_rounding`,!1)}},$t=class{constructor(){v(this,`inventory_control`,!1),v(this,`sold_out_for_today_only`,!1)}},en=class{constructor(){v(this,`pax`,!0),v(this,`detail`,!1)}},tn=class{constructor(){v(this,`interface`,``),v(this,`genesis_date`,``),v(this,`upload_time`,``),v(this,`ftp_svr`,``),v(this,`ftp_usr`,``),v(this,`ftp_port`,``),v(this,`ftp_path`,``),v(this,`ftp_pwd`,``),v(this,`mall_id`,``),v(this,`machine_id`,``),v(this,`ftp_type`,`ftp`)}},nn=class{constructor(){v(this,`kick_code`,`27, 112, 48, 55, 121`),v(this,`connection_mode`,`via_receipt_printer`)}},rn=class{constructor(e){v(this,`name`,``),v(this,`base64`,``),v(this,`extension`,`png`),Object.assign(this,e)}};const an=e=>e===``||e===void 0,on=e=>t=>an(e)||t.includes(e),sn=e=>t=>an(e)||e.includes(t),cn=(e,t)=>n=>n>e&&n<t,ln=e=>typeof e==`function`?(t,n)=>!e(t,n):t=>t!=e,un=e=>e,dn=e=>t=>!t.deleted_at&&Object.keys(e).every(n=>{if(an(e[n])||t[n]===e[n])return!0;if(typeof e[n]==`function`)return e[n](t[n],t)});var fn=class{constructor(){v(this,`db`,void 0),v(this,`moduleName`,void 0)}get table(){return this.db.table(this.moduleName)}liveQuery(e){return i(e)}async saveOne(e){let n={...e};return n.created_at||(n.created_at=new Date),n.uid||(n.uid=t()),n.updated_at=new Date,await this.db.table(this.moduleName).put(n),n}async saveMany(e){let n=e.map(e=>(e.uid||(e.uid=t(),e.created_at=new Date),e.updated_at=new Date,e));return await this.db.table(this.moduleName).bulkPut(n),n}async hasAny(){return await this.db.table(this.moduleName).count()>0}async getOne(e){return await this.db.table(this.moduleName).get(e)||null}async getOneByParams(e){return this.db.table(this.moduleName).filter(dn(e)).first()}async getDefaultOne(){return this.moduleName?this.db.table(this.moduleName).filter(e=>e.deleted_at===null||e.deleted_at===void 0).first():null}async getAll(){return this.db.table(this.moduleName).toArray()}async getMany(e={},t={}){let{page:n=1,pageSize:r=10,...i}=t||{},a=await this.db.table(this.moduleName).filter(dn(e)).count(),o=this.db.table(this.moduleName).filter(dn(e));return r!==-1&&o.offset((n-1)*r).limit(r),{list:await o.toArray(),count:a,page:n,pageSize:r}}},pn=class extends fn{async updateOne(e,t){throw Error(`Method not implemented.`)}async deleteOne(e){throw Error(`Method not implemented.`)}},K=class extends fn{constructor(...e){super(...e),v(this,`http`,void 0),v(this,`methodName`,void 0),v(this,`options`,void 0)}async addOne(e){return this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${this.methodName}`,e)}async updateOne(e,t){return this.http.patch(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${e}`,t)}async updateMany(e){return this.http.patch(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}`,e)}async deleteOne(e){return e.deleted_at=new Date,this.http.delete(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${e.id_in_server}`)}async hardDeleteOne(e){return await this.db.table(this.moduleName).delete(e.uid),e}};let mn=function(e){return e[e.printable=0]=`printable`,e[e.generative=1]=`generative`,e}({});var hn=class{constructor(){v(this,`uid`,E.ReportCategory+ +t()),v(this,`name`,``),v(this,`name_translations`,{}),v(this,`reports`,[]),v(this,`created_at`,new Date),v(this,`created_at_timestamp`,new Date().getTime()),v(this,`updated_at`,new Date),v(this,`deleted_at`,null)}},gn=class{constructor(){v(this,`uid`,E.Report+t()),v(this,`name`,``),v(this,`name_translations`,{}),v(this,`type`,void 0),v(this,`codename`,``),v(this,`created_at`,new Date),v(this,`created_at_timestamp`,new Date().getTime()),v(this,`updated_at`,new Date),v(this,`deleted_at`,null)}},_n=class extends w{constructor(){super(),v(this,`uid`,E.AppReport+t()),v(this,`reports`,[]),v(this,`version`,1)}},vn=class{constructor(){v(this,`start_datetime`,``),v(this,`humanized_start_datetime`,``),v(this,`end_datetime`,``),v(this,`humanized_end_datetime`,``),v(this,`humanized_printed_datetime`,``),v(this,`sales_summary`,new yn),v(this,`drawer_summary`,new bn),v(this,`payments_summary`,[]),v(this,`loyalty_program_summary`,new Sn),v(this,`item_sales_summary`,[]),v(this,`item_sales_summary_total`,0),v(this,`item_sales_summary_total_count`,0),v(this,`item_sales_summary_by_category`,[]),v(this,`modifier_sales_summary`,[]),v(this,`modifier_sales_summary_total`,0),v(this,`modifier_sales_summary_total_count`,0),v(this,`config`,{}),v(this,`invoice_discount_summary`,[]),v(this,`item_discount_summary`,[])}},yn=class{constructor(){v(this,`sales_total`,0),v(this,`foc_sales_total`,0),v(this,`foc_sales_count`,0),v(this,`foc_rounding_total`,0),v(this,`foc_tax_total`,0),v(this,`foc_service_charge_total`,0),v(this,`rounding_total`,0),v(this,`tax_total`,0),v(this,`service_charge_total`,0),v(this,`discount_total`,0),v(this,`voucher_total`,0),v(this,`voucher_count`,0),v(this,`coupon_total`,0),v(this,`coupon_count`,0),v(this,`paid_invoice_count`,0),v(this,`paid_invoice_total`,0),v(this,`void_invoice_count`,0),v(this,`void_invoice_total`,0),v(this,`total_pax`,0),v(this,`pax_sales_total`,0)}},bn=class{constructor(){v(this,`open_amount`,0),v(this,`declared_amount`,0),v(this,`drawer_amount`,0),v(this,`difference`,0),v(this,`pay_in_total`,0),v(this,`pay_in_count`,0),v(this,`cash_invoice_total`,0),v(this,`cash_invoice_count`,0),v(this,`pay_out_total`,0),v(this,`pay_out_count`,0)}},xn=class{constructor(){v(this,`code`,``),v(this,`name`,``),v(this,`total`,0),v(this,`count`,0)}},Sn=class{constructor(){v(this,`add_credit_total`,0),v(this,`add_credit_count`,0),v(this,`topup_paid_total`,0),v(this,`topup_paid_count`,0),v(this,`rewarded_credit_total`,0),v(this,`rewarded_credit_count`,0),v(this,`minus_credit_total`,0),v(this,`minus_credit_count`,0),v(this,`rewarded_point_total`,0),v(this,`rewarded_point_count`,0),v(this,`minus_point_total`,0),v(this,`minus_point_count`,0)}},Cn=class{constructor(){v(this,`item`,{}),v(this,`quantity`,0),v(this,`total_amount`,0),v(this,`modifiers`,[])}},wn=class{constructor(){v(this,`item`,{}),v(this,`quantity`,0),v(this,`total_amount`,0)}},Tn=class{constructor(){v(this,`category`,null),v(this,`items`,[]),v(this,`total_quantity`,0),v(this,`total_amount`,0)}},En=class extends K{constructor(e,t,n,r=`printers`,i=`printer`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i,v(this,`configService`,void 0),v(this,`printJobService`,void 0),v(this,`printersFromCache`,void 0),this.configService=new Br(e,t,n,`configs`,`config`),this.printJobService=new Xr(e,t,n,`print_jobs`,`print_job`),this.init().catch(e=>console.error(e))}async init(){this.printersFromCache||(this.printersFromCache=(await this.configService.getDefaultOne())?.cache?.printers??[])}async getPhysicalPrintersFromNode(){return(await this.http.get(`api/v5/merchants/`+this.options.merchant_uid+`/`+this.moduleName+`/get_physical_printers`)).data}async getUnpairedNode(){return this.http.get(`api/v5/merchants/`+this.options.merchant_uid+`/node`)}async pairNode(e){return this.http.get(`api/v5/merchants/`+this.options.merchant_uid+`/nodes/${e}/pair-node`)}async getDefaultPrinter(e){let t=await this.db.table(`printers`).filter(t=>t.type===e&&t.deleted_at==null).toArray();return t.find(e=>!e.is_not_default)||t[0]||null}async getDefaultReceiptPrinter(){return this.getDefaultPrinter(z.ReceiptPrinter)}async getDefaultPrinterByType(e){return this.getDefaultPrinter(e)}async getDefaultKioskPrinter(){return this.getDefaultPrinter(z.KioskPrinter)}async getDefaultCheckPrinter(){return this.getDefaultPrinter(z.CheckPrinter)}async getDefaultKitchenPrinter(){return this.getDefaultPrinter(z.KitchenPrinter)}async getDefaultOrderPrinter(){return this.getDefaultPrinter(z.OrderPrinter)}async getDefaultKitchenDisplayPrinter(){return this.getDefaultPrinter(z.KitchenDisplayPrinter)}async getPrintersByUids(e){return this.db.table(`printers`).where(`uid`).anyOf(e).filter(e=>e.deleted_at==null).toArray()}async searchPrinters(e=!1,t=9100){if(this.printersFromCache&&!e)return this.printersFromCache;let n=[],r=await u.getWiFiIPAddress();console.log(`ipAddress`,r);let i=r.subnet.split(`.`).map(Number),a=r.ip.split(`.`).map(Number);a[3]=0;let o=i.reduce((e,t,n)=>e+(t^255)*256**(3-n),0);for(let e=1;e<o;e++){let r=[...a],i=3,o=e;for(;o>0;){let e=o%256;for(o=Math.floor(o/256),r[i]+=e;r[i]>254&&i>0;)r[i]-=256,r[--i]++}let s=r.join(`.`);console.log(`ip`,s),await new Me().connect(s,t,200)&&n.push(s)}return await this.configService.updateCache({printers:n}),n}async openCashDrawer(){let e=await this.getDefaultReceiptPrinter(),t=new L;t.items.push({type:I.OpenCashDrawer});let n=new V(e,t,!1,1);await this.printJobService.addOne(n)}};function q(e,t=2){let n=10**t;return Math.round(e*n)/n}function Dn(e){let t=e.name,n=t.lastIndexOf(`.`);return n===-1||n===t.length-1?``:t.slice(n+1)}function On(e){return new Promise((t,n)=>{let r=new FileReader;r.onloadend=()=>{typeof r.result==`string`?t(r.result.split(`,`)[1]):n(Error(`Could not convert file to Base64.`))},r.onerror=()=>n(Error(`File reading failed.`)),r.readAsDataURL(e)})}const J=(e,t)=>e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/[_\-\.]+/g,` `).toLowerCase().replace(/[\s]+(\w)/g,(e,n)=>t(n)),kn=e=>e.replace(/^\W+|\W+$/g,``),An=e=>typeof e==`string`?J(e,e=>e.toUpperCase()):``,jn=e=>typeof e==`string`?e.charAt(0).toUpperCase()+e.slice(1):``,Mn=e=>typeof e==`string`?e.replace(/\w\S*/g,e=>jn(e)):``,Nn=e=>typeof e==`string`?J(e,e=>`-`+e):``,Pn=e=>typeof e==`string`?J(e,e=>`.`+e):``,Fn=e=>In(e),In=e=>typeof e==`string`?e.toLowerCase():``,Ln=e=>{if(typeof e!=`string`)return``;let t=J(e,e=>e.toUpperCase());return t.charAt(0).toUpperCase()+t.slice(1)},Rn=e=>typeof e==`string`?J(e,e=>`/`+e):``,zn=e=>typeof e==`string`?e.replace(/((?:\S[^\.\?\!]*)[\.\?\!]*)/g,e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()):``,Bn=e=>typeof e==`string`?J(e,e=>`_`+e):``,Vn=e=>typeof e==`string`?e.replace(/[- _]+/g,` `).split(` `).map(e=>jn(e)).join(` `):``,Hn=e=>Un(e),Un=e=>typeof e==`string`?e.toUpperCase():``,Wn=(e,t)=>typeof e==`string`&&typeof t==`string`?e+t:e,Gn=(e,t)=>{if(typeof e!=`string`)return``;let n=``;for(let e=0;e<t;e++)n+=` `;return n+e+n},Kn=e=>typeof e==`string`?kn(e):``,qn=e=>typeof e==`string`?e.split(` `).join(`-`):``,Jn=(e,t=` `)=>typeof e==`string`?(typeof t!=`string`&&(t=` `),e.split(t).join(`+`)):``,Yn=(e,t)=>typeof e==`string`&&typeof t==`string`?t+e:e,Xn=(e,t)=>typeof e==`string`?typeof t==`string`?e.split(t).join(``):e:``,Zn=(e,t)=>typeof e==`string`?typeof t==`string`?e.replace(t,``):e:``,Qn=(e,t,n)=>typeof e==`string`?typeof t==`string`?(typeof n!=`string`&&(n=``),e.split(t).join(n)):e:``,$n=(e,t,n)=>typeof e==`string`?typeof t==`string`?(typeof n!=`string`&&(n=``),e.replace(t,n)):e:``,er=e=>typeof e==`string`?e.split(``).reverse().join(``):``,tr=(e,t=`,`)=>typeof e==`string`?(typeof t!=`string`&&(t=`,`),e.split(t)):[],nr=(e,t)=>typeof e==`string`?e.length<=t?e:or(e,t)+`…`:``,rr=e=>typeof e==`string`?e.trim():``,ir=e=>typeof e==`string`?e.replace(/^\s+/,``):``,ar=e=>typeof e==`string`?e.replace(/\s+$/,``):``,or=(e,t,n=``)=>typeof e==`string`?(typeof n!=`string`&&(n=``),e.length>t?e.slice(0,t-n.length)+n:e):``;var sr={camelcase:An,capitalize:jn,capitalizeAll:Mn,dashcase:Nn,dotcase:Pn,downcase:Fn,lowercase:In,pascalcase:Ln,pathcase:Rn,sentence:zn,snakecase:Bn,titleize:Vn,upcase:Hn,uppercase:Un,append:Wn,center:Gn,chop:Kn,hyphenate:qn,plusify:Jn,prepend:Yn,remove:Xn,removeFirst:Zn,replace:Qn,replaceFirst:$n,reverse:er,split:tr,ellipsis:nr,trim:rr,trimLeft:ir,trimRight:ar,truncate:or,truncateWords:(e,t,n=`…`)=>{if(typeof e==`string`&&typeof t==`number`){typeof n!=`string`&&(n=`…`);let r=e.split(/[ \t]/);return(t>r.length?r:r.slice(0,t)).join(` `).trim()+n}return``},isString:e=>typeof e==`string`,occurrences:(e,t)=>{if(typeof e!=`string`)return 0;let n=t.length,r=0,i=0;for(;(r=e.indexOf(t,r))>-1;)i++,r+=n;return i}};const cr=e=>e&&typeof e==`object`&&typeof e.fn==`function`,Y=(e,t,n)=>cr(n)?e?n.fn?n.fn(t):!0:n.inverse?n.inverse(t):!1:e,lr=function(...e){let t=e.pop();return Y(e.every(e=>!!e),this,t)},ur=function(...e){let t=e.pop();return Y(e.some(e=>!!e),this,t)},dr=function(e,t){return Y(!e,this,t)},fr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),Y(e===t,this,n)},pr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),Y(e==t,this,n)},mr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),Y(e!==t,this,n)},hr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),Y(e!=t,this,n)},gr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),Y(e>t,this,n)},_r=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),Y(e>=t,this,n)},vr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),Y(e<t,this,n)},yr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),Y(e<=t,this,n)},br=function(e,t,n,r){if(arguments.length<4)throw Error(`Helper {{compare}} expects 4 arguments`);let i;switch(t){case`==`:i=e==n;break;case`===`:i=e===n;break;case`!=`:i=e!=n;break;case`!==`:i=e!==n;break;case`<`:i=e<n;break;case`>`:i=e>n;break;case`<=`:i=e<=n;break;case`>=`:i=e>=n;break;case`typeof`:i=typeof e===n;break;default:throw Error(`Helper {{compare}}: invalid operator: \`${t}\``)}return Y(i,this,r)},xr=function(e,t,n){return typeof n==`number`&&(n=arguments[3]),Y(e==null?!1:Array.isArray(e)||typeof e==`string`?e.includes(t):typeof e==`object`?t in e:!1,this,n)},Sr=xr,Cr=function(e,...t){let n=t.pop();return Y(t.includes(e),this,n)},wr=(e,t)=>{if(!(!e||!t))return t.split(`.`).reduce((e,t)=>e?.[t],e)},Tr=e=>{let t=[];for(let n=0;n<e.length-1;n+=2)typeof e[n]==`string`&&!cr(e[n+1])&&t.push({prop:e[n],value:e[n+1]});return t};var Er={and:lr,or:ur,not:dr,eq:fr,is:pr,neq:mr,isnt:hr,gt:gr,gte:_r,lt:vr,lte:yr,compare:br,contains:xr,includes:Sr,in:Cr,findAnd:function(e,...t){if(!Array.isArray(e))return null;let n=Tr(t);return e.find(e=>n.every(t=>wr(e,t.prop)===t.value))||null},findOr:function(e,...t){if(!Array.isArray(e))return null;let n=Tr(t);return e.find(e=>n.some(t=>wr(e,t.prop)===t.value))||null},filterAnd:function(e,...t){if(!Array.isArray(e))return[];let n=Tr(t);return e.filter(e=>n.every(t=>wr(e,t.prop)===t.value))},filterOr:function(e,...t){if(!Array.isArray(e))return[];let n=Tr(t);return e.filter(e=>n.some(t=>wr(e,t.prop)===t.value))},default:function(...e){for(let t=0;t<e.length-1;t++)if(e[t]!=null)return e[t];return``},neither:function(e,t,n){return Y(!e&&!t,this,n)},ifEven:function(e,t){return Y(e%2==0,this,t)},ifOdd:function(e,t){return Y(e%2!=0,this,t)},ifNth:function(e,t,n){return Y(typeof e==`number`&&typeof t==`number`&&t%e===0,this,n)}};function Dr(e){let t=e?.handlebars||e?.hbs||m(`handlebars`);return Object.keys(sr).forEach(e=>{t.registerHelper(e,sr[e])}),Object.keys(Er).forEach(e=>{t.registerHelper(e,Er[e])}),t.helpers}var Or=Dr,kr=class extends w{constructor(){super(),v(this,`uid`,E.OrderDisplaySystem+t()),v(this,`order_number`,``),v(this,`status`,X.Preparing)}};let X=function(e){return e.Preparing=`preparing`,e.ReadyForPickup=`ready_for_pickup`,e}({});var Ar=class extends K{constructor(e,t,n,r=`order_displays`,i=`order_display`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async toPickUp(e){let t=await this.getOne(e);if(!t)throw new D(`Display order not found`);if(t.status==`ready_for_pickup`)throw new D(`Order is already ready for pickup`);if(t.status=X.ReadyForPickup,t.updated_at=new Date,t.id_in_server==0)throw new D(`Order is not synced with server`);return await this.updateOne(t.id_in_server,t),t}async toPreparing(e){let t=await this.getOne(e);if(!t)throw new D(`Display order not found`);if(t.status==`preparing`)throw new D(`Order is already preparing`);if(t.status=X.Preparing,t.updated_at=new Date,t.id_in_server==0)throw new D(`Order is not synced with server`);return await this.updateOne(t.id_in_server,t),t}async undo(){let e=await this.db.table(this.moduleName).filter(e=>e.status==X.ReadyForPickup).reverse().limit(100).toArray();if(e.length===0)throw new D(`No order to undo`);e.sort((e,t)=>{let n=new Date(e.updated_at).getTime();return new Date(t.updated_at).getTime()-n});let t=e[0];if(t.status=X.Preparing,t.updated_at=new Date,t.id_in_server==0)throw new D(`Order is not synced with server`);return await this.updateOne(t.id_in_server,t),t}};Or({handlebars:d});const jr={quantity:1,price:0,remark:``};var Mr=class extends K{constructor(e,t,n,r=`invoices`,i=`invoice`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i,v(this,`tillService`,void 0),v(this,`sectionItemService`,void 0),v(this,`sectionService`,void 0),v(this,`configService`,void 0),v(this,`printTemplateService`,void 0),v(this,`printerService`,void 0),v(this,`printJobService`,void 0),v(this,`itemService`,void 0),v(this,`orderDisplayService`,void 0),this.tillService=new Gr(e,t,n,`tills`,`till`),this.sectionItemService=new Hr(e,t,n,`section_items`,`section_item`),this.sectionService=new Vr(e,t,n,`sections`,`section`),this.configService=new Br(e,t,n,`configs`,`config`),this.printTemplateService=new Qr(e,t,n,`print_templates`,`print_template`),this.printerService=new En(e,t,n,`printers`,`printer`),this.printJobService=new Xr(e,t,n,`print_jobs`,`print_job`),this.itemService=new Rr(e,t,n,`items`,`item`),this.orderDisplayService=new Ar(e,t,n)}calculate(e,t,n=!1){if(e.lines==null||e.lines.length<1)return this.resetInvoiceCalculations(e),e;if(this.calculateLines(e),this.calculatePointSubtotal(e),this.calculateInvoiceServiceChargeableSubtotal(e),e.discount_amount=0,this.calculateDiscount(e,G.AfterSubtotal),e.grand_total<0&&(e.grand_total=0,e.service_chargeable_subtotal=0),this.calculateInvoiceCharges(e,G.AfterSubtotal),e.subtotal>0&&e.discount_amount>0){let t=1-e.discount_amount/e.subtotal;e.service_chargeable_subtotal=q(Math.max(0,e.service_chargeable_subtotal*t),2)}else e.discount_amount>=e.subtotal&&(e.service_chargeable_subtotal=0);let r=t.config.charges.service_charge?t.config.charges.service_charge_rate:0;this.calculateServiceCharge(e,r),this.calculateDiscount(e,G.AfterServiceCharge),e.grand_total<0&&(e.grand_total=0),this.calculateInvoiceCharges(e,G.AfterServiceCharge);let i=t.config.tax.enabled?t.config.tax.rate:0;return this.calculateTax(e,i,t.config.tax.method),this.calculateDeliveryCharge(e),this.calculateCreditDeduction(e),this.calculateTip(e),n?e.rounding=0:this.calculateRounding(e,t.config.rounding.base,t.config.rounding.up,t.config.rounding.cashless,t.config.rounding.nearest),this.calculateDiscount(e,G.AfterGrantTotal),e.grand_total<0&&(e.grand_total=0),this.calculateInvoiceCharges(e,G.AfterGrantTotal),e.grand_total=q(e.grand_total),e.rewarded_credit_rate=t.config?.loyalty_program?.rewarded_credit_rate??0,this.calculateRewardCredit(e,0,t.config?.loyalty_program?.inclusive_service_charge,t.config?.loyalty_program?.inclusive_tax),this.calculateAddCredit(e),this.calculateAddPoint(e),e.rewarded_point_rate=t.config?.loyalty_program?.rewarded_point_rate??0,this.calculateRewardPoint(e,t.config?.loyalty_program?.rewarded_point_rate,t.config?.loyalty_program?.inclusive_service_charge,t.config?.loyalty_program?.inclusive_tax),e.grand_total<0&&(e.grand_total=0),this.calculateChangeAmount(e),e}calculateLines(e){e.subtotal=0,e.point_subtotal=0;let t=0;for(let n of e.lines)this.calculateLine(n),t+=n.subtotal,e.subtotal+=q(n.subtotal,2),e.point_subtotal+=n.point_subtotal;e.subtotal=q(t,2),e.grand_total=q(e.subtotal,2)}calculateLine(e){this.resetLineCalculations(e),e.point_subtotal=e.quantity*e.point;let t=0;e.modifiers&&(t=e.modifiers.reduce((e,t)=>e+t.price*t.quantity,0)),e.subtotal=e.subtotal_before_discount=q(e.quantity*(e.price+t),2),e.item.discountable&&(e.discount_amount>0||e.discount_percent>0)&&(e.discount_calc_type==W.Flat||(e.discount_amount=q(e.subtotal*e.discount_percent,2)),e.subtotal-=e.discount_amount),e.subtotal=q(e.subtotal,2)}calculatePointSubtotal(e){if(e.point_subtotal=0,!(e.lines==null||e.lines.length<1)){for(let t of e.lines)t.point_subtotal=t.quantity*t.point,e.point_subtotal+=t.point_subtotal;e.minus_point=e.point_subtotal}}calculateInvoiceServiceChargeableSubtotal(e){(e.lines==null||e.lines.length<1)&&(e.service_chargeable_subtotal=0),e.service_chargeable_subtotal=q(q(e.lines.filter(e=>!e.is_take_out&&!e.item.is_service_charge_exempt).reduce((e,t)=>e+t.subtotal,0)),2)}calculateDiscount(e,t){if(!e?.lines?.length)return;let n=0;if(e.discountable_subtotal=q(e.lines.filter(e=>e.item.discountable).reduce((e,t)=>e+t.subtotal,0),2),e.discounts?.length){for(let r of e.discounts.filter(e=>e.calc_flow==t))if(!r.applying_item_uids?.length)r.calc_type==W.Flat?n+=r.amount:(r.percent_amount=q((e.discountable_subtotal-e.discount_amount-n)*r.percent),n+=r.percent_amount);else{let t=0,i=!1;for(let n of e.lines)r.applying_item_uids.includes(n.item_uid)&&n.price>t&&(t=n.price,i=!0);if(!i){e.discounts=e.discounts.filter(e=>e.uid!=r.uid);continue}r.calc_type==W.Flat?(r.amount=q(r.amount>t?t:r.amount),n+=r.amount):(r.percent_amount=q(t*r.percent),n+=r.percent_amount)}e.discount_amount+=q(n),e.grand_total=q(e.grand_total-n)}}calculateRounding(e,t,n,r,i){if(e.rounding=0,!t||!r&&!e.payment_has_cash)return;let a=(e.payments?.filter(e=>!e.payment_method?.is_cash)||[]).reduce((e,t)=>e+t.tender_amount-t.change_amount,0),o=a>0?e.grand_total-a:e.grand_total;e.rounding=q(this.roundingStep(o,t,n,i)),e.grand_total+=e.rounding}roundingStep(e,t,n,r){let i=Math.round(e*100),a=Math.round(t*100),o=i%a;if(o===0)return 0;let s;return s=r?o>=a/2?a-o:-o:n?a-o:-o,q(s/100)}calculateDeliveryCharge(e){e.delivery_charge>0&&e.type===st.Delivery&&(e.grand_total+=e.delivery_charge,e.grand_total=q(e.grand_total,2))}calculateServiceCharge(e,t){let n=0;e.service_charge=0,!(e.lines==null||e.lines.length<1)&&(e.type==st.Delivery||e.type==st.TakeOut||(t>0&&(n=e.service_chargeable_subtotal*(t/100)),e.service_charge=q(n,2),e.grand_total+=e.service_charge,e.grand_total=q(e.grand_total,2)))}calculateTax(e,t,n){if(e.tax=0,t<=0)return;let r=this.calculateTaxSubtotalRatio(e),i=e.grand_total-e.service_charge;n===lt.Inclusive?e.tax=q(i*r*t/(100+t)+e.service_charge*t/(100+t),2):(e.tax=q(i*r*t/100+e.service_charge*t/100,2),e.grand_total=q(e.grand_total+e.tax,2))}calculateCreditDeduction(e){e.minus_credit||(e.minus_credit=0),!(e.minus_credit<=0)&&(e.minus_credit=q(e.minus_credit),e.minus_credit>e.grand_total&&(e.minus_credit=q(e.grand_total)),e.grand_total=q(e.grand_total-e.minus_credit))}calculateTip(e){e.tip>0&&(e.grand_total=q(e.grand_total+e.tip,2))}calculateTaxSubtotalRatio(e){let t=1;return!e.lines||!e.lines.some(e=>e.item.is_tax_exempt)||e.grand_total===0||e.subtotal===0||(t=1-e.lines.filter(e=>e.item.is_tax_exempt).reduce((e,t)=>e+t.subtotal,0)/e.subtotal),t}calculateRewardCredit(e,t,n,r){if(e.rewarded_credit=0,e.grand_total<=0||t>0&&t>e.grand_total)return;let i=e.rewarded_credit_rate,a=e.grand_total;n||(a-=e.service_charge),r||(a-=e.tax),a-=e.lines.filter(e=>e.item.is_credit_reward_exempt).reduce((e,t)=>e+t.subtotal,0),e.rewarded_credit=q(a*i,2)}calculateAddCredit(e){let t=0;if(e.add_credit=0,!(!e.lines||e.lines.length<=0)){for(let n of e.lines.filter(e=>e.item.add_credit>0))t+=n.item.add_credit*n.quantity;e.add_credit=t}}calculateAddPoint(e){let t=0;if(e.add_point=0,!(!e.lines||e.lines.length<=0)){for(let n of e.lines.filter(e=>e.item.add_point>0))t+=n.item.add_point*n.quantity;e.add_point=t}}calculateRewardPoint(e,t,n,r){if(e.rewarded_point=0,e.rewarded_point_rate<=0||e.grand_total<=0)return;let i=e.grand_total;n||(i-=e.service_charge),r||(i-=e.tax),i-=e.lines.filter(e=>e.item.is_point_reward_exempt).reduce((e,t)=>e+t.subtotal,0),e.rewarded_point=Math.floor(i*e.rewarded_point_rate)}calculateDiscountFromTargetTotal(e,t,n){if(this.calculate(e,n),t>=e.grand_total)return 0;let r=n.config.rounding.base||.01,i=0,a=e.grand_total-t+r*10;for(;a-i>r/2;){let r=q((i+a)/2,2);if(r===i||r===a)break;let s=o.cloneDeep(e);s.discounts||(s.discounts=[]),s.discounts.push({...new gt,calc_type:W.Flat,calc_flow:G.AfterServiceCharge,amount:r}),this.calculate(s,n),s.grand_total<=t?a=r:i=r}let s=o.cloneDeep(e);if(s.discounts=[...s.discounts||[],{...new gt,calc_type:W.Flat,calc_flow:G.AfterServiceCharge,amount:a}],this.calculate(s,n),s.grand_total>t)throw Error(`Target grand total ${t} is unreachable`);return q(a,2)}resetInvoiceCalculations(e){e.subtotal=0,e.point_subtotal=0,e.service_chargeable_subtotal=0,e.service_charge=0,e.tax=0,e.grand_total=0,e.rounding=0,e.discount_amount=0,e.minus_credit=0,e.rewarded_credit=0,e.rewarded_point=0,e.add_credit=0,e.add_point=0,e.charges&&e.charges.length>0&&e.charges.forEach(e=>{e.amount=0})}resetLineCalculations(e){e.subtotal=0,e.subtotal_before_discount=0,e.point_subtotal=0}calculateChangeAmount(e){if(e.payments.length<=0||e.payments.every(e=>!e.payment_method.is_cash))return;let t=e.grand_total;e.payments.forEach(e=>{e.payment_method.is_cash?(e.change_amount=q(Math.max(0,e.tender_amount-Math.max(0,t))),t=q(t-e.tender_amount)):e.payment_method.allow_custom_amount?(t=q(t-Math.min(e.tender_amount,Math.max(0,t))),e.change_amount=0):(e.change_amount=0,t=q(t-e.tender_amount))})}calculateInvoiceCharges(e,t){if(!(!e.charges||e.charges.length===0))for(let n of e.charges.filter(e=>e.calc_flow===t)){let t=0;switch(n.calc_flow){case G.AfterSubtotal:t=e.subtotal;break;case G.AfterServiceCharge:t=e.subtotal+e.service_charge;break;case G.AfterGrantTotal:t=e.grand_total;break;default:t=e.subtotal}n.percentage>0&&(n.amount=q(t*(n.percentage/100),2)),e.grand_total+=n.amount,e.grand_total=q(e.grand_total,2)}}},Nr=class extends Mr{addItemToLine(e,n,r,i,a,o,s,c,l){let u={...jr,...o};e.lines??(e.lines=[]);let d=this.findOrCreateLine(e,i,u.quantity,u.price,a,u.remark,s,c,l);return i.type==P.Combo&&(d.is_combo=!0),d.uid?(d.quantity+=u.quantity,d.quantity<=0&&(e.lines=e.lines.filter(e=>e.uid!==d.uid))):u.quantity>0&&(d.uid=E.InvoiceLine+t(),e.lines.push(d)),d}duplicateLine(e,n){let r=o.cloneDeep(n);r.is_duplicate=!0,r.duplicated_from_uid=n.uid,r.uid=E.InvoiceLine+t(),e.lines.push(r);for(let i of this.getAttachedLines(e,n.uid)){let n=o.cloneDeep(i);n.uid=E.InvoiceLine+t(),n.attached_to_line_uid=r.uid,e.lines.push(n)}return e}addAttachedItemsToLine(e,t,n,r,i){if(!n?.length)return[];let a=[];for(let o of n){let n=this.addItemToLine(e,r,i,o,[],{quantity:t.quantity},!0);n.attached_to_line_uid=t.uid,a.push(n)}return a}getAttachedLines(e,t){return e.lines?.filter(e=>e.attached_to_line_uid===t)||[]}calibrateDuplicates(e){if(!e.lines||e.lines.length<=0)return e;let t=e.lines.filter(e=>e.is_duplicate);for(let n of t){let t=e.lines.find(e=>e.uid===n.duplicated_from_uid&&!e.is_duplicate);t&&this.compareLines(t,n)?(t.quantity+=n.quantity,t.sent+=n.sent,e.lines=e.lines.filter(e=>e!==n)):n.is_duplicate=!1}return e}toInvoiceCoreLine(e,t=1){let n=new _t;return n.item=o.cloneDeep(e),n.item_uid=e.uid,n.quantity=t,n.price=e.price,n}addModifier(e,t){if(!e||e.length<=0)return[t];{let n=e.findIndex(e=>e.item_uid===t.item_uid&&e.price===t.price);return n<0?e.push(t):e[n].quantity+=t.quantity,e}}changeLinePrice(e,t){return e==null||(e.price=t),e}changeLineDiscount(e,t,n){if(e==null)return e;if(t==W.Percent&&n>100)throw new D(`Discount percent can not be more than 100%`);if(t==W.Flat&&n>e.subtotal)throw new D(`Discount amount can not be more than price`);return e.discount_calc_type=t,t==W.Flat?e.discount_amount=n:e.discount_percent=n,e}minusLineQuantity(e,t,n,r=!1){if(n<=0)throw new D(`Quantity can not be less than 0, input a positive quantity to minus the line quantity`);if(e.lines==null||e.lines.length<=0)return e;if(!t)throw new D(`Line can not be null or empty`);if(t.quantity-t.sent<Math.abs(n)){let i=Math.abs(n)-(t.quantity-t.sent),a=o.cloneDeep(t);a.quantity=i,a.sent=i,r||e.deleted_lines.push(a),t.sent-=i}t.quantity<=n&&(e.lines=e.lines.filter(e=>e.uid!==t.uid)),t.quantity-=n;let i=this.getAttachedLines(e,t.uid);if(t.quantity<=0){let t=new Set(i.map(e=>e.uid));e.lines=e.lines.filter(e=>!t.has(e.uid))}else for(let e of i)e.quantity=t.quantity}addLineQuantity(e,t,n){if(e.lines==null||e.lines.length<=0)return e;t.quantity+=n;for(let n of this.getAttachedLines(e,t.uid))n.quantity=t.quantity}minusModifierQuantity(e,t,n=0){if(!e||e.length<=0)return e;{n=n??0;let r=e.findIndex(e=>e.item_uid===t.item_uid&&e.price===t.price);return r<0||(e[r].quantity<=n?e.splice(r,1):e[r].quantity-=n),e}}changeModifierQuantity(e,t,n){if(!e||e.length<=0)return e;n=n??0;let r=e.findIndex(e=>e.item_uid===t.item_uid&&e.price===t.price);return r<0?e:(e[r].quantity+=n,e[r].quantity<=0&&e.splice(r,1),e)}addModifierQuantity(e,t,n=0){if(!e||e.length<=0)return e;{n=n??0;let r=e.findIndex(e=>e.item_uid===t.item_uid&&e.price===t.price);return r<0||(e[r].quantity+=n),e}}changeModifierPrice(e,t){return e&&(e.price=t,e)}overwriteNoteToLine(e,t){return t&&(e.remark=t),e}findOrCreateLine(e,t,n,r=0,i=[],a=``,o=!1,s,c){if(r=r??t.price,!e.lines||e.lines.length<=0||o)return this.createInvoiceLine(t,n,r,i,a);{let o=e.lines.filter(e=>e.item_uid===t.uid);if(!o||o.length<=0)return this.createInvoiceLine(t,n,r,i,a);if(s&&c){for(let e of o)if(e.is_combo_item&&this.compareModifiers(e.modifiers,i)&&e.remark===a&&e.price===r&&e.combo_line_uid===s&&e.combo_group_uid===c)return e}else for(let e of o)if(!e.is_combo_item&&this.compareModifiers(e.modifiers,i)&&e.remark===a&&e.price===r&&!e.is_take_out)return e;return this.createInvoiceLine(t,n,r,i,a)}}createInvoiceLine(e,t,n=0,r=[],i=``){let a=new vt;return a.item=o.cloneDeep(e),a.item_uid=e.uid,a.quantity=t,a.point=e.minus_point,a.price=n??e.price,a.quantity=t,a.modifiers=r,a.remark=i,a}compareModifiers(e,t){if(e.length!==t.length)return!1;for(let n of e)if(!t.some(e=>e.item_uid===n.item_uid&&e.price===n.price&&e.quantity===n.quantity))return!1;return!0}compareLines(e,t){return!(e.remark!=t.remark||e.price!=t.price||e.is_take_out!=t.is_take_out||e.discount_calc_type!=t.discount_calc_type||e.discount_amount!=t.discount_amount||e.discount_percent!=t.discount_percent||!this.compareModifiers(e.modifiers,t.modifiers))}addComboItemToLine(e,t,n,r,i,a,o,s){let c=this.addItemToLine(e,t,n,r,o,s,!1,i,a);return c.is_combo_item=!0,c.combo_line_uid=i,c.combo_group_uid=a,c}removeAllComboItems(e,t,n=!1){if(!e.lines||e.lines.length==0)return[];let r=e.lines.filter(e=>e.combo_line_uid==t&&e.is_combo_item);return e.lines=o.differenceBy(e.lines,r,`uid`),n||e.deleted_lines.push(...r),r}duplicateComboLines(e,n){if(!n.is_combo)throw new D(`Line is not a combo`);let r=o.cloneDeep(n);return r.uid=E.InvoiceLine+t(),r.is_duplicate=!0,r.duplicated_from_uid=n.uid,e.lines.push(r),e.lines.filter(e=>e.combo_line_uid===n.uid&&e.is_combo_item).forEach(n=>{let i=o.cloneDeep(n);i.uid=E.InvoiceLine+t(),i.combo_line_uid=r.uid,i.is_duplicate=!0,e.lines.push(i)}),e}},Pr=class extends Nr{async addInvoice(e){let t=await this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/add_invoice`,e);if(t.error==O.outdatedInvoice)throw await this.saveOne(t.data),new D(t.error);if(t.error)throw new D(t.error);return t.data}async createInvoice(e,t,n){e.status=U.Open,e.ref_id||(e.ref_id=await this.getRefId()),e.call_num||(e.call_num=e.ref_id.slice(-3)),e.table_name=t.name,e.table_uid=t.uid,t.invoice_uid=e.uid,t.status=M.OPENED,this.sectionItemService.syncInvoiceData(t,e),this.addEmployeeToInvoice(e,n),e.created_at=new Date,e.created_at_timestamp=e.created_at.getTime();let r=(await this.configService.getDefaultOne()).config?.order?.datetime_format;e.humanized_created_at=R(e.created_at,r),t.invoice_created_at=new Date;let i=await this.createKitchenPrintJobs(e),a=await this.createLabelPrintJobs(e),o=await this.createOrderPrintJobs(e),s=this.sortPrintJobsByPrinterSequence([...i,...a,...o]);e.kitchen_print_job_uids||(e.kitchen_print_job_uids=[]),e.label_print_job_uids||(e.label_print_job_uids=[]),e.order_print_job_uids||(e.order_print_job_uids=[]);let c=e.kitchen_print_job_uids.length,l=e.label_print_job_uids.length,u=e.order_print_job_uids.length,d=i.map(e=>e.uid),f=a.map(e=>e.uid),p=o.map(e=>e.uid);d.length>0&&e.kitchen_print_job_uids.push(d),f.length>0&&e.label_print_job_uids.push(f),p.length>0&&e.order_print_job_uids.push(p);let m=this.getItemStockChangeList(e);await this.preprocessInvoice(e);let h={invoice:e,section_item:t};s.length>0&&(h.print_jobs=s),m.length>0&&(h.items=await this.itemService.getItemsWithStockChanges(m));try{let e=await this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${this.methodName}`,h);if(e.error==O.outdatedInvoice)throw await this.saveOne(e.data),h.invoice=e.data,new D(e.error);if(e.error==O.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),h.section_item=e.data,new D(e.error);return h}catch(t){throw e.kitchen_print_job_uids.length=c,e.label_print_job_uids.length=l,e.order_print_job_uids.length=u,t}}async updateInvoice(e,t,n){this.sectionItemService.syncInvoiceData(t,e),this.addEmployeeToInvoice(e,n),e.updated_at=new Date;let r=await this.createKitchenPrintJobs(e),i=await this.createCancelKitchenPrintJobs(e,e.deleted_lines),a=await this.createVoidSlipPrintJobs(e,e.deleted_lines,t),o=await this.createLabelPrintJobs(e),s=await this.createOrderPrintJobs(e),c=this.sortPrintJobsByPrinterSequence([...r,...i,...a,...o,...s]);e.kitchen_print_job_uids||(e.kitchen_print_job_uids=[]),e.label_print_job_uids||(e.label_print_job_uids=[]),e.order_print_job_uids||(e.order_print_job_uids=[]);let l=e.kitchen_print_job_uids.length,u=e.label_print_job_uids.length,d=e.order_print_job_uids.length,f=r.map(e=>e.uid),p=o.map(e=>e.uid),m=s.map(e=>e.uid);f.length>0&&e.kitchen_print_job_uids.push(f),p.length>0&&e.label_print_job_uids.push(p),m.length>0&&e.order_print_job_uids.push(m);let h=this.getItemStockChangeList(e);await this.preprocessInvoice(e);let g={invoice:e,section_item:t};c.length>0&&(g.print_jobs=c),h.length>0&&(g.items=await this.itemService.getItemsWithStockChanges(h));try{let e=await this.http.patch(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/update_invoice`,g);if(e.error==O.outdatedInvoice)throw await this.saveOne(e.data),new D(`${e.error}, system has updated the data, please try again`);if(e.error==O.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),g.section_item=e.data,new D(`${e.error}, system has updated the data, please try again`);return g}catch(t){throw e.kitchen_print_job_uids.length=l,e.label_print_job_uids.length=u,e.order_print_job_uids.length=d,t}}async cancelInvoice(e,t,n){if(e.id_in_server==0&&e.lines.length<=0)throw new D(`The invoice is empty and nothing can be canceled.`);if(e.id_in_server==0)return e.lines=[],{invoice:e,section_item:t};e.status=U.Void,t.invoice_uid=``,t.status=M.CLOSED,this.sectionItemService.reset(t),this.addEmployeeToInvoice(e,n);let r=await this.createReceiptPrintJob(e,z.ReceiptPrinter,!0),i={invoice:e,section_item:t};r&&(i.print_jobs=[r]);let a=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/cancel_invoice`,i);if(a.error==O.outdatedInvoice)throw await this.saveOne(a.data),i.invoice=a.data,new D(a.error);if(a.error==O.outdatedSectionItem)throw await this.sectionItemService.saveOne(a.data),i.section_item=a.data,new D(a.error);return i}async checkInvoice(e,t,n,r){t.status=M.PAYMENT,this.addEmployeeToInvoice(e,n);let i=await this.createReceiptPrintJob(e,z.CheckPrinter,!1,0,r),a=await this.createLabelPrintJobs(e),o=await this.createKitchenPrintJobs(e),s=await this.createOrderPrintJobs(e),c=[...a,...o,...s];i&&c.push(i);let l=this.sortPrintJobsByPrinterSequence(c);e.kitchen_print_job_uids||(e.kitchen_print_job_uids=[]),e.label_print_job_uids||(e.label_print_job_uids=[]),e.order_print_job_uids||(e.order_print_job_uids=[]);let u=e.kitchen_print_job_uids.length,d=e.label_print_job_uids.length,f=e.order_print_job_uids.length,p=o.map(e=>e.uid),m=a.map(e=>e.uid),h=s.map(e=>e.uid);p.length>0&&e.kitchen_print_job_uids.push(p),m.length>0&&e.label_print_job_uids.push(m),h.length>0&&e.order_print_job_uids.push(h);let g=this.getItemStockChangeList(e);await this.preprocessInvoice(e);let _={invoice:e,section_item:t};l.length>0&&(_.print_jobs=l),g.length>0&&(_.items=await this.itemService.getItemsWithStockChanges(g));try{let e=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/check_invoice`,_);if(e.error==O.outdatedInvoice)throw await this.saveOne(e.data),_.invoice=e.data,new D(e.error);if(e.error==O.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),_.section_item=e.data,new D(e.error);return _}catch(t){throw e.kitchen_print_job_uids.length=u,e.label_print_job_uids.length=d,e.order_print_job_uids.length=f,t}}async switchInvoice(e,t,n,r){if(t.uid==n.uid)throw new D(`source and target table can not be the same`);if(t.status!=M.CLOSED)throw new D(`target table is occupied`);if(e.lines==null||e.lines.length<=0)throw new D(`source table has nothing to switch`);t.invoice_uid=e.uid,t.status=n.status,this.sectionItemService.syncInvoiceData(t,e),n.invoice_uid=``,n.status=M.CLOSED,this.sectionItemService.reset(n),e.table_uid=t.uid,e.table_name=t.name,this.addEmployeeToInvoice(e,r);let i={invoice:e,target_section_item:t,source_section_item:n},a=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/switch_invoice`,i);if(a.error==O.outdatedInvoice)throw await this.saveOne(a.data),i.invoice=a.data,new D(a.error);if(a.error==O.outdatedSourceSectionItem)throw await this.sectionItemService.saveOne(a.data),i.source_section_item=a.data,new D(a.error);if(a.error==O.outdatedTargetSectionItem)throw await this.sectionItemService.saveOne(a.data),i.target_section_item=a.data,new D(a.error);return i}async payInvoice(e,t,n,r,i){e.status=U.Paid,t.invoice_uid=``,t.status=M.CLOSED,this.sectionItemService.reset(t),this.addEmployeeToInvoice(e,r),e.paid_at=new Date;let a=(await this.configService.getDefaultOne()).config,o=a?.order?.datetime_format;e.humanized_paid_at=R(e.paid_at,o),e.payment_has_cash=e.payments?.some(e=>e.payment_method?.is_cash===!0);let s=this.mergeStockChangeLists(this.getItemStockChangeList(e),this.getModifierStockChangeList(e)),c=await this.sectionService.getOne(t.section_uid),l=await this.createLabelPrintJobs(e),u=await this.createReceiptPrintJob(e,z.ReceiptPrinter,c?.disable_auto_print_receipt||!1,0,i),d=await this.createKitchenPrintJobs(e),f=await this.createCancelKitchenPrintJobs(e,e.deleted_lines),p=await this.createVoidSlipPrintJobs(e,e.deleted_lines,t),m=await this.createOrderPrintJobs(e),h=[...l,...d,...f,...p,...m];u&&h.push(u);let g=this.sortPrintJobsByPrinterSequence(h);e.kitchen_print_job_uids||(e.kitchen_print_job_uids=[]),e.label_print_job_uids||(e.label_print_job_uids=[]),e.order_print_job_uids||(e.order_print_job_uids=[]);let _=e.kitchen_print_job_uids.length,v=e.label_print_job_uids.length,y=e.order_print_job_uids.length,b=d.map(e=>e.uid),x=l.map(e=>e.uid),S=m.map(e=>e.uid);b.length>0&&e.kitchen_print_job_uids.push(b),x.length>0&&e.label_print_job_uids.push(x),S.length>0&&e.order_print_job_uids.push(S),await this.preprocessInvoice(e);let C={invoice:e,section_item:t,till:n};g.length>0&&(C.print_jobs=g),s.length>0&&(C.items=await this.itemService.getItemsWithStockChanges(s));try{let t=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/pay_invoice`,C);if(t.error==O.outdatedInvoice)throw await this.saveOne(t.data),C.invoice=t.data,new D(`${t.error}, system has updated the data and please try again`);if(t.error==O.outdatedSectionItem)throw await this.sectionItemService.saveOne(t.data),C.section_item=t.data,new D(`${t.error}, system has updated the data and please try again`);if(e.call_num&&a?.ods?.enabled){let t=new kr;t.order_number=e.call_num,await this.orderDisplayService.addOne(t)}return C}catch(t){throw e.kitchen_print_job_uids.length=_,e.label_print_job_uids.length=v,e.order_print_job_uids.length=y,t}}async directPayInvoice(e,t,n,r,i,a=!1){e.status=U.Paid,n!=null&&this.addEmployeeToInvoice(e,n),e.paid_at=new Date;let o=(await this.configService.getDefaultOne()).config,s=o?.order?.datetime_format;e.humanized_paid_at=R(e.paid_at,s),e.created_at=new Date,e.created_at_timestamp=e.created_at.getTime(),e.humanized_created_at=R(e.created_at,s),e.ref_id||(e.ref_id=await this.getRefId()),e.call_num||(e.call_num=e.ref_id.slice(-3)),e.payment_has_cash=e.payments?.some(e=>e.payment_method?.is_cash===!0);let c=this.mergeStockChangeLists(this.getItemStockChangeList(e),this.getModifierStockChangeList(e)),l=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,u=(l?.section_uid?await this.sectionService.getOne(l.section_uid):null)?.disable_auto_print_receipt||!1,d=null,f=null;if(r&&r.type==z.KioskPrinter){let t=!!o?.kiosk?.disable_receipt_printer_receipt||u;d=await this.createReceiptPrintJob(e,z.ReceiptPrinter,t),f=await this.createReceiptPrintJob(e,z.KioskPrinter,!1,0,r,i)}else d=await this.createReceiptPrintJob(e,z.ReceiptPrinter,u,0,r);let p=await this.createLabelPrintJobs(e),m=await this.createKitchenPrintJobs(e,a),h=await this.createOrderPrintJobs(e),g=[...p,...m,...h];d&&g.push(d),f&&g.push(f);let _=this.sortPrintJobsByPrinterSequence(g),v=m.map(e=>e.uid),y=p.map(e=>e.uid),b=h.map(e=>e.uid);v.length>0&&(e.kitchen_print_job_uids=[v]),y.length>0&&(e.label_print_job_uids=[y]),b.length>0&&(e.order_print_job_uids=[b]),await this.preprocessInvoice(e);let x={invoice:e,till:t};_.length>0&&(x.print_jobs=_),c.length>0&&(x.items=await this.itemService.getItemsWithStockChanges(c));let S=await this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/direct_pay_invoice`,x);if(S.error==O.outdatedInvoice)throw await this.saveOne(S.data),x.invoice=S.data,new D(S.error);if(e.call_num&&o?.ods?.enabled){let t=new kr;t.order_number=e.call_num,await this.orderDisplayService.addOne(t)}return x}async voidInvoice(e,t,n,r){n&&(e.etc.void_reason=n);let i=e.status;e.status=U.Void,e.voided_at=new Date;let a=(await this.configService.getDefaultOne()).config?.order?.datetime_format;e.humanized_voided_at=R(e.voided_at,a),t&&(t.deleted_at=new Date),this.addEmployeeToInvoice(e,r);let o=(await this.configService.getDefaultOne()).config,s=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,c=await this.createReceiptPrintJob(e,z.ReceiptPrinter,!0),l=[];o.kitchen.print_cancel_whole_invoice&&(l=await this.createCancelKitchenPrintJobs(e,e.lines)||[]);let u=[];o.receipt.print_cancel_whole_invoice&&(u=await this.createVoidSlipPrintJobs(e,e.lines,s)||[]);let d=[...l,...u];c&&d.push(c);let f={invoice:e,till:t};d.length>0&&(f.print_jobs=d);let p=await this.tillService.db.table(`tills`).where({invoice_uid:e.uid}).toArray(),m=p.filter(e=>e.type===A.CashInvoice&&!e.deleted_at).reduce((e,t)=>e+t.amount,0);if(m>0){let t=new j;t.type=A.CashInvoice,t.amount=-m,t.invoice_uid=e.uid,t.shift_uid=p[0]?.shift_uid,t.user_uid=r?.uid||p[0]?.user_uid,f.till=t}s&&s.status!=M.CLOSED&&s.invoice_uid===e.uid&&(s.invoice_uid=``,s.status=M.CLOSED,f.section_item=s);let h=this.getItemStockChangeList(e,!0),g=i==U.Paid?this.mergeStockChangeLists(h,this.getModifierStockChangeList(e,!0)):h;g.length>0&&(f.items=await this.itemService.getItemsWithStockChanges(g));let _=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/void_invoice`,f);if(_.error==O.outdatedInvoice)throw await this.saveOne(_.data),f.invoice=_.data,new D(_.error);return f}async duplicateInvoice(e,n){if(e.status!=U.Paid)throw new D(`invalid invoice status`);let r=o.cloneDeep(e);if(r.etc.is_duplicate=!0,r.etc.duplicated_from_uid=r.uid,r.uid=E.Invoice+t(),r.status=U.Open,r.ref_id=await this.getRefId(),this.addEmployeeToInvoice(r,n),r.lines)for(let e of r.lines)e.uid=E.InvoiceLine+t();if(r.payments)for(let e of r.payments)e.uid=E.Payment+t();return r}async reprintReceipt(e,n=!1,r){if(!e?.receipt_print_job_uid)throw new D(`The invoice does not have a receipt`);let i=await this.printJobService.getOne(e.receipt_print_job_uid);if(!i){let t=new f().addParam(`uid`,`EqualTo`,e.receipt_print_job_uid),n=await this.printJobService.autoquery(t);if(!n.results||n.results.length<=0)throw new D(`The invoice does not have a receipt`);i=n.results[0]}let a=r;if(a||(a=await this.printerService.getOne(i.printer_uid)),a||(a=await this.printerService.getDefaultReceiptPrinter()),!a)throw new D(`Receipt printer not found`);return i=this.printJobService.replacePrinter(i,a),i.uid=E.PrintJob+t(),i.save_only=n,i.status=Je.Queued,i.print_times=1,i.printed=0,i.retries=0,i.created_at_timestamp=Date.now(),await this.printJobService.addOne(i),i}async printLastKitchenSlips(e){let n=await this.getOne(e);if(!n)throw new D(`Invoice not found`);let r=n.kitchen_print_job_uids?.[n.kitchen_print_job_uids.length-1]||[],i=n.label_print_job_uids?.[n.label_print_job_uids.length-1]||[],a=[...r,...i];if(a.length===0)throw new D(`No kitchen or label print found`);let o=new f().addParam(`uid`,`In`,a),s=await this.printJobService.autoquery(o);if(!s.results||s.results.length===0)throw new D(`Print jobs not found`);for(let e of s.results){let n=await this.printerService.getOne(e.printer_uid);if(!n)continue;let r=this.printJobService.replacePrinter(e,n),i=r.uid;r.uid=E.PrintJob+t(),r.save_only=!1,r.status=Je.Queued,r.print_times=1,r.printed=0,r.retries=0,r.created_at_timestamp=Date.now(),r.meta||(r.meta={}),r.meta.is_reprint=!0,r.meta.parent_uid=i,await this.printJobService.addOne(r)}return!0}async printLastOrderDocket(e){let n=await this.getOne(e);if(!n)throw new D(`Invoice not found`);let r=n.order_print_job_uids?.[n.order_print_job_uids.length-1]||[];if(r.length===0)throw new D(`No order docket print found`);let i=new f().addParam(`uid`,`In`,r),a=await this.printJobService.autoquery(i);if(!a.results||a.results.length===0)throw new D(`Print jobs not found`);for(let e of a.results){let n=await this.printerService.getOne(e.printer_uid);if(!n)continue;let r=this.printJobService.replacePrinter(e,n),i=r.uid;r.uid=E.PrintJob+t(),r.save_only=!1,r.status=Je.Queued,r.print_times=1,r.printed=0,r.retries=0,r.created_at_timestamp=Date.now(),r.meta||(r.meta={}),r.meta.is_reprint=!0,r.meta.parent_uid=i,await this.printJobService.addOne(r)}return!0}addInvoiceDiscount(e,t,n,r=G.AfterSubtotal,i=`custom`,a={}){if(e.discounts||(e.discounts=[]),t==W.Percent&&n>100)throw new D(`Discount percent can not be more than 100%`);let o=new gt;return o.calc_type=t,o.calc_flow=r,o.name=i,o.name_translation=a,t==W.Flat?o.amount=n:o.percent=n,e.discounts.push(o),e}addCouponToInvoice(e,t,n=G.AfterSubtotal){e.discounts||(e.discounts=[]);let r=new gt;if(r.calc_type=t.coupon.discount_calc_type==1?W.Flat:W.Percent,r.calc_flow=n,r.name=t.coupon.name,r.calc_type==W.Flat?r.amount=t.coupon.discount_amount:r.percent=t.coupon.discount_percent,r.coupon_uid=t.guid,t.coupon.applying_plus.applying_items?.length>0&&(r.applying_item_uids=t.coupon.applying_plus.applying_items,!e.lines||o.intersection(r.applying_item_uids,e.lines.map(e=>e.item_uid)).length===0))throw new D(`Coupon can not applied to any product in this order`);return e.discounts.push(r),e}removeInvoiceDiscount(e,t){return e.discounts&&(e.discounts=e.discounts.filter(e=>e.uid!==t)),e}overwriteNoteToInvoice(e,t){return t&&(e.remark=t),e}addSalesPersonToInvoice(e,t){return e.sales_user_uid=t,e}addPaxToInvoice(e,t){return e.pax=t,e}addCustomerToInvoice(e,t){if(!t)throw new D(`Customer object can not be null`);return e.customer_id=t.id,e.customer=o.cloneDeep(t),e}async autoQuery(e,t){return await this.http.get(`sapi/v5/merchants/${this.options.merchant_uid}/${this.moduleName}`,{params:e.build(),...t})}appendInvoice(e,t){if(e?.id_in_server==0)return t;for(let n of t.lines)if(n.is_combo||n.is_combo_item)n.quantity>0&&e.lines.push(n);else{let t=this.findOrCreateLine(e,n.item,n.quantity,n.price,n.modifiers,n.remark);t.uid?t.quantity+=n.quantity:n.quantity>0&&e.lines.push(n)}return t.remark&&(e.remark=t.remark),t.customer_id&&!e.customer_id&&(e.customer_id=t.customer_id),e}async mergeInvoice(e,t){if(t.lines?.length==0)throw new D(`Source invoice has no nothing to merge`);if(t.lines.some(e=>e.quantity!=e.sent))throw new D(`Please send first before merging`);if(!await this.getOne(e.uid))throw new D(`Target invoice not found`);if(!await this.getOne(t.uid))throw new D(`Source invoice not found`);if(e?.id_in_server==0)throw new D(`Target invoice is not synced to server`);if(t?.id_in_server==0)throw new D(`Source invoice is not synced to server`);for(let n of t.lines)if(n.is_combo||n.is_combo_item)n.quantity>0&&e.lines.push(n);else{let t=this.findOrCreateLine(e,n.item,n.quantity,n.price,n.modifiers,n.remark);t.uid?t.quantity+=n.quantity:n.quantity>0&&e.lines.push(n)}return e.customer_id||(e.customer_id=t.customer_id),e}async getRefId(){let e=(await this.configService.getDefaultOne()).config?.order?.ref_prefix||`01`,t=(await this.http.get(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${this.methodName}/get_invoice_counter`)).data.toString().padStart(9,`0`);return`${e}${this.formatDate(new Date)}${t}`}async changePayments(e,t){if(e.status!=U.Paid)throw new D(`invalid invoice status`);if(!t||t.length<1)throw new D(`invalid options`);for(let n of t){let t=e.payments.find(e=>e.uid==n.source_payment.uid);if(!t)throw new D(`payment not found`);t.payment_method_uid=n.target_payment_method.uid,t.payment_method_code=n.target_payment_method.payment_method_code,t.payment_method_name=n.target_payment_method.name,t.payment_method=o.cloneDeep(n.target_payment_method),t.payment_method_history=o.cloneDeep(n.target_payment_method),t.payment_method_history.changed_at=new Date}return e.is_sales_exclusive=e.payments.some(e=>e.payment_method.is_sales_exclusive),e}formatDate(e){let t=e.getFullYear().toString().slice(-2),n=(e.getMonth()+1).toString().padStart(2,`0`),r=e.getDate().toString().padStart(2,`0`);return t+n+r}addEmployeeToInvoice(e,t){return t?(e.employee_uid=t.uid,e.employee_name=t.name,e):e}async createReceiptPrintJob(e,t,n=!1,r=0,i=null,a){let o;if(i)o=i;else if(t==z.ReceiptPrinter||t==z.CheckPrinter){let n=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,r=t==z.ReceiptPrinter?n?.receipt_printer_uid:n?.check_printer_uid;r&&(o=await this.printerService.getOne(r)),o||(o=t==z.ReceiptPrinter?await this.printerService.getDefaultReceiptPrinter():await this.printerService.getDefaultCheckPrinter())}if(!o||!o.print_template_uid)return null;r||(r=o.print_times);let s=await this.configService.getDefaultOne(),c=await this.printTemplateService.getOneByParams({uid:o.print_template_uid});if(!c)throw new D(`Print template not found`);t==z.ReceiptPrinter&&!s.config?.receipt?.enabled&&(n=!0);let l=await this.printTemplateService.renderPrintTemplate(e,s.config,c,{...new H,printer_name:o.name}),u=new V(o,l,n,r);return t!=z.ReceiptPrinter&&(u.printer_type=t),o.connection_type!=Ke.ETHERNET&&(u.connection_type=o.connection_type),t==z.ReceiptPrinter&&(e.receipt_print_job_uid=u.uid),a&&(u.device_uid_to_print=a),u}sortLinesByItemSequence(e){return o.chain(e||[]).groupBy(e=>e.is_combo_item?e.combo_line_uid:e.uid).map(e=>o.sortBy(e,[e=>!e.is_combo,e=>e.item.printing_sequence||e.item.sequence||999999])).sortBy(e=>e[0].item.printing_sequence||e[0].item.sequence||999999).flatten().value()}getSortedLines(e,t){return t.disable_printing_sequence?e:this.sortLinesByItemSequence(e)}sortLineModifiers(e){for(let t of e){if(!t.modifiers?.length||!t.item.modifiers?.length)continue;let e=new Map(t.item.modifier_categories?.map(e=>[e.uid,e.printing_sequence??999999])),n=new Map(t.item.modifiers.map(e=>[e.uid,e]));t.modifiers.sort((t,r)=>{let i=n.get(t.item_uid),a=n.get(r.item_uid);return(e.get(i?.category_uid)??999999)-(e.get(a?.category_uid)??999999)||(i?.sequence??0)-(a?.sequence??0)})}}async createKitchenPrintJobs(e,t=!1){let n=(await this.configService.getDefaultOne()).config;if(!n.kitchen.enabled&&!t||e.lines.every(e=>e.sent==e.quantity))return[];let r=[],{lines:i,printerUids:a}=this.filterLinesAndPrintersToPrint(e.lines,z.KitchenPrinter),s=await this.printerService.getPrintersByUids(a);for(let t of s){let a=await this.printTemplateService.getOneByParams({uid:t.print_template_uid});if(!a)continue;let s=i.filter(e=>e.item.kitchen_printers_uids.includes(t.uid)),c=this.getSortedLines(s,t);this.sortLineModifiers(c);let l=o.cloneDeep(e);if(t.kitchen_itemized_print)for(let e of c){l.lines=[e];let i=new V(t,await this.printTemplateService.renderPrintTemplate(l,n,a,{...new H,printer_name:t.name}),!1,t.print_times);r.push(i)}else{l.lines=c;let e=new V(t,await this.printTemplateService.renderPrintTemplate(l,n,a,{...new H,printer_name:t.name}),!1,t.print_times);r.push(e)}}return r}async createOrderPrintJobs(e){let t=(await this.configService.getDefaultOne()).config;if(!t.receipt.print_docket||e.lines.every(e=>e.sent==e.quantity))return[];let n=[],{lines:r,printerUids:i}=this.filterLinesAndPrintersToPrint(e.lines,z.OrderPrinter),a=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,s=await this.printerService.getPrintersByUids(i);for(let i of s){if(a?.order_printer_uids?.length>0&&!a.order_printer_uids.includes(i.uid))continue;let s=await this.printTemplateService.getOneByParams({uid:i.print_template_uid});if(!s)continue;let c=r.filter(e=>e.item.order_printers_uids.includes(i.uid)),l=this.getSortedLines(c,i);this.sortLineModifiers(l);let u=o.cloneDeep(e);u.lines=l;let d=new V(i,await this.printTemplateService.renderPrintTemplate(u,t,s,{...new H,printer_name:i.name}),!1,i.print_times);n.push(d)}return n}async createVoidSlipPrintJobs(e,t,n){if(!t||t.length===0||e.action===ut.PayAtCounter)return[];let r=(await this.configService.getDefaultOne()).config;if(!r.receipt.print_cancel_slip||(t=t.filter(e=>!e.is_cancel_slip_printed),t.length===0))return[];let i=new Set;for(let e of t)e.item?.order_printers_uids&&e.item.order_printers_uids.forEach(e=>i.add(e));let a=Array.from(i);if(a.length===0)return[];let s=await this.printerService.getPrintersByUids(a),c=[];for(let i of s){if(n?.order_printer_uids?.length>0&&!n.order_printer_uids.includes(i.uid))continue;let a=await this.printTemplateService.getOneByParams({uid:i.print_template_uid});if(!a)continue;let s=t.filter(e=>e.item?.order_printers_uids?.includes(i.uid));if(s.length===0)continue;let l=this.getSortedLines(s,i);this.sortLineModifiers(l);let u=o.cloneDeep(e);u.lines=l;let d=new V(i,await this.printTemplateService.renderPrintTemplate(u,r,a,{...new H,printer_name:i.name,is_cancel:!0}),!1,i.print_times);c.push(d)}for(let e of t)e.is_cancel_slip_printed=!0;return c}async createLabelPrintJobs(e){let t=(await this.configService.getDefaultOne()).config;if(e.lines.every(e=>e.sent==e.quantity))return[];let n=[],{lines:r,printerUids:i}=this.filterLinesAndPrintersToPrint(e.lines,z.LabelPrinter);if(i.length==0||r.length==0)return[];let a=await this.printerService.getPrintersByUids(i),s=o.cloneDeep(e);this.sortLineModifiers(r);let c=r.length,l=1;for(let e of r)e.meta.total_index=c,e.meta.index=l,l++;for(let e of a)for(let i of r){if(!i.item.label_printers_uids.includes(e.uid))continue;let r=await this.printTemplateService.getOneByParams({uid:e.print_template_uid});if(!r||!r.commands)continue;let a=d.compile(r.commands);s.lines=[i];let o=a({invoice:s,config:t}),c=new V(e,new L,!1,e.print_times);c.commands=o,n.push(c)}return n}filterLinesAndPrintersToPrint(e,t){let n;switch(t){case z.KitchenPrinter:n=`kitchen_printers_uids`;break;case z.OrderPrinter:n=`order_printers_uids`;break;case z.LabelPrinter:n=`label_printers_uids`;break;default:n=`kitchen_printers_uids`}let r=[],i=new Set;for(let a of e)if(a.quantity<=a.sent)continue;else if(!a.item[n]||a.item[n].length==0)continue;else{a.item[n].forEach(e=>i.add(e));let e=o.cloneDeep(a);if(e.quantity-=e.sent,t==z.LabelPrinter)for(let t=0;t<e.quantity;t++){let t=o.cloneDeep(e);t.quantity=1,r.push(t)}else r.push(e)}return{lines:r,printerUids:Array.from(i)}}filterDeletedLinesForCancelPrint(e){let t=[],n=new Set;for(let r of e){if(r.is_cancel_printed||!r.item.kitchen_printers_uids||r.item.kitchen_printers_uids.length==0)continue;r.item.kitchen_printers_uids.forEach(e=>n.add(e));let e=o.cloneDeep(r);t.push(e)}return{lines:t,printerUids:Array.from(n)}}async createCancelKitchenPrintJobs(e,t){let n=(await this.configService.getDefaultOne()).config;if(!n.kitchen.print_cancel_slip||!t||t.length===0||e.action===ut.PayAtCounter)return[];let{lines:r,printerUids:i}=this.filterDeletedLinesForCancelPrint(t);if(r.length===0)return[];let a=await this.printerService.getPrintersByUids(i),s=[];for(let t of a){let i=await this.printTemplateService.getOneByParams({uid:t.print_template_uid});if(!i)continue;let a=r.filter(e=>e.item.kitchen_printers_uids.includes(t.uid)),c=this.getSortedLines(a,t);this.sortLineModifiers(c);let l=o.cloneDeep(e);if(t.kitchen_itemized_print)for(let e of c){l.lines=[e];let r=new V(t,await this.printTemplateService.renderPrintTemplate(l,n,i,{printer_name:t.name,kitchen_itemized_print:t.kitchen_itemized_print,is_cancel:!0}),!1,t.print_times);s.push(r)}else{l.lines=c;let e=new V(t,await this.printTemplateService.renderPrintTemplate(l,n,i,{printer_name:t.name,kitchen_itemized_print:t.kitchen_itemized_print,is_cancel:!0}),!1,t.print_times);s.push(e)}}for(let t of e.deleted_lines)t.is_cancel_printed=!0;return s}sortPrintJobsByPrinterSequence(e){return e.sort((e,t)=>(e?.print_sequence??999)-(t?.print_sequence??999))}async preprocessInvoice(e){if(e.lines)for(let t of e.lines)t.sent=t.quantity;return e}addInvoiceCharge(e,t,n,r,i=G.AfterSubtotal){e.charges||(e.charges=[]);let a=new pt;return a.name=t,a.percentage=n,a.amount=r,a.calc_flow=i,e.charges.push(a),e}removeInvoiceCharge(e,t){return e.charges&&(e.charges=e.charges.filter(e=>e.uid!==t)),e}getItemStockChangeList(e,t=!1){let n=new Map;for(let r of e.lines||[]){let e=t?-(r.sent||0):r.quantity-(r.sent||0);if(e===0)continue;let i=n.get(r.item_uid)||new he(r.item_uid);i.quantity-=e,n.set(r.item_uid,i)}for(let t of e.deleted_lines||[]){let e=(t.sent||0)-(t.stock_reverted||0);if(e<=0)continue;let r=n.get(t.item_uid)||new he(t.item_uid);r.quantity+=e,n.set(t.item_uid,r),t.stock_reverted=t.sent}return Array.from(n.values())}getModifierStockChangeList(e,t=!1){if(!e.lines||e.lines.length===0)return[];let n=new Map;for(let r of e.lines){if(!r.modifiers||r.modifiers.length===0)continue;let e=n.get(r.item_uid)||new he(r.item_uid);for(let n of r.modifiers){let i=e.modifiers.find(e=>e.item_uid===n.item_uid);i||(i={item_uid:n.item_uid,quantity:0},e.modifiers.push(i)),i.quantity+=t?r.quantity*n.quantity:-(r.quantity*n.quantity)}n.set(r.item_uid,e)}return Array.from(n.values())}mergeStockChangeLists(...e){let t=new Map;for(let n of e)for(let e of n){let n=t.get(e.item_uid)||new he(e.item_uid);n.quantity+=e.quantity;for(let t of e.modifiers){let e=n.modifiers.find(e=>e.item_uid===t.item_uid);e||(e={item_uid:t.item_uid,quantity:0},n.modifiers.push(e)),e.quantity+=t.quantity}t.set(e.item_uid,n)}return Array.from(t.values())}sliceInvoice(e){if(!e||!e.lines||e.lines.length===0)return[];let t=[];for(let n of e.lines)for(let r=0;r<n.quantity;r++){let r=o.cloneDeep(e),i=o.cloneDeep(n);i.quantity=1,r.lines=[i],t.push(r)}return t}},Fr=class extends Pr{},Ir=class extends K{constructor(e,t,n,r=`employee_roles`,i=`employee_role`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Lr=class extends K{constructor(e,t,n,r=`employees`,i=`employee`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async login(e,t){try{let n=await this.getOne(e);if(n){if(await p.compare(t,n.password))return!0;throw new D(`Password is incorrect`)}else throw new D(`User not found`)}catch(e){throw e instanceof D?e:new D(`Unexpected error, login failed`)}}async createEmployee(e){try{if(await this.getOne(e.uid))throw new D(`User already exists`);return e.password&&(e.password=await p.hash(e.password,12)),this.addOne(e)}catch(e){throw e instanceof D?e:new D(`Unexpected error, creating employee failed`)}}async changePassword(e){try{return await p.hash(e,12)}catch{throw new D(`Unexpected error, changing password failed`)}}},Rr=class extends K{constructor(e,t,n,r=`items`,i=`item`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async search(e){return this.db.transaction(`r`,[this.db.table(this.moduleName),this.db.table(`categories`)],async()=>{let t=await this.db.table(this.moduleName).where(`name`).anyOfIgnoreCase(e).or(`codename`).anyOfIgnoreCase(e).or(`barcode`).anyOfIgnoreCase(e).toArray();if(!t.length)return t;let n=await this.db.table(`categories`).toArray(),r=new Map(n.map(e=>[e.uid,e]));return t.filter(e=>e.non_searchable!==!0&&r.get(e.category_uid)?.non_searchable!==!0)})}async addModifierCategory(e,n){return n.uid=E.ItemModifierCategory+t(),e.modifier_categories||(e.modifier_categories=[]),e.modifier_categories.push(n),e}async updateModifierCategory(e,t){if(!e.modifier_categories)throw e.modifier_categories=[],new D(`Item does not have any modifier categories`);let n=e.modifier_categories.findIndex(e=>e.uid===t.uid);if(n===-1)throw new D(`Modifier category not found`);return e.modifier_categories[n]=t,e}async removeModifierCategory(e,t){if(!e.modifier_categories)throw e.modifier_categories=[],new D(`Item does not have any modifier categories`);return e.modifier_categories=e.modifier_categories.filter(e=>e.uid!==t.uid),e}async addModifier(e,n){return e.modifiers||(e.modifiers=[]),n.uid=E.ItemModifier+t(),e.modifiers.push(n),e}async updateModifier(e,t){if(!e.modifiers)throw e.modifiers=[],new D(`Item does not have any modifiers`);let n=e.modifiers.findIndex(e=>e.uid===t.uid);if(n===-1)throw new D(`Modifier not found`);return e.modifiers[n]=t,e}async removeModifier(e,t){if(!e.modifiers)throw e.modifiers=[],new D(`Item does not have any modifiers`);return e.modifiers=e.modifiers.filter(e=>e.uid!==t.uid),e}async attachModifierToGroup(e,t,n){if(!e.modifier_categories)throw e.modifier_categories=[],new D(`Item does not have any modifier categories`);if(!e.modifier_categories.find(e=>e.uid===n))throw new D(`Modifier category not found`);let r=e.modifiers.find(e=>e.uid===t);if(!r)throw new D(`Modifier not found`);return r.category_uid=n,e}async addImageAsync(e,t){let n=a(),r=this.getFileExtension(e);await this.http.post(`api/v5/merchants/`+this.options.merchant_uid+`/upload-image`,new rn({base64:await this.convertFileToBase64(e),name:n,extension:this.getFileExtension(e)})),t.image_url=`${this.options.base_url}images/${n}.${r}`,t.image_thumbnail_url=`${this.options.base_url}images/${n}.thumbnail.${r}`}async changeToSoldOut(e){let t=await this.getOne(e);if(!t)throw new D(`Item not found`);return t.stock=0,t.is_sold_out=!0,this.updateOne(t.id_in_server,t)}async changeToAvailable(e,t=1){let n=await this.getOne(e);if(!n)throw new D(`Item not found`);return n.stock=t,n.is_sold_out=!1,this.updateOne(n.id_in_server,n)}async changeStock(e,t){let n=await this.getOne(e);if(!n)throw new D(`Item not found`);let r=Number(n.stock);return n.stock=(isNaN(r)?0:r)+t,this.updateOne(n.id_in_server,n)}async changeItemsStock(e){let t=[];for(let n of e){let e=await this.getOne(n.item_uid);if(!e)continue;let r=Number(e.stock);e.stock=(isNaN(r)?0:r)+n.quantity;for(let t of n.modifiers){let n=e.modifiers?.find(e=>e.uid===t.item_uid);if(!n)continue;let r=Number(n.stock);n.stock=(isNaN(r)?0:r)+Number(t.quantity)}t.push(e)}await this.updateMany(t)}async getItemsWithStockChanges(e){let t=[];for(let n of e){let e=await this.getOne(n.item_uid);if(e){e.stock=(Number(e.stock)||0)+n.quantity;for(let t of n.modifiers){let n=e.modifiers?.find(e=>e.uid===t.item_uid);n&&(n.stock=(Number(n.stock)||0)+t.quantity)}t.push(e)}}return t}convertFileToBase64(e){return new Promise((t,n)=>{let r=new FileReader;r.onloadend=()=>{typeof r.result==`string`?t(r.result.split(`,`)[1]):n(Error(`Could not convert file to Base64.`))},r.onerror=()=>n(Error(`File reading failed.`)),r.readAsDataURL(e)})}getFileExtension(e){let t=e.name,n=t.lastIndexOf(`.`);return n===-1||n===t.length-1?``:t.slice(n+1)}async cloneItem(e){let n=o.cloneDeep(e);if(n.uid=E.Item+t(),n.id_in_server=0,!n.modifier_categories||n.modifier_categories.length===0)return n;let r=[],i=[];for(let e of n.modifier_categories){let t=n.modifiers?.filter(t=>t.category_uid===e.uid);if(!t||t.length===0)continue;let{modifierCategory:a,modifiers:o}=await this.cloneModifiers(e,t);r.push(a),i.push(...o)}return n.modifier_categories=r,n.modifiers=i,n}async cloneModifiers(e,n){let r=o.cloneDeep(e);r.uid=E.ItemModifierCategory+t();let i=[];for(let e of n){let n=o.cloneDeep(e);n.uid=E.ItemModifier+t(),n.category_uid=r.uid,i.push(n)}return{modifierCategory:r,modifiers:i}}async copyModifierGroupToItems(e,t,n){if(!e||!t?.length||!n?.length)throw new D(`Invalid input parameters`);let r=[];for(let i of n){i.modifier_categories=i.modifier_categories||[],i.modifiers=i.modifiers||[];let{modifierCategory:n,modifiers:a}=await this.cloneModifiers(e,t);i.modifier_categories.push(n),i.modifiers.push(...a),r.push(i)}return await this.updateMany(r),r}sanitize(e){if(e.name&&(e.name=e.name.trim()),e.name_translations)for(let t in e.name_translations)e.name_translations[t]&&(e.name_translations[t]=e.name_translations[t].trim());if(e.type!==P.Combo)return e.combo_groups=[],e;if(!e.combo_groups?.length)return e;for(let t of e.combo_groups)for(let e of t.combo_items)delete e.combo_item;return e}},zr=class extends K{constructor(e,t,n,r=`categories`,i=`category`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async addSubcategory(e,t){return e.subcategories||(e.subcategories=[]),e.subcategories.push(t),e.has_subcategory||(e.has_subcategory=!0),e.id_in_server?await this.updateOne(e.id_in_server,e):await this.addOne(e),e}async updateSubcategory(e,t){if(!e.subcategories)throw e.subcategories=[],e.has_subcategory&&(e.has_subcategory=!1),new D(`Category does not have any subcategories`);let n=e.subcategories.findIndex(e=>e.uid===t.uid);if(n===-1)throw new D(`Subcategory not found`);return e.subcategories[n]=t,e.id_in_server?await this.updateOne(e.id_in_server,e):await this.addOne(e),e}async removeSubcategory(e,t){if(!e.subcategories)throw e.subcategories=[],e.has_subcategory&&(e.has_subcategory=!1),new D(`Category does not have any subcategories`);return e.subcategories=e.subcategories.filter(e=>e.uid!==t),e.id_in_server?await this.updateOne(e.id_in_server,e):await this.addOne(e),e}},Br=class extends K{constructor(e,t,n,r=`configs`,i=`config`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i,v(this,`configFactories`,{general:()=>new Rt,product:()=>new Lt,till:()=>new zt,report:()=>new Bt,receipt:()=>new Vt,kitchen:()=>new Ht,kds:()=>new Ut,label:()=>new Wt,order:()=>new Gt,payment:()=>new qt,user:()=>new Jt,tax:()=>new Yt,rounding:()=>new Qt,charges:()=>new Xt,currency:()=>new Zt,inventory:()=>new $t,pax_config:()=>new en,gto:()=>new tn,cash_drawer:()=>new nn,marketing:()=>new jt})}async updateConfig(e,t){let n=await this.getDefaultOne();n||(n=new xt);let r=this.configFactories[e],i=n.config[e]||{};return n.config[e]||(r&&typeof r==`function`?n.config[e]=r():n.config[e]={},i=n.config[e]),Object.keys(t).forEach(e=>{t[e]!==void 0&&(i[e]=t[e])}),n.id_in_server?this.updateOne(n.id_in_server,n):this.addOne(n)}async updateGeneralConfig(e){let t=await this.getDefaultOne();t||(t=new xt);let n=t.config.general;return Object.keys(e).forEach(t=>{e[t]!==void 0&&(n[t]=e[t])}),t.id_in_server?this.updateOne(t.id_in_server,t):this.addOne(t)}async updateCache(e){let t=await this.getDefaultOne();return t.cache={...t.cache,...e},t.id_in_server?this.updateOne(t.id_in_server,t):this.addOne(t)}async uploadFile(e){let t=a(),n=Dn(e);return await this.http.post(`api/v5/merchants/`+this.options.merchant_uid+`/upload-image`,new rn({base64:await On(e),name:t,extension:n})),{file_url:`${this.options.base_url}images/${t}.${n}`,thumbnail_url:`${this.options.base_url}images/${t}.thumbnail.${n}`}}},Vr=class extends K{constructor(e,t,n,r=`sections`,i=`section`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Hr=class extends K{constructor(e,t,n,r=`section_items`,i=`section_item`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async changeToTakeOut(e){let t=await this.getOne(e);if(!t)throw Error(`Item not found`);return t.is_take_out=!t.is_take_out,this.updateOne(t.id_in_server,t)}reset(e){e.total=0,e.pax=0,e.customer={}}syncInvoiceData(e,t){e.total=t.grand_total,e.pax=t.pax,e.customer={display_name:t.customer?.display_name||``,phone_number:t.customer?.phone_number||``}}},Ur=class extends K{constructor(e,t,n,r=`products`,i=`product`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Wr=class extends K{constructor(e,t,n,r=`shifts`,i=`shift`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i,v(this,`tillService`,void 0),this.tillService=new Gr(e,t,n)}async cashIn(e,t){let n=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status===k.Open).first();if(!n)throw new D(`No opening shift found`);let r=new j;return r.amount=e,r.type=A.CashIn,r.user_uid=n.user_uid,r.shift_uid=n.uid,r.note=t,this.tillService.addOne(r)}async cashOut(e,t){let n=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status===k.Open).first();if(!n)throw new D(`No opening shift found`);let r=new j;return r.amount=e,r.type=A.CashOut,r.user_uid=n.user_uid,r.shift_uid=n.uid,r.note=t,this.tillService.addOne(r)}async closeShift(e,t){let n=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status==k.Open).first();if(!n)throw new D(`No opening shift found`);return n.declared_amount=e,n.ended_at=new Date,n.user_uid=t,n.status=k.Closed,this.updateOne(n.id_in_server,n)}async openShift(e,t,n=``){console.log(`open shift entry`);let r=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status==k.Open).first();if(r)throw new D(`shift is already opened shift at ${r.started_at}`);let i=new de;if(i.started_at=new Date,i.user_uid=t,i.status=k.Open,await this.addOne(i),e>0){let r=new j;r.amount=e,r.type=A.OpenDeposit,r.user_uid=t,r.amount=e,r.shift_uid=i.uid,r.note=n,await this.tillService.addOne(r)}return console.log(`open shift end`),i}},Gr=class extends K{constructor(e,t,n,r=`tills`,i=`till`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}createCashInvoiceTill(e,t,n,r=``,i=``){let a=new j;return a.shift_uid=t,a.user_uid=n,a.note=r,a.invoice_uid=i,a.amount=q(e.filter(e=>e.payment_method.is_cash).map(e=>e.tender_amount-e.change_amount).reduce((e,t)=>e+t,0)),a.type=A.CashInvoice,a}},Kr=class extends K{constructor(e,t,n,r=`payment_methods`,i=`payment_method`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async syncStandardPaymentMethods(){try{let{data:e}=await this.http.get(`api/v5/merchants/`+this.options.merchant_uid+`/standard_payment_methods`),t=[];for(let n of e){let e=new tt(n),r=await this.getOneByParams({payment_method_code:e.payment_method_code}),i=e.toPaymentMethod();r?(i.uid=r.uid,i.id_in_server=r.id_in_server,i.sequence=r.sequence,i.is_disabled=r.is_disabled,i.is_integrated=r.is_integrated,i.api_id=r.api_id,i.api_key=r.api_key):(i.is_disabled=!0,await this.addOne(i)),t.push(i)}return t}catch(e){return console.error(`Failed to sync standard payment methods:`,e),[]}}async enablePaymentMethod(e){return e.is_disabled=!1,this.updateOne(e.id_in_server,e)}async disablePaymentMethod(e){return e.is_disabled=!0,this.updateOne(e.id_in_server,e)}async changeSequence(e,t){let n=(await this.db.table(this.moduleName).filter(e=>!e.is_disabled).sortBy(`sequence`)).filter(t=>t.id_in_server!==e.id_in_server);t<0&&(t=0),t>n.length&&(t=n.length),n.splice(t,0,e);let r=[];for(let e=0;e<n.length;e++)n[e].sequence!==e&&(n[e].sequence=e,r.push(n[e]));return r.length>0&&await this.updateMany(r),e}},qr=class extends K{constructor(e,t,n,r=`payments`,i=`payment`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async addPayment(e,t,n){let r=new Qe;r.invoice_uid=e.uid,r.tender_amount=t;let i=e.payments.reduce((e,t)=>e+t.tender_amount,0)+t;return n.is_cash&&i>=e.grand_total&&(r.change_amount=q(i-e.grand_total)),r.payment_method_uid=n.uid,r.payment_method_code=n.payment_method_code,r.payment_method_name=n.name,r.payment_method=o.cloneDeep(n),e.payments.push(r),e}async removePayment(e,t){return e.payments=e.payments.filter(e=>e.uid!==t),e}},Jr=class{async calibrateSequence(e){let t=await e.getAll();t.sort((e,t)=>e.sequence-t.sequence);let n=[];for(let e=0;e<t.length;e++){let r=t[e];r.sequence!==e&&(r.sequence=e,n.push(r))}await e.updateMany(n)}async changeSequence(e,t,n){if(n<0)throw new D(`Invalid target index.`);let r=Array.isArray(e),i=r?e:await e.getAll();if(i=i.filter(e=>e.deleted_at===null).sort((e,t)=>e.sequence-t.sequence),n>=i.length)throw new D(`Invalid target index.`);let a=i.findIndex(e=>e.uid==t.uid),o=new Map(i.map(e=>[e.uid,e.sequence]));a<n&&(n+=1),i.splice(n,0,null);let s=i.filter(e=>!(e&&e.uid===t.uid)).map((e,n)=>e===null?(t.sequence=n+1,t):(e.sequence=n+1,e)).filter(e=>o.get(e.uid)!==e.sequence);return r||await e.updateMany(s),s}},Yr=class extends K{constructor(e,t,n,r=`reports`,i=`report`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i,v(this,`invoiceService`,void 0),v(this,`tillService`,void 0),v(this,`paymentService`,void 0),v(this,`printerService`,void 0),v(this,`printTemplateService`,void 0),v(this,`printJobService`,void 0),v(this,`configService`,void 0),this.invoiceService=new Fr(e,t,n,`invoices`,`invoice`),this.tillService=new Gr(e,t,n,`tills`,`till`),this.paymentService=new qr(e,t,n,`payments`,`payment`),this.printerService=new En(e,t,n,`printers`,`printer`),this.printTemplateService=new Qr(e,t,n,`print_templates`,`print_template`),this.printJobService=new Xr(e,t,n,`print_jobs`,`print_job`),this.configService=new Br(e,t,n,`configs`,`config`)}async syncStandardReports(){let e=await this.getDefaultOne();e||(e=new _n);let t=await this.http.get(`api/v5/merchants/`+this.options.merchant_uid+`/standard_reports`);return e={...e,...t.data},e.updated_at=new Date,e.id_in_server?await this.updateOne(e.id_in_server,e):await this.addOne(e),e}async printReport(e){e.copies=e.copies||1;let t=await this.printerService.getDefaultReceiptPrinter();if(!t)throw new D(`No default receipt printer found`);let n=await this.printTemplateService.getOneByParams({report_code_name:e.report_code_name});if(!n)throw new D(`No print template found`);let r=await this.configService.getDefaultOne(),i=await this.getReportData(e,r.config?.order?.datetime_format,r.config?.currency?.currency_symbol||`$`),a=new V(t,await this.printTemplateService.renderReportPrintTemplate(i,r.config,n),!1,e.copies);await this.printJobService.addOne(a)}async getReportData(e,t,n=`$`){let r=new vn;if(e.shift_uid){await this.db.table(`shifts`).where(`uid`).equals(e.shift_uid).and(e=>e.deleted_at==null||e.deleted_at==null).first(),r.drawer_summary.declared_amount=e.declared_amount;let t=await this.db.table(`tills`).where(`shift_uid`).equals(e.shift_uid).and(e=>e.deleted_at==null).toArray();r.drawer_summary.open_amount=q(t.filter(e=>e.type==A.OpenDeposit).reduce((e,t)=>e+t.amount,0)),r.drawer_summary.pay_in_total=q(t.filter(e=>e.type==A.CashIn).reduce((e,t)=>e+t.amount,0)),r.drawer_summary.cash_invoice_total=q(t.filter(e=>e.type==A.CashInvoice).reduce((e,t)=>e+t.amount,0)),r.drawer_summary.cash_invoice_count=t.filter(e=>e.type==A.CashInvoice).length,r.drawer_summary.pay_in_count=t.filter(e=>e.type==A.CashIn).length,r.drawer_summary.pay_out_total=q(t.filter(e=>e.type==A.CashOut).reduce((e,t)=>e+t.amount,0)),r.drawer_summary.pay_out_count=t.filter(e=>e.type==A.CashOut).length,r.drawer_summary.drawer_amount=q(r.drawer_summary.open_amount+r.drawer_summary.pay_in_total+r.drawer_summary.cash_invoice_total-r.drawer_summary.pay_out_total),r.drawer_summary.difference=q(r.drawer_summary.drawer_amount-r.drawer_summary.declared_amount)}r.start_datetime=new Date(e.start_datetime).toISOString(),r.end_datetime=new Date(e.end_datetime).toISOString(),r.humanized_start_datetime=R(new Date(e.start_datetime),t),r.humanized_end_datetime=R(new Date(e.end_datetime),t),r.humanized_printed_datetime=R(new Date,t);let i=new f().addParam(`paid_at`,`GreaterThanOrEqualTo`,new Date(e.start_datetime).toISOString()).addParam(`paid_at`,`LessThanOrEqualTo`,new Date(e.end_datetime).toISOString()).addParam(`deleted_at`,`IsNull`,!0).includeTotal(!0),a=(await this.invoiceService.autoQuery(i,{timeout:6e5})).results||[];return this.processReportInvoicesData(r,a,n)}async processReportInvoicesData(e,t=[],n=`$`){let r=new Map,i=new Map,a=await this.db.table(`categories`).toArray(),o=new Map(a.map(e=>[e.uid,e])),s=new Map,c=new Map,l=(e,t,n)=>`${e}|${t}|${n.toFixed(4)}`,u=(e,t,r,i)=>e||(t===W.Percent?`${q(i*100)}% Discount`:`${n}${q(r)} Discount`),d=(e,t,n,r,i,a)=>{let o=l(t,n,n===W.Percent?i:r),s=e.get(o);s?(s.count++,s.total=q(s.total+a)):e.set(o,{name:t,alias:u(t,n,r,i),calc_type:n,amount:r,percent:i,count:1,total:q(a)})};t.forEach(t=>{t.status==U.Paid&&(e.sales_summary.paid_invoice_total+=t.grand_total,e.sales_summary.sales_total+=t.grand_total,e.sales_summary.paid_invoice_count++,e.sales_summary.rounding_total+=t.rounding,e.sales_summary.tax_total+=t.tax,e.sales_summary.service_charge_total+=t.service_charge,e.sales_summary.discount_total+=t.discount_amount,t.add_credit>0&&(e.loyalty_program_summary.add_credit_total+=t.add_credit,e.loyalty_program_summary.add_credit_count++,e.loyalty_program_summary.topup_paid_count++),t.rewarded_credit>0&&(e.loyalty_program_summary.rewarded_credit_total+=t.rewarded_credit,e.loyalty_program_summary.rewarded_credit_count++),t.minus_credit>0&&(e.loyalty_program_summary.minus_credit_total+=t.minus_credit,e.loyalty_program_summary.minus_credit_count++),t.rewarded_point>0&&(e.loyalty_program_summary.rewarded_point_total+=t.rewarded_point,e.loyalty_program_summary.rewarded_point_count++),t.minus_point>0&&(e.loyalty_program_summary.minus_point_total+=t.minus_point,e.loyalty_program_summary.minus_point_count++),e.sales_summary.total_pax+=t.pax,t.pax>0&&(e.sales_summary.pax_sales_total+=t.grand_total),t.lines.forEach(t=>{t.item.add_credit>0&&(e.loyalty_program_summary.topup_paid_total+=t.subtotal);let n=this.generateItemKey(t),a=r.get(n);if(a?(a.quantity+=t.quantity,a.total_amount=q(a.total_amount+t.subtotal),t.modifiers&&t.modifiers.length>0&&t.modifiers.forEach(e=>{let t=e.item.name.trim(),n=i.get(t);n?(n.quantity+=e.quantity,n.total_amount=q(n.total_amount+e.price*e.quantity)):(n=new wn,n.item=e.item,n.quantity=e.quantity,n.total_amount=q(e.price*e.quantity),i.set(t,n))})):(a=new Cn,a.item=t.item,a.quantity=t.quantity,a.total_amount=q(t.subtotal),a.modifiers=[],t.modifiers&&t.modifiers.length>0&&t.modifiers.forEach(e=>{let t={item:e.item,quantity:e.quantity,total_amount:q(e.price*e.quantity)};a.modifiers.push(t);let n=e.item.name.trim(),r=i.get(n);r?(r.quantity+=e.quantity,r.total_amount=q(r.total_amount+e.price*e.quantity)):(r=new wn,r.item=e.item,r.quantity=e.quantity,r.total_amount=q(e.price*e.quantity),i.set(n,r))}),r.set(n,a)),t.discount_amount||t.discount_percent){let e=t.subtotal_before_discount-t.subtotal;e>0&&d(c,``,t.discount_calc_type,t.discount_amount,t.discount_percent,e)}}),t.payments.forEach(t=>{let n=e.payments_summary.find(e=>e.code==t.payment_method_code);t.tender_amount||(t.tender_amount=t.change_amount),n?(n.count++,n.total=q(n.total+(t.tender_amount-t.change_amount))):e.payments_summary.push({code:t.payment_method_code,name:t.payment_method_name,count:1,total:q(t.tender_amount-t.change_amount)})}),t.discounts?.forEach(e=>{let t=e.applying_item_uids&&e.applying_item_uids.length>0,n=e.calc_type===W.Percent?e.percent_amount:e.amount;d(t?c:s,e.name||``,e.calc_type,e.amount,e.percent,n)})),t.status==U.Paid&&t.is_sales_exclusive&&(e.sales_summary.foc_sales_total+=t.grand_total,e.sales_summary.foc_sales_count++,e.sales_summary.foc_rounding_total+=t.rounding,e.sales_summary.foc_tax_total+=t.tax,e.sales_summary.foc_service_charge_total+=t.service_charge),t.status==U.Void&&(e.sales_summary.void_invoice_total+=t.grand_total,e.sales_summary.void_invoice_count++)});let f=Array.from(r.values());f.sort((e,t)=>{let n=o.get(e.item.category_uid),r=o.get(t.item.category_uid),i=n?.sequence??999999,a=r?.sequence??999999;return i===a?(e.item.sequence??999999)-(t.item.sequence??999999):i-a}),e.item_sales_summary=f;let p=0,m=0,h=new Map;f.forEach(e=>{if(p+=e.total_amount,m+=e.quantity,!e.item.category_uid)return;let t=e.item.category_uid,n=h.get(t);n||(n=new Tn,n.category=o.get(e.item.category_uid)||null,h.set(t,n)),n.items.push(e),n.total_quantity+=e.quantity,n.total_amount+=e.total_amount}),e.item_sales_summary_total=q(p),e.item_sales_summary_total_count=m;let g=Array.from(h.values());g.sort((e,t)=>(e.category?.sequence??999999)-(t.category?.sequence??999999)),g.forEach(e=>{e.total_amount=q(e.total_amount),e.items.sort((e,t)=>t.total_amount===e.total_amount?t.quantity-e.quantity:t.total_amount-e.total_amount)}),e.item_sales_summary_by_category=g;let _=Array.from(i.values());_.sort((e,t)=>t.quantity===e.quantity?t.total_amount-e.total_amount:t.quantity-e.quantity),e.modifier_sales_summary=_;let v=0,y=0;return e.modifier_sales_summary.forEach(e=>{v+=e.total_amount,y+=e.quantity}),e.modifier_sales_summary_total=q(v),e.modifier_sales_summary_total_count=y,e.invoice_discount_summary=Array.from(s.values()),e.item_discount_summary=Array.from(c.values()),e.sales_summary.paid_invoice_total=q(e.sales_summary.paid_invoice_total),e.sales_summary.sales_total=q(e.sales_summary.sales_total),e.sales_summary.rounding_total=q(e.sales_summary.rounding_total),e.sales_summary.tax_total=q(e.sales_summary.tax_total),e.sales_summary.service_charge_total=q(e.sales_summary.service_charge_total),e.sales_summary.discount_total=q(e.sales_summary.discount_total),e.sales_summary.foc_sales_total=q(e.sales_summary.foc_sales_total),e.sales_summary.foc_rounding_total=q(e.sales_summary.foc_rounding_total),e.sales_summary.foc_tax_total=q(e.sales_summary.foc_tax_total),e.sales_summary.foc_service_charge_total=q(e.sales_summary.foc_service_charge_total),e.sales_summary.void_invoice_total=q(e.sales_summary.void_invoice_total),e.sales_summary.pax_sales_total=q(e.sales_summary.pax_sales_total),e.loyalty_program_summary.add_credit_total=q(e.loyalty_program_summary.add_credit_total),e.loyalty_program_summary.topup_paid_total=q(e.loyalty_program_summary.topup_paid_total),e.loyalty_program_summary.rewarded_credit_total=q(e.loyalty_program_summary.rewarded_credit_total),e.loyalty_program_summary.minus_credit_total=q(e.loyalty_program_summary.minus_credit_total),e}generateItemKey(e){let t=e.item.uid;if(e.modifiers&&e.modifiers.length>0){let n=[...e.modifiers].sort((e,t)=>{let n=`${e.item.name.trim()}:${e.quantity}`,r=`${t.item.name.trim()}:${t.quantity}`;return n.localeCompare(r)}).map(e=>`${e.item.uid}:${e.quantity}`);t+=`-`+n.join(`-`)}return t}},Xr=class extends K{constructor(e,t,n,r=`print_jobs`,i=`print_job`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async autoquery(e){let t=e.build();return await this.http.get(`sapi/v5/merchants/${this.options.merchant_uid}/${this.moduleName}`,{params:{...t}})}replacePrinter(e,t){return e.printer_name=t.name,e.printer_ip=t.ip_address,e.printer_type=t.type,e.printer_uid=t.uid,e.driver_printer_name=t.driver_printer_name,t.protocol&&(e.protocol=t.protocol),t.connection_type&&(e.connection_type=t.connection_type),e.usb_serial_number=t.usb_serial_number,e.use_device_name=t.use_device_name,e.usb_device_name=t.usb_device_name,t.print_sequence!==void 0&&(e.print_sequence=t.print_sequence),e}},Zr=class extends K{constructor(e,t,n,r=`menus`,i=`menu`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Qr=class extends K{constructor(e,t,n,r=`print_templates`,i=`print_template`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i,v(this,`httpClient`,void 0),v(this,`secretKey`,`tKB84ZlZRzLzA2LcglNNLquucKZwtJApRTaPKjAJHFbDd8nJRD`),this.httpClient=s.create({baseURL:`https://revopos-cdn.sgp1.digitaloceanspaces.com`,timeout:3e3})}async initialize(){if(!await this.getOneByParams({printer_type:z.ReceiptPrinter})){let e=new B;e.name=`Default Receipt Template`,e.body=await this.getPrintTemplate(`rbt`),e.header=await this.getPrintTemplate(`rht`),e.footer=await this.getPrintTemplate(`rft`),e.printer_type=z.ReceiptPrinter,await this.addOne(e),console.log(`Default Receipt Template added`)}if(!await this.getOneByParams({printer_type:z.CheckPrinter})){let e=new B;e.name=`Default Check Template`,e.body=await this.getPrintTemplate(`cbt`),e.header=await this.getPrintTemplate(`cht`),e.footer=await this.getPrintTemplate(`cft`),e.printer_type=z.CheckPrinter,await this.addOne(e),console.log(`Default Check Template added`)}if(!await this.getOneByParams({printer_type:z.OrderPrinter})){let e=new B;e.name=`Default docket Template`,e.body=await this.getPrintTemplate(`obt`),e.header=await this.getPrintTemplate(`oht`),e.footer=await this.getPrintTemplate(`oft`),e.printer_type=z.OrderPrinter,await this.addOne(e),console.log(`Default Order Template added`)}if(!await this.getOneByParams({printer_type:z.KitchenPrinter})){let e=new B;e.name=`Default Kitchen Template`,e.body=await this.getPrintTemplate(`kbt`),e.header=await this.getPrintTemplate(`kht`),e.footer=await this.getPrintTemplate(`kft`),e.printer_type=z.KitchenPrinter,await this.addOne(e),console.log(`Default Kitchen Template added`)}if(!await this.getOneByParams({printer_type:z.KioskPrinter})){let e=new B;e.name=`Default Kiosk Template`,e.body=await this.getPrintTemplate(`kioskbt`),e.header=await this.getPrintTemplate(`kioskht`),e.footer=await this.getPrintTemplate(`kioskft`),e.printer_type=z.KioskPrinter,await this.addOne(e),console.log(`Default Kiosk Template added`)}if(!await this.getOneByParams({printer_type:z.KitchenDisplayPrinter})){let e=new B;e.name=`Default Kitchen Display Template`,e.body=await this.getPrintTemplate(`kdsbt`),e.header=await this.getPrintTemplate(`kdsht`),e.footer=await this.getPrintTemplate(`kdsft`),e.printer_type=z.KitchenDisplayPrinter,await this.addOne(e),console.log(`Default Kitchen Display Template added`)}if(!await this.getOneByParams({printer_type:z.LabelPrinter})){let e=new B;e.commands=await this.getPrintTemplate(`tspl_cmds`),e.name=`Default Label Template`,e.printer_type=z.LabelPrinter,await this.addOne(e)}if(!await this.getOneByParams({printer_type:z.QrCodePrinter})){let e=new B;e.name=`Default QR Code Template`,e.body=await this.getPrintTemplate(`qrbt`),e.header=await this.getPrintTemplate(`qrht`),e.footer=await this.getPrintTemplate(`qrft`),e.printer_type=z.QrCodePrinter,await this.addOne(e)}if(!await this.getOneByParams({report_code_name:`sales_summary_report`})){let e=new B;e.name=`Sales Summary Report`,e.body=await this.getPrintTemplate(`sumbt`),e.header=await this.getPrintTemplate(`sumht`),e.footer=await this.getPrintTemplate(`sumft`),e.report_code_name=`sales_summary_report`,await this.addOne(e),console.log(`Sales Summary Report Template added`)}if(!await this.getOneByParams({report_code_name:`shift_report`})){let e=new B;e.name=`Shift Report`,e.body=await this.getPrintTemplate(`sbt`),e.header=await this.getPrintTemplate(`sht`),e.footer=await this.getPrintTemplate(`sft`),e.report_code_name=`shift_report`,await this.addOne(e),console.log(`Shift Report Template added`)}if(!await this.getOneByParams({report_code_name:`item_sales_report`})){let e=new B;e.name=`Item Sales Report`,e.body=await this.getPrintTemplate(`isrbt`),e.header=await this.getPrintTemplate(`isrht`),e.footer=await this.getPrintTemplate(`isrft`),e.report_code_name=`item_sales_report`,await this.addOne(e),console.log(`Item Sales Report Template added`)}if(!await this.getOneByParams({report_code_name:`modifier_sales_report`})){let e=new B;e.name=`Modifier Sales Report`,e.body=await this.getPrintTemplate(`msrbt`),e.header=await this.getPrintTemplate(`msrht`),e.footer=await this.getPrintTemplate(`msrft`),e.report_code_name=`modifier_sales_report`,await this.addOne(e),console.log(`Modifier Sales Report Template added`)}}async renderPrintTemplate(e,t,n,r=new H){let i=new L;n.printer_type==z.KitchenPrinter||n.printer_type==z.OrderPrinter?i.codepage=n.codepage||this.getCodepageByCountryCode(t.kitchen.language):i.codepage=n.codepage||this.getCodepageByCountryCode(t.receipt.language);let a=new Ze;return a.invoice=e,a.config=t,a.normalized_printed_at=R(a.printed_at,t?.order?.datetime_format),a.printer_name=r.printer_name,r.is_cancel&&(a.is_cancel=r.is_cancel),i.items.push(...await this.renderPrintCommand(n.header,a)),i.items.push(...await this.renderPrintCommand(n.body,a)),i.items.push(...await this.renderPrintCommand(n.footer,a)),i}async renderReportPrintTemplate(e,t,n,r=new H){let i=new L,a=new Ze;return a.report_data=e,a.config=t,a.normalized_printed_at=R(a.printed_at,t?.order?.datetime_format),i.codepage=n.codepage||F.SimplifiedChinese,i.items.push(...await this.renderPrintCommand(n.header,a)),i.items.push(...await this.renderPrintCommand(n.body,a)),i.items.push(...await this.renderPrintCommand(n.footer,a)),i}async renderPrintTemplateByData(e,t,n=new H){let r=new L;return r.items.push(...await this.renderPrintCommand(e.header,t)),r.items.push(...await this.renderPrintCommand(e.body,t)),r.items.push(...await this.renderPrintCommand(e.footer,t)),r}async getPrintTemplate(e){let t=await this.httpClient.get(`/xpos-core/${e}.enc`,{responseType:`text`});return c.AES.decrypt(t.data,this.secretKey).toString(c.enc.Utf8)}getCodepageByCountryCode(e){let t={US:F.English,GR:F.Greek,DE:F.WesternEurope,LT:F.BalticRim,PL:F.CentralEurope,RU:F.Cyrillic,TR:F.Turkish,EU:F.MultilingualLatin1WithEuro,PT:F.Portuguese,IS:F.Icelandic,IL:F.Hebrew,CA:F.FrenchCanadian,EG:F.Arabic,NO:F.Nordic,BY:F.Russian,MK:F.ModernGreek,CN:F.SimplifiedChinese,KR:F.Korean,TW:F.TraditionalChinese,FR:F.WesternEuropeanLatin,AE:F.ArabicISO,JP:F.Japanese,CZ:F.CentralEuropeanLatinWindows,BG:F.CyrillicWindows,ES:F.WesternEuropeanLatinWindows,CY:F.GreekWindows,AZ:F.TurkishWindows,PS:F.HebrewWindows,SA:F.ArabicWindows,LV:F.BalticWindows,VN:F.Vietnamese};return e&&t[e.toUpperCase()]||t.CN}async renderPrintCommand(e,t){try{let n=new l(!0),r=JSON.parse(e);console.log(`template`,JSON.stringify(r)),console.log(`templateData`,JSON.stringify(t));let i=await n.transform(r,t,!1);return i=o.flatMap(i,e=>e),i=o.compact(i),i}catch(e){throw console.error(e),e}}},$r=class extends K{constructor(e,t,n,r=`storages`,i=`storage`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},ei=class extends K{constructor(e,t,n,r=`stock_logs`,i=`stock_log`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},ti=class extends K{constructor(e,t,n,r=`appointments`,i=`appointment`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}};function ni(e,t,n){let r=s.create({baseURL:e,timeout:2e4,headers:{"x-device-uid":t,Authorization:`Bearer ${n}`}});return r.interceptors.response.use(function(e){return e.data},function(e){return Promise.reject(e)}),r}const ri=new Map([[`Item`,Rr],[`Section`,Vr],[`SectionItem`,Hr],[`Category`,zr],[`Config`,Br],[`Shift`,Wr],[`Till`,Gr],[`Employee`,Lr],[`PaymentMethod`,Kr],[`Invoice`,Fr],[`Report`,Yr],[`Printer`,En],[`PrintJob`,Xr],[`PrintTemplate`,Qr],[`EmployeeRole`,Ir],[`OrderDisplay`,Ar],[`Storage`,$r],[`Menu`,Zr],[`StockLog`,ei],[`Appointment`,ti]]),Z=`uid, updated_at, created_at, deleted_at, _timestamp, id_in_server, created_at_timestamp`,Q=`${Z}, sequence`,ii=`${Q}, status`,ai=`${Z}, till_type, shift_uid, invoice_uid`,oi=`${Q}, payment_method_code, is_disabled`,si=`${Z}, type, status, table_uid`,ci=`${Q}, name, barcode, codename`,li=`${Z}, status, printer_type, connection_type, protocol, save_only, device_uid_to_print`,ui=`${Z}, name, printer_type`,di=`${Z}, order_number, status`,fi=`${Z}, model`,pi={items:ci,sections:Q,section_items:Q,categories:Q,shifts:ii,tills:ai,employees:`${Z}, role_uid`,payment_methods:oi,invoices:si,configs:Z,reports:Z,printers:Z,print_jobs:li,print_templates:ui,employee_roles:`${Z}, name, is_default`,order_displays:di,storages:fi,menus:Z,stock_logs:`${Z}, entity_type, entity_uid, type`,appointments:`${Z}, status, scheduled_at, employee_uid, customer_id`};var $=function(e){return e.DISCONNECTED=`disconnected`,e.CONNECTED=`connected`,e.ERROR=`error`,e}($||{}),mi=class e{constructor(e,t,n=!1){this.options=e,this.win=t,v(this,`mode`,void 0),v(this,`http`,void 0),v(this,`dataSource`,void 0),v(this,`status`,$.DISCONNECTED),this.mode=e.mode,this.http=ni(e.base_url,e.device_uid,e.token),n||this.initializeDatabase(),De.setWindow(t)}static async init(t,n,r=!1){let i=new e(t,n,!0);return r||await i.initializeDatabase(),i}async initializeDatabase(){try{if(!this.options.database||!this.options.database.name)throw Error(`Database name is not defined`);this.dataSource=await new r(this.options.database.name),this.dataSource.version(30).stores(pi),this.status=$.CONNECTED}catch(e){this.status=$.ERROR,console.error(`Database connection error:`,e)}return this.dataSource}async dropDatabase(){await r.delete(this.options.database.name),await this.initializeDatabase()}clearTableData(e){return this.dataSource.table(e).clear()}async getService(e){if(this.status==$.ERROR)throw Error(`Database connection error`);for(;this.status==$.DISCONNECTED;)await new Promise(e=>setTimeout(e,100));try{return new e(this.http,this.dataSource,this.options)}catch(e){throw Error(`Service instantiation error: `+e?.message)}}async getServiceByName(e){if(this.status==$.ERROR)throw Error(`Database connection error`);for(;this.status==$.DISCONNECTED;)await new Promise(e=>setTimeout(e,100));try{let t=ri.get(e);if(!t)throw Error(`No service found for model: ${e}`);return new t(this.http,this.dataSource,this.options)}catch(e){throw Error(`Service instantiation error: `+e?.message)}}};async function hi(e){if(!e)return``;let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,12).toUpperCase()}const gi={v1:{headers:[`Type`,`Name`,`SKU`,`Price`,`Stock`,`Is Internal`,`Min Order`,`Max Order`,`Image URL`,`Thumbnail URL`,`Sequence`]},v2:{headers:[`Type`,`Name`,`SKU`,`Price`,`Stock`,`Is Internal`,`Min Order`,`Max Order`,`Image URL`,`Thumbnail URL`,`Sequence`,`Item UID`]},v3:{headers:[`Type`,`Name`,`SKU`,`Price`,`Stock`,`Is Internal`,`Min Order`,`Max Order`,`Image URL`,`Thumbnail URL`,`Sequence`,`Item UID`,`Print On Receipt`,`Discountable`,`Open Editor Panel`,`Is Delisted`,`Name Translations`]},v4:{headers:[`Type`,`Name`,`SKU`,`Price`,`Stock`,`Is Internal`,`Min Order`,`Max Order`,`Image URL`,`Thumbnail URL`,`Sequence`,`Item UID`,`Print On Receipt`,`Discountable`,`Open Editor Panel`,`Is Delisted`,`Name Translations`,`Prices`]},v5:{headers:[`Type`,`Name`,`SKU`,`Price`,`Stock`,`Is Internal`,`Min Order`,`Max Order`,`Image URL`,`Thumbnail URL`,`Sequence`,`Item UID`,`Print On Receipt`,`Discountable`,`Open Editor Panel`,`Is Delisted`,`Name Translations`,`Prices`,`PLU`,`Code`]}},_i=[`category`,`subcategory`,`product`,`modifier_category`,`modifier`,`combo`,`combo_group`,`combo_item`];function vi(e,t,n=`export.csv`){return bi(wi(e,t,e=>e.code||``,e=>e.plu||``))}async function yi(e,t){let n=new Map,r=new Map;for(let t of e){let e=t.code||(t.name?await hi(`${t.name}|CAT`):``);n.set(t,e),t.uid&&r.set(t.uid,e)}let i=new Map,a=new Map;for(let e of t){let t=e.price??0,n=e.plu||(e.name?await hi(`${e.name}|${t.toFixed(2)}`):``);i.set(e,n),e.uid&&a.set(e.uid,n)}return{blob:bi(wi(e,t,e=>n.get(e)||``,e=>i.get(e)||``)),productPluByUid:a,categoryCodeByUid:r}}function bi(e){let t=Ei(e);return new Blob([``+t],{type:`text/csv;charset=utf-8;`})}function xi(e){if(!(e==null||e===``)){if(typeof e==`number`&&!isNaN(e))return e;if(typeof e==`string`){let t=parseFloat(e);return isNaN(t)?void 0:t}}}function Si(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e);return t.length===0?``:t.map(([e,t])=>`${e}:${t}`).join(`|`)}function Ci(e){if(!e||!e.trim())return{};let t={};for(let n of e.split(`|`)){let e=n.indexOf(`:`);e>0&&(t[n.slice(0,e).trim()]=n.slice(e+1).trim())}return t}function wi(e,t,n,r){let i=[],a=new Map;for(let e of t)a.has(e.category_uid)||a.set(e.category_uid,[]),a.get(e.category_uid).push(e);for(let t of e){let e=n(t);i.push({type:`category`,name:t.name,sku:``,price:void 0,stock:void 0,is_internal:t.is_internal,min_order:void 0,max_order:void 0,image_url:t.image_url||``,image_thumbnail_url:t.image_thumbnail_url||``,sequence:t.sequence,is_delisted:t.is_delisted,name_translations:Si(t.name_translations),code:e});let o=a.get(t.uid)||[];if(t.has_subcategory&&t.subcategories&&t.subcategories.length>0){let e=new Map;for(let n of t.subcategories)e.set(n.uid,n);let n=new Map,a=[];for(let t of o)t.subcategory_uid&&e.has(t.subcategory_uid)?(n.has(t.subcategory_uid)||n.set(t.subcategory_uid,[]),n.get(t.subcategory_uid).push(t)):a.push(t);for(let e of a)Ti(i,e,r);for(let e of t.subcategories){i.push({type:`subcategory`,name:e.name,sku:``,sequence:e.sequence,name_translations:Si(e.name_translations)});let t=n.get(e.uid)||[];for(let e of t)Ti(i,e,r)}}else for(let e of o)Ti(i,e,r)}return i}function Ti(e,t,n){let r=t.type===P.Combo,i=n(t);if(e.push({type:r?`combo`:`product`,name:t.name,sku:t.sku||``,price:t.price,stock:xi(t.stock),is_internal:t.is_internal,min_order:void 0,max_order:void 0,image_url:t.image_url||``,image_thumbnail_url:t.image_thumbnail_url||``,sequence:t.sequence,print_on_receipt:t.print_on_receipt,discountable:t.discountable,open_editor_panel:t.open_editor_panel,is_delisted:t.is_delisted,name_translations:Si(t.name_translations),item_uid:t.uid,prices:t.prices?.length?t.prices:void 0,plu:i}),r&&t.combo_groups&&t.combo_groups.length>0){for(let n of t.combo_groups)if(e.push({type:`combo_group`,name:n.name,sku:``,price:void 0,stock:void 0,is_internal:void 0,min_order:n.min_order,max_order:n.max_order,image_url:``,image_thumbnail_url:``,sequence:n.sequence}),n.combo_items&&n.combo_items.length>0)for(let t of n.combo_items)e.push({type:`combo_item`,name:t.combo_item?.name||``,sku:``,price:t.price,stock:void 0,is_internal:void 0,min_order:void 0,max_order:void 0,image_url:``,image_thumbnail_url:``,sequence:t.sequence,item_uid:t.item_uid})}if(!r&&t.modifier_categories&&t.modifier_categories.length>0){for(let n of t.modifier_categories)if(e.push({type:`modifier_category`,name:n.name,sku:``,price:void 0,stock:void 0,is_internal:void 0,min_order:n.min_order,max_order:n.max_order,image_url:``,image_thumbnail_url:``,sequence:n.sequence}),t.modifiers&&t.modifiers.length>0){let r=t.modifiers.filter(e=>e.category_uid===n.uid);for(let t of r)e.push({type:`modifier`,name:t.name,sku:t.sku||``,price:t.price,stock:xi(t.stock),is_internal:t.is_internal,min_order:void 0,max_order:void 0,image_url:t.image_url||``,image_thumbnail_url:t.image_thumbnail_url||``,sequence:t.sequence,print_on_receipt:t.print_on_receipt,name_translations:Si(t.name_translations),prices:t.prices?.length?t.prices:void 0})}}}function Ei(e){let t=[gi.v5.headers.join(`,`)];for(let n of e)try{let e=n.prices?.length?`"${JSON.stringify(n.prices).replace(/"/g,`""`)}"`:``,r=[n.type,`"${n.name.replace(/"/g,`""`)}"`,n.sku||``,n.price===void 0?``:n.price.toString(),n.stock===void 0?``:n.stock.toString(),n.is_internal===void 0?``:n.is_internal.toString(),n.min_order===void 0?``:n.min_order.toString(),n.max_order===void 0?``:n.max_order.toString(),n.image_url||``,n.image_thumbnail_url||``,n.sequence===void 0?``:n.sequence.toString(),n.item_uid||``,n.print_on_receipt===void 0?``:n.print_on_receipt.toString(),n.discountable===void 0?``:n.discountable.toString(),n.open_editor_panel===void 0?``:n.open_editor_panel.toString(),n.is_delisted===void 0?``:n.is_delisted.toString(),n.name_translations?`"${n.name_translations.replace(/"/g,`""`)}"`:``,e,n.plu?`"${n.plu.replace(/"/g,`""`)}"`:``,n.code?`"${n.code.replace(/"/g,`""`)}"`:``];t.push(r.join(`,`))}catch(e){throw Error(`Export failed on "${n.name}" (type: ${n.type}): ${e.message}`)}return t.join(`
|
|
3
|
-
`)}async function Di(e){return Ni(ji(await e.text()))}function Oi(e){let t=Mi(e).map(e=>e.trim());return t.includes(`PLU`)||t.includes(`Code`)?`v5`:t.includes(`Prices`)?`v4`:t.includes(`Print On Receipt`)||t.includes(`Name Translations`)?`v3`:t.includes(`Item UID`)?`v2`:`v1`}function ki(e,t,n){let r=e?.trim().toLowerCase();if(r){if(r===`true`)return!0;if(r===`false`)return!1;throw Error(`Invalid ${t} "${e}" at line ${n}. Must be: true or false`)}}function Ai(e,t){if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))throw Error(`not an array`);return t.map(e=>{let t=new
|
|
1
|
+
import e from"dayjs";import{nanoid as t}from"nanoid";import n from"wcwidth";import{Dexie as r,liveQuery as i}from"dexie";import{v4 as a}from"uuid";import*as o from"lodash";import s from"axios";import c from"crypto-js";import{SelectTransform as l}from"selecttransform";import{NetworkInterface as u}from"@awesome-cordova-plugins/network-interface";import d from"handlebars";import{QueryBuilder as f}from"@litepos/autoquery";import p from"bcryptjs";var m=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){if(typeof require<`u`)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function.")});function h(e){"@babel/helpers - typeof";return h=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},h(e)}function g(e,t){if(h(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(h(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function _(e){var t=g(e,`string`);return h(t)==`symbol`?t:t+``}function v(e,t,n){return(t=_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var y=class{constructor(){v(this,`address1`,``),v(this,`address2`,``),v(this,`lat`,``),v(this,`lng`,``),v(this,`postcode`,``),v(this,`note`,``),v(this,`is_default`,!1),v(this,`name`,``),v(this,`salute`,``),v(this,`phone_number`,``)}},b=class{constructor(){v(this,`id`,0),v(this,`ref_id`,``),v(this,`image_url`,``),v(this,`stripe_token`,``),v(this,`stripe_customer_id`,``),v(this,`username`,``),v(this,`normalized_username`,``),v(this,`company`,``),v(this,`ic`,``),v(this,`display_name`,``),v(this,`full_name`,``),v(this,`birth_date`,``),v(this,`gender`,``),v(this,`address`,``),v(this,`postcode`,``),v(this,`note`,``),v(this,`language`,``),v(this,`time_zone`,``),v(this,`created_at`,new Date),v(this,`updated_at`,new Date),v(this,`license_ids`,``),v(this,`security_stamp`,``),v(this,`phone_number`,``)}},x=class extends b{constructor(){super(),v(this,`license_id`,0),v(this,`credit`,0),v(this,`point`,0),v(this,`transaction_total`,0),v(this,`transaction_time`,0),v(this,`user_group_id`,0),v(this,`user_group_name`,``),v(this,`group_expires_at`,null),v(this,`error`,``)}},S=function(e){return e[e.All=1]=`All`,e[e.Inclusive=2]=`Inclusive`,e[e.Exclusive=3]=`Exclusive`,e}(S||{}),C=function(e){return e[e.Flat=1]=`Flat`,e[e.Percent=2]=`Percent`,e}(C||{}),ee=class{constructor(){v(this,`applying_type`,S.Inclusive),v(this,`applying_items`,[])}},te=class{constructor(e){v(this,`guid`,``),v(this,`promo_code`,``),v(this,`is_multi_stores`,!1),v(this,`name`,``),v(this,`alias`,void 0),v(this,`description`,void 0),v(this,`description_alias`,void 0),v(this,`applying_plus`,void 0),v(this,`applying_user_tags`,void 0),v(this,`applying_user_groups`,void 0),v(this,`discount_calc_type`,C.Flat),v(this,`discount_amount`,void 0),v(this,`discount_percent`,void 0),v(this,`duration`,30),v(this,`usage_count`,0),v(this,`usage_limit_per_invoice`,1),v(this,`above_invoice_amount`,void 0),v(this,`below_invoice_amount`,void 0),v(this,`is_delivery_free`,!1),v(this,`is_individual_use`,!0),v(this,`price_in_points`,void 0),v(this,`styles`,{}),v(this,`expired_at`,void 0),v(this,`auto_gen`,!1),v(this,`can_sell`,!0),v(this,`can_redeem`,!0),e&&(this.guid=e.guid,this.promo_code=e.promo_code,this.is_multi_stores=e.is_multi_stores,this.name=e.name,this.alias=e.alias,this.description=e.description,this.description_alias=e.description_alias,this.applying_plus=e.applying_plus,this.applying_user_tags=e.applying_user_tags,this.applying_user_groups=e.applying_user_groups,this.discount_calc_type=e.discount_calc_type,this.discount_amount=e.discount_amount,this.discount_percent=e.discount_percent,this.duration=e.duration,this.usage_count=e.usage_count,this.usage_limit_per_invoice=e.usage_limit_per_invoice,this.above_invoice_amount=e.above_invoice_amount,this.below_invoice_amount=e.below_invoice_amount,this.is_delivery_free=e.is_delivery_free,this.is_individual_use=e.is_individual_use,this.price_in_points=e.price_in_points,this.styles={...e.styles},this.expired_at=e.expired_at,this.auto_gen=e.auto_gen,this.can_sell=e.can_sell,this.can_redeem=e.can_redeem)}},ne=class{constructor(e){v(this,`invoice_uid`,``),e&&(this.invoice_uid=e.invoice_uid)}},re=class{constructor(e){v(this,`guid`,``),v(this,`coupon`,new te),v(this,`is_multi_stores`,!1),v(this,`usage`,new ne),v(this,`employee_uid`,``),v(this,`promo_code`,``),v(this,`is_expired`,!1),v(this,`is_redeemed`,!1),v(this,`is_generated`,!1),e&&(this.guid=e.guid,this.coupon=new te(e.coupon),this.is_multi_stores=e.is_multi_stores,this.usage=new ne(e.usage),this.employee_uid=e.employee_uid,this.promo_code=e.promo_code,this.is_expired=e.is_expired,this.is_redeemed=e.is_redeemed,this.is_generated=e.is_generated)}};const ie={from(t){return e(t).format(`YYYY-MM-DD HH:mm:ss`)},to(e){return e}};var w=class{constructor(){v(this,`uid`,void 0),v(this,`updated_at`,new Date),v(this,`created_at`,new Date),v(this,`created_at_timestamp`,new Date().getTime()),v(this,`deleted_at`,null),v(this,`_timestamp`,void 0),v(this,`id_in_server`,void 0)}},T=class extends w{constructor(){super(),v(this,`name`,void 0),v(this,`name_translations`,{})}},ae=class extends T{constructor(...e){super(...e),v(this,`description`,void 0),v(this,`description_translations`,{})}};let E=function(e){return e.Merchant=`mnt_`,e.Section=`sec_`,e.SectionItem=`sit_`,e.Category=`cat_`,e.Subcategory=`sat_`,e.Item=`itm_`,e.ItemModifier=`iod_`,e.ItemModifierCategory=`imc_`,e.Config=`cfg_`,e.Device=`dev_`,e.Invoice=`inv_`,e.InvoiceLine=`iln_`,e.InvoiceCharge=`ich_`,e.Payment=`pay_`,e.Employee=`emp_`,e.Shift=`shf_`,e.Till=`til_`,e.ReportCategory=`rpc_`,e.Report=`rpt_`,e.AppReport=`apr_`,e.PaymentMethod=`pmd_`,e.PrintTemplate=`ptl_`,e.PrintJob=`pjb_`,e.Printer=`prt_`,e.InvoiceDiscount=`ind_`,e.EmployeeRole=`emr_`,e.OrderDisplaySystem=`ods_`,e.Charge=`chr_`,e.Price=`prc_`,e.ComboGroup=`cbo_`,e.Storage=`sto_`,e.Menu=`men_`,e.StockLog=`stl_`,e.Appointment=`apt_`,e.AppointmentServiceLine=`asl_`,e}({}),oe=function(e){return e.Merchant=`mnt`,e.Section=`sec`,e.SectionItem=`sit`,e.Category=`cat`,e.Subcategory=`sat`,e.Item=`itm`,e.Config=`cfg`,e.Device=`dev`,e.Invoice=`inv`,e}({}),se=function(e){return e.LOCAL=`local`,e.CLOUD=`cloud`,e}({});var ce=class{constructor(){v(this,`mode`,void 0),v(this,`base_url`,void 0),v(this,`device_uid`,void 0),v(this,`merchant_uid`,void 0),v(this,`token`,void 0),v(this,`database`,void 0)}};let le=function(e){return e.Data=`DataMessage`,e.Event=`EventMessage`,e}({});var ue=class{constructor(){v(this,`model`,``),v(this,`data`,``),v(this,`has_many`,!1),v(this,`type`,le.Data)}},D=class extends Error{constructor(e){super(e),this.name=`system_error`}};let O=function(e){return e.outdatedInvoice=`outdated invoice`,e.outdatedSectionItem=`outdated section item`,e.outdatedSourceSectionItem=`outdated source section item`,e.outdatedTargetSectionItem=`outdated target section item`,e}({}),k=function(e){return e.Open=`opened`,e.Closed=`closed`,e}({});var de=class extends w{constructor(){super(),v(this,`user_uid`,``),v(this,`started_at`,new Date),v(this,`ended_at`,new Date),v(this,`declared_amount`,0),v(this,`drawer_amount`,0),v(this,`first_invoice_number`,0),v(this,`status`,k.Open),v(this,`uid`,E.Shift+t())}};let A=function(e){return e.OpenDeposit=`open_deposit`,e.CashDeposit=`cash_deposit`,e.CashIn=`cash_in`,e.CashOut=`cash_out`,e.CashInvoice=`cash_invoice`,e}({});var j=class extends w{constructor(){super(),v(this,`user_uid`,``),v(this,`shift_uid`,``),v(this,`invoice_uid`,``),v(this,`type`,A.CashDeposit),v(this,`amount`,0),v(this,`note`,``),v(this,`uid`,E.Till+t())}};let M=function(e){return e.CLOSED=`closed`,e.OPENED=`opened`,e.PAYMENT=`payment`,e}({});var fe=class extends T{constructor(){super(),v(this,`printer_id_order_list`,[]),v(this,`order_printer_uids`,[]),v(this,`receipt_printer_uid`,``),v(this,`check_printer_uid`,``),v(this,`qr_printer_uid`,``),v(this,`total`,0),v(this,`time`,0),v(this,`pax`,0),v(this,`invoice_created_at`,new Date),v(this,`child_pax`,0),v(this,`baby_pax`,0),v(this,`uid`,E.SectionItem+t()),v(this,`invoice_uid`,``),v(this,`section_uid`,``),v(this,`status`,M.CLOSED),v(this,`size_x`,0),v(this,`size_y`,0),v(this,`row`,0),v(this,`col`,0),v(this,`is_take_out`,!1),v(this,`is_delivery`,!1),v(this,`is_locked`,!1),v(this,`soup_base_quota`,0),v(this,`soup_base_type`,0),v(this,`is_delete`,!1),v(this,`meta`,{}),v(this,`customer`,{}),v(this,`etc`,{})}},pe=class extends T{constructor(){super(),v(this,`sequence`,0),v(this,`disable_auto_print_receipt`,!1),v(this,`uid`,E.Section+t())}},me=class extends T{constructor(){super(),v(this,`permissions`,[]),v(this,`is_default`,!1),v(this,`uid`,E.EmployeeRole+t())}},he=class{constructor(e){v(this,`item_uid`,``),v(this,`quantity`,0),v(this,`modifiers`,[]),this.item_uid=e,this.quantity=0,this.modifiers=[]}},ge=class extends ae{constructor(){super(),v(this,`meta`,{}),v(this,`etc`,{}),v(this,`assets`,{}),v(this,`config`,{online_order_display_large_image:!1}),v(this,`is_internal`,!1),v(this,`color`,``),v(this,`icon`,``),v(this,`sequence`,0)}},_e=class{constructor(){v(this,`system`,ve.POS),v(this,`visible`,!1),v(this,`sequence`,0)}};let ve=function(e){return e.POS=`pos`,e.QrCodeOrder=`qr_code_order`,e}({}),ye=function(e){return e.Product=`product`,e.Modifier=`modifier`,e}({});var be=class extends ge{constructor(){super(),v(this,`type`,ye.Modifier),v(this,`visibility`,[]),v(this,`uid`,E.ItemModifierCategory+t()),v(this,`max_order`,0),v(this,`min_order`,0),v(this,`is_delisted`,!1),v(this,`code`,void 0),v(this,`printing_sequence`,0),v(this,`allow_custom_modifier`,void 0)}},xe=class extends ge{constructor(){super(),v(this,`image_url`,``),v(this,`image_file_path`,``),v(this,`image_thumbnail_url`,``),v(this,`image_thumbnail_file_path`,``),v(this,`has_subcategory`,!1),v(this,`name_translations`,{}),v(this,`visibility`,void 0),v(this,`printing_sequence`,0),v(this,`type`,ye.Product),v(this,`is_delisted`,!1),v(this,`subcategories`,[]),v(this,`uid`,E.Category+t()),v(this,`max_order`,0),v(this,`min_order`,0),v(this,`code`,void 0),v(this,`non_searchable`,!1)}},Se=class extends ge{constructor(){super(),v(this,`category_uid`,``),v(this,`uid`,E.Subcategory+t())}};let N=function(e){return e.ByQuantity=`by_quantity`,e.ByWeight=`by_weight`,e.Service=`service`,e.Combo=`combo`,e.Modifier=`modifier`,e.Package=`package`,e}({});var Ce=class extends ge{constructor(){super(),v(this,`image_url`,``),v(this,`image_file_path`,``),v(this,`image_thumbnail_url`,``),v(this,`image_thumbnail_file_path`,``),v(this,`visibility`,[]),v(this,`sku`,``),v(this,`type`,N.Modifier),v(this,`barcode`,``),v(this,`plu`,void 0),v(this,`category_uid`,``),v(this,`price`,0),v(this,`original_price`,0),v(this,`prices`,[]),v(this,`stock`,1e3),v(this,`print_on_receipt`,!0),v(this,`price_adjustable`,!1),v(this,`is_sold_out`,!1),v(this,`recipe`,``),v(this,`is_remark_disabled`,!1),v(this,`auto_select_first_modifier`,!1),v(this,`is_auto_applied`,!1),v(this,`uid`,E.ItemModifier+t())}},we=class extends Ce{constructor(){super(),v(this,`codename`,``),v(this,`sku`,``),v(this,`recipe`,``),v(this,`barcode`,``),v(this,`type`,N.ByQuantity),v(this,`add_credit`,0),v(this,`add_point`,0),v(this,`category_uid`,``),v(this,`subcategory_uid`,``),v(this,`unit`,0),v(this,`stock`,0),v(this,`is_sold_out`,!1),v(this,`sold`,0),v(this,`print_on_receipt`,!0),v(this,`price`,0),v(this,`open_editor`,!0),v(this,`price_adjustable`,!1),v(this,`minus_point`,0),v(this,`cost`,0),v(this,`discountable`,!0),v(this,`printing_sequence`,0),v(this,`recommended`,!1),v(this,`likes`,0),v(this,`dislikes`,0),v(this,`is_tax_exempt`,!1),v(this,`is_service_charge_exempt`,!1),v(this,`is_point_reward_exempt`,!1),v(this,`is_credit_reward_exempt`,!1),v(this,`is_internal`,!1),v(this,`is_delisted`,!1),v(this,`uid`,E.Item+t()),v(this,`modifiers`,void 0),v(this,`modifier_categories`,void 0),v(this,`kitchen_printers_uids`,[]),v(this,`order_printers_uids`,[]),v(this,`label_printers_uids`,[]),v(this,`open_editor_panel`,!1),v(this,`open_price_editor`,!1),v(this,`combo_groups`,[]),v(this,`non_searchable`,!1)}},Te=class extends w{constructor(){super(),v(this,`lookup_keys`,[]),v(this,`product_uid`,``),v(this,`uid`,E.Price+t()),v(this,`amount`,0),v(this,`name`,``),v(this,`name_translations`,{})}},Ee=class{constructor(){v(this,`item_uid`,``),v(this,`combo_item`,void 0),v(this,`price`,0),v(this,`sequence`,0),v(this,`meta`,{})}},De=class{constructor(){v(this,`uid`,E.ComboGroup+t()),v(this,`name`,``),v(this,`name_translations`,{}),v(this,`min_order`,1),v(this,`max_order`,1),v(this,`combo_items`,[]),v(this,`sequence`,0),v(this,`meta`,{})}},Oe=class e{constructor(){v(this,`_state`,e.State.CLOSED),v(this,`cleanup`,void 0),v(this,`onData`,null),v(this,`onClose`,null),v(this,`onError`,null)}get state(){return this._state}static setWindow(t){e.electronSocket=t.electronSocket}setupListeners(){this.cleanup?.(),this.cleanup=window.electronSocket.onEvent(t=>{switch(t.type){case`DataReceived`:this.onData?.(new Uint8Array(t.data));break;case`Close`:this._state=e.State.CLOSED,this.onClose?.(t.hasError),this.cleanup?.();break;case`Error`:this.onError?.(t.errorMessage);break}})}async open(t,n,r,i){try{if(this._state!==e.State.CLOSED){i?.(`Invalid state: ${this._state}`);return}this._state=e.State.OPENING,this.setupListeners(),await e.electronSocket.open(t,n)?(this._state=e.State.OPENED,r?.()):i?.(`Open failed`)}catch(t){this._state=e.State.CLOSED,this.cleanup?.(),i?.(`Open failed: ${t}`)}}async write(t,n,r){try{this._state!==e.State.OPENED&&r?.(`Socket not opened`),await e.electronSocket.write(Array.from(t))?n?.():r?.(`Write failed`)}catch(e){r?.(`Write failed: ${e}`)}}async close(t,n){if(this._state!==e.State.OPENED){n?.(`Invalid state: ${this._state}`);return}try{this._state=e.State.CLOSING,await e.electronSocket.close()?(this._state=e.State.CLOSED,this.cleanup?.(),t?.()):n?.(`Close socket failed`)}catch(t){this._state=e.State.CLOSED,this.cleanup?.(),n?.(`Close socket failed: ${t}`)}}};v(Oe,`State`,{CLOSED:0,OPENING:1,OPENED:2,CLOSING:3}),v(Oe,`electronSocket`,null);function ke(e){return e===`69`}const Ae={Ẳ:2,Ẵ:5,Ẫ:6,Ỷ:20,Ỹ:25,Ỵ:30,Ạ:128,Ắ:129,Ằ:130,Ặ:131,Ấ:132,Ầ:133,Ẩ:134,Ậ:135,Ẽ:136,Ẹ:137,Ế:138,Ề:139,Ể:140,Ễ:141,Ệ:142,Ố:143,Ồ:144,Ổ:145,Ỗ:146,Ộ:147,Ợ:148,Ớ:149,Ờ:150,Ở:151,Ị:152,Ỏ:153,Ọ:154,Ỉ:155,Ủ:156,Ũ:157,Ụ:158,Ỳ:159,Õ:160,ắ:161,ằ:162,ặ:163,ấ:164,ầ:165,ẩ:166,ậ:167,ẽ:168,ẹ:169,ế:170,ề:171,ể:172,ễ:173,ệ:174,ố:175,ồ:176,ổ:177,ỗ:178,Ỡ:179,Ơ:180,ộ:181,ờ:182,ở:183,ị:184,Ự:185,Ứ:186,Ừ:187,Ử:188,ơ:189,ớ:190,Ư:191,À:192,Á:193,Â:194,Ã:195,Ả:196,Ă:197,ẳ:198,ẵ:199,È:200,É:201,Ê:202,Ẻ:203,Ì:204,Í:205,Ĩ:206,ỳ:207,Đ:208,ứ:209,Ò:210,Ó:211,Ô:212,ạ:213,ỷ:214,ừ:215,ử:216,Ù:217,Ú:218,ỹ:219,ỵ:220,Ý:221,ỡ:222,ư:223,à:224,á:225,â:226,ã:227,ả:228,ă:229,ữ:230,ẫ:231,è:232,é:233,ê:234,ẻ:235,ì:236,í:237,ĩ:238,ỉ:239,đ:240,ự:241,ò:242,ó:243,ô:244,õ:245,ỏ:246,ọ:247,ụ:248,ù:249,ú:250,ũ:251,ủ:252,ý:253,ợ:254,Ữ:255};function je(e,t=63){let n=[];for(let r of e)if(Ae[r]!==void 0)n.push(Ae[r]);else{let e=r.charCodeAt(0);e<=127?n.push(e):n.push(t)}return Uint8Array.from(n)}function Me(){return typeof Socket>`u`?new Oe:new Socket}var Ne=class{constructor(){v(this,`socket`,void 0),this.socket=Me(),console.log(`this.socket`,JSON.stringify(this.socket)),this.socket.onData=function(e){console.log(`event - receive: `,e)},this.socket.onClose=function(e){console.log(`event - socket closed`)},this.socket.onError=function(e){console.error(`event - socket error:`,e)}}async testPrint(e){await this.connect(`192.168.1.253`);let t=await this.interpret(e);console.log(`escpos commands:`,JSON.stringify(t));let n=await this.write(t);return await this.disconnect(),n}async connect(e,t=9100,n=5e3){return new Promise((r,i)=>{let a,o,s=()=>{a&&window.clearTimeout(a),o&&window.clearInterval(o)};o=window.setInterval(()=>{this.socket.state===2&&(s(),r(!0))},100),a=window.setTimeout(()=>{s(),r(!1)},n),this.socket.open(e,t,()=>{},e=>{s(),r(!1)})}).catch(async e=>!1)}async write(e,t=1e4){return new Promise((n,r)=>{let i;this.socket.write(e,()=>{console.log(`write success`),clearTimeout(i),n(!0)}),i=window.setTimeout(()=>{console.error(`socket write timed out`),n(!1)},t)}).catch(e=>(console.error(`socket write exception: `,e),!1))}async interpret(e){let{default:t}=await import(`esc-pos-encoder-ionic`),n=new t,r=n.initialize();if(e.codepage&&!Object.values(P).includes(e.codepage)){let t=parseInt(e.codepage,10);r.raw([31,27,31,255,t,10,0])}else e.codepage&&Object.values(P).includes(e.codepage)?n.codepage(e.codepage):n.codepage(P.SimplifiedChinese);for(let t of e.items){if(!t)throw Error(`Item is undefined or null`);switch(t.style){case Fe.Bold:r.bold(!0);break;case Fe.Italic:r.italic(!0);break;case Fe.Underline:r.underline(!0);break;default:r.bold(!1),r.italic(!1),r.underline(!1);break}switch(t.align&&r.align(t.align),t.type){case F.Text:if(t.item?.text){if(t.item.size===Ie.Custom&&t.item.height&&t.item.width){if(t.item.width<0||t.item.width>7||t.item.height<0||t.item.height>7)throw Error(`font_width and font_height must be between 0 and 7`);let e=t.item.height<<4|t.item.width;r.raw([29,33,e])}else t.item.size&&r.size(t.item.size);if(ke(e.codepage)){let e=je(t.item.text);r.raw(Array.from(e))}else r.text(t.item.text,t.item.line_width??48);t.item.size===Ie.Custom&&r.raw([29,33,0])}break;case F.Table:if(t.table){if(t.table.size===Ie.Custom&&t.table.height&&t.table.width){if(t.table.width<0||t.table.width>7||t.table.height<0||t.table.height>7)throw Error(`font_width and font_height must be between 0 and 7`);let e=t.table.height<<4|t.table.width;r.raw([29,33,e])}else t.table.size&&r.size(t.table.size);this.formatTable(t.table.items,t.table.line_width??48).forEach(t=>{if(ke(e.codepage)){let e=je(t);r.raw(Array.from(e))}else r.text(t);r.newline()}),t.table.size===Ie.Custom&&r.raw([29,33,0])}break;case F.Line:r.line(t.item?.text?.repeat(48)??`-`.repeat(48),t.item?.line_width??48);break;case F.NewLine:t.repeat=t.repeat??1;for(let e=0;e<t.repeat;e++)r.newline();break;case F.Image:if(t.image){let e=await this.base64ToImageBitmap(t.image.base64_data);r.image(e,t.image.width,t.image.height,t.image.algorithm,t.image.threshold)}break;case F.QRCode:t.qrcode&&r.qrcode(t.qrcode.data,t.qrcode.model,t.qrcode.size,t.qrcode.errorlevel);break;case F.Barcode:t.barcode&&r.barcode(t.barcode.data,t.barcode.symbology,t.barcode.height);break;case F.Cut:r.cut(t.item?.text??`full`);break;case F.Beeper:r.beeper();break;case F.OpenCashDrawer:r.openCashDrawer();break;default:throw Error(`Unsupported item type: ${t.type}`)}}return r.encode()}formatTable(e,t=48){let n=e.map(e=>Math.floor(t*(e.column_width/100))),r=e.map((e,t)=>this.wrapText(e.text,n[t])),i=[],a=Math.max(...r.map(e=>e.length));for(let t=0;t<a;t++){let a=``;for(let i=0;i<e.length;i++){let e=r[i][t]||``;a+=this.padEnd(e,n[i])}i.push(a)}return i}padEnd(e,t){let r=Array.from(e).reduce((e,t)=>e+n(t),0);return e+` `.repeat(Math.max(0,t-r))}padStart(e,t){let r=Array.from(e).reduce((e,t)=>e+n(t),0);return` `.repeat(Math.max(0,t-r))+e}wrapText(e,t){if(typeof e!=`string`&&(e=e.toString()),!e)return[``];let r=[],i=``,a=0;for(let o of e){if(o===`
|
|
2
|
+
`){r.push(i),i=``,a=0;continue}let e=n(o);a+e>t&&(r.push(i),i=``,a=0),i+=o,a+=e}return i&&r.push(i),r}async disconnect(){if(!this.socket||this.socket.state!==2)return!0;try{return await this.close(),!0}catch(e){throw Error(e)}}close(e=5e3){return new Promise((t,n)=>{let r=this.socket.onClose,i;this.socket.onClose=e=>{clearTimeout(i),this.socket.onClose=r,e?n(Error(`Socket closed with error: ${e}`)):t(),typeof r==`function`&&r(e)},i=window.setTimeout(()=>{this.socket.onClose=r,n(Error(`Socket close operation timed out`))},e),this.socket.close(()=>console.log(`Close initiated successfully`),e=>{clearTimeout(i),this.socket.onClose=r,n(e)})})}async base64ToImageBitmap(e){let t=e.match(/^data:(image\/(?:jpeg|png));base64,(.+)$/i);if(!t)throw Error(`base64_data format is invalid or image type is not supported (only jpeg/png allowed)`);let[,n,r]=t,i=new Blob([Uint8Array.from(atob(r),e=>e.charCodeAt(0))],{type:n});return await createImageBitmap(i)}};let P=function(e){return e.English=`cp437`,e.Greek=`cp737`,e.WesternEurope=`cp850`,e.BalticRim=`cp775`,e.CentralEurope=`cp852`,e.Cyrillic=`cp855`,e.Turkish=`cp857`,e.MultilingualLatin1WithEuro=`cp858`,e.Portuguese=`cp860`,e.Icelandic=`cp861`,e.Hebrew=`cp862`,e.FrenchCanadian=`cp863`,e.Arabic=`cp864`,e.Nordic=`cp865`,e.Russian=`cp866`,e.ModernGreek=`cp869`,e.SimplifiedChinese=`cp936`,e.Korean=`cp949`,e.TraditionalChinese=`cp950`,e.WesternEuropeanLatin=`cp1252`,e.ArabicISO=`iso88596`,e.Japanese=`shiftjis`,e.CentralEuropeanLatinWindows=`windows1250`,e.CyrillicWindows=`windows1251`,e.WesternEuropeanLatinWindows=`windows1252`,e.GreekWindows=`windows1253`,e.TurkishWindows=`windows1254`,e.HebrewWindows=`windows1255`,e.ArabicWindows=`windows1256`,e.BalticWindows=`windows1257`,e.Vietnamese=`windows1258`,e}({}),Pe=function(e){return e.Left=`left`,e.Center=`center`,e.Right=`right`,e}({}),Fe=function(e){return e.Normal=`normal`,e.Bold=`bold`,e.Italic=`italic`,e.Underline=`underline`,e}({}),Ie=function(e){return e.Custom=`custom`,e.Normal=`normal`,e.Small=`small`,e}({}),F=function(e){return e.Text=`text`,e.Table=`table`,e.Line=`line`,e.Image=`image`,e.QRCode=`qrcode`,e.NewLine=`newline`,e.Barcode=`barcode`,e.Cut=`cut`,e.Beeper=`beeper`,e.OpenCashDrawer=`open_cash_drawer`,e}({});var Le=class{constructor(){v(this,`data`,``),v(this,`symbology`,`ean13`),v(this,`height`,0)}},Re=class{constructor(){v(this,`data`,``),v(this,`model`,2),v(this,`size`,6),v(this,`errorlevel`,`m`)}},ze=class{constructor(){v(this,`base64_data`,``),v(this,`width`,0),v(this,`height`,0),v(this,`algorithm`,`threshold`),v(this,`threshold`,128)}};let Be=function(e){return e[e.SunmiPrinter=0]=`SunmiPrinter`,e}({});var I=class{constructor(){v(this,`codepage`,P.WesternEuropeanLatin),v(this,`items`,[])}};function L(t,n){return e(t).format(n||`YYYY-MMM-DD HH:mm:ss`)}function Ve(e){return`${e.getFullYear()}-${(e.getMonth()+1).toString().padStart(2,`0`)}-${e.getDate().toString().padStart(2,`0`)} ${e.getHours().toString().padStart(2,`0`)}:${e.getMinutes().toString().padStart(2,`0`)}:${e.getSeconds().toString().padStart(2,`0`)}`}var He=class extends T{constructor(){super(),v(this,`machine_name`,``),v(this,`connection_id`,``),v(this,`type`,We.Client),v(this,`etc`,{fomopay_terminal_id:``,hirector_public_key:``,hirector_private_key:``,yeahpay_app_id:``,yeahpay_device_sn:``,yeahpay_server_public_key:``,yeahpay_client_private_key:``,yeahpay_signature_key:``,yeahpay_async_url:``,sync_to_specific_cds:``})}},Ue=class extends T{constructor(){super(),v(this,`type`,We.Node),v(this,`machine_name`,``),v(this,`connection_id`,``),v(this,`etc`,{fomopay_terminal_id:``,hirector_public_key:``,hirector_private_key:``,yeahpay_app_id:``,yeahpay_device_sn:``,yeahpay_server_public_key:``,yeahpay_client_private_key:``,yeahpay_signature_key:``,yeahpay_async_url:``,sync_to_specific_cds:``})}};let We=function(e){return e.Client=`client`,e.Node=`node`,e}({}),R=function(e){return e.ReceiptPrinter=`receipt_printer`,e.CheckPrinter=`check_printer`,e.OrderPrinter=`order_printer`,e.KitchenPrinter=`kitchen_printer`,e.KioskPrinter=`kiosk_printer`,e.LabelPrinter=`label_printer`,e.QrCodePrinter=`qr_code_printer`,e.KitchenDisplayPrinter=`kitchen_display_printer`,e}({});var Ge=class{constructor(){v(this,`printer_name`,``),v(this,`status`,``),v(this,`port_name`,``),v(this,`error`,``)}};let Ke=function(e){return e.ESCPOS=`ESC/POS`,e.TSPL=`TSPL`,e}({}),qe=function(e){return e.USB=`USB`,e.WINDOWS_DRIVER=`WINDOWS_DRIVER`,e.ETHERNET=`ETHERNET`,e.BLUETOOTH=`BLUETOOTH`,e.BUILTIN=`BUILTIN`,e.IMIN_BUILT_IN=`IMIN_BUILT_IN`,e}({});var Je=class{constructor(){v(this,`header`,``),v(this,`body`,``),v(this,`footer`,``),v(this,`commands`,``),v(this,`type`,R.ReceiptPrinter)}},z=class extends T{constructor(){super(),v(this,`header`,``),v(this,`body`,``),v(this,`footer`,``),v(this,`commands`,``),v(this,`printer_type`,R.ReceiptPrinter),v(this,`codepage`,void 0),v(this,`uid`,E.PrintTemplate+t()),v(this,`report_code_name`,``)}};let Ye=function(e){return e.Queued=`queued`,e.Printed=`printed`,e.Failed=`failed`,e.Expired=`expired`,e}({});var B=class extends T{constructor(e,n,r=!1,i=1){super(),v(this,`printer_name`,``),v(this,`driver_printer_name`,``),v(this,`printer_ip`,``),v(this,`printer_uid`,``),v(this,`printer_type`,R.ReceiptPrinter),v(this,`protocol`,Ke.ESCPOS),v(this,`connection_type`,qe.ETHERNET),v(this,`data`,new I),v(this,`status`,Ye.Queued),v(this,`retries`,0),v(this,`commands`,``),v(this,`uid`,E.PrintJob+t()),v(this,`save_only`,!1),v(this,`print_times`,1),v(this,`printed`,0),v(this,`device_uid_to_print`,``),v(this,`designated_table_section_uids`,[]),v(this,`job_id`,0),v(this,`print_sequence`,void 0),v(this,`meta`,{}),this.driver_printer_name=e.driver_printer_name,e.protocol&&(this.protocol=e.protocol),e.connection_type&&(this.connection_type=e.connection_type),this.printer_name=e.name,this.printer_ip=e.ip_address,e.type&&(this.printer_type=e.type),this.data=n,this.printer_uid=e.uid,this.save_only=r,this.print_times=i,e.print_sequence!==void 0&&(this.print_sequence=e.print_sequence)}};let Xe=function(e){return e.Online=`online`,e.Offline=`offline`,e}({});var Ze=class extends T{constructor(){super(),v(this,`device_uid`,``),v(this,`terminal_device_uids`,[]),v(this,`type`,R.ReceiptPrinter),v(this,`is_not_default`,!1),v(this,`driver_printer_name`,``),v(this,`fallback_printer_uid`,0),v(this,`protocol`,Ke.ESCPOS),v(this,`connection_type`,qe.ETHERNET),v(this,`print_template_uid`,``),v(this,`uid`,E.Printer+t()),v(this,`ip_address`,``),v(this,`status`,Xe.Online),v(this,`kitchen_itemized_print`,!1),v(this,`print_times`,1),v(this,`retries`,1),v(this,`use_device_name`,!1),v(this,`usb_device_name`,``)}},Qe=class{constructor(){v(this,`config`,{}),v(this,`invoice`,{}),v(this,`report_data`,{}),v(this,`section_item`,{}),v(this,`printer_name`,``),v(this,`printed_at`,new Date),v(this,`normalized_printed_at`,``),v(this,`meta`,{}),v(this,`is_cancel`,!1),this.normalized_printed_at=L(this.printed_at)}},V=class{constructor(){v(this,`printer_name`,``),v(this,`kitchen_itemized_print`,!1),v(this,`is_cancel`,!1)}},$e=class extends w{constructor(){super(),v(this,`invoice_uid`,``),v(this,`tender_amount`,0),v(this,`change_amount`,0),v(this,`payment_method_uid`,``),v(this,`payment_method_code`,``),v(this,`payment_method_name`,``),v(this,`payment_method`,new et),v(this,`payment_method_history`,void 0),v(this,`uid`,E.Payment+t()),v(this,`updated_at`,new Date)}},et=class extends T{constructor(){super(),v(this,`sequence`,0),v(this,`payment_currency_id`,0),v(this,`currency_code`,``),v(this,`currency_symbol`,`$`),v(this,`payment_method_code`,``),v(this,`name`,``),v(this,`codename`,``),v(this,`name_abbrev`,``),v(this,`enable_drawer`,!1),v(this,`enable_receipt`,!1),v(this,`image_url`,``),v(this,`custom_image_url`,``),v(this,`is_cash`,!1),v(this,`is_integrated`,!1),v(this,`is_disabled`,!0),v(this,`type`,0),v(this,`api_id`,``),v(this,`api_key`,``),v(this,`is_sales_exclusive`,!1),v(this,`enable_credit_validation`,!1),v(this,`enable_customer_validation`,!1),v(this,`is_cancellable`,!1),v(this,`require_zero_balance`,!1),v(this,`allow_custom_amount`,!1),v(this,`uid`,E.PaymentMethod+t())}},tt=class extends et{constructor(){super(),v(this,`changed_at`,new Date),v(this,`changed_by`,``)}},nt=class{toPaymentMethod(){let e=new et;return e.currency_code=this.currency_code||``,e.payment_method_code=this.payment_method_code||``,e.codename=this.codename||``,e.name=this.name||``,e.name_abbrev=this.name_abbrev||``,e.enable_drawer=this.enable_drawer,e.enable_receipt=this.enable_receipt,e.image_url=this.image_url||``,e.is_cash=this.is_cash,e.is_integrated=this.is_integrated,e.is_disabled=this.is_disabled,e.type=this.type,e.api_id=this.api_id||``,e.api_key=this.api_key||``,e}constructor(e){v(this,`access_token`,null),v(this,`image_base64`,null),v(this,`error`,null),v(this,`currency_code`,null),v(this,`payment_method_code`,``),v(this,`codename`,null),v(this,`name_abbrev`,null),v(this,`name`,``),v(this,`enable_drawer`,!1),v(this,`enable_receipt`,!0),v(this,`image_url`,``),v(this,`is_cash`,!1),v(this,`is_integrated`,!1),v(this,`is_disabled`,!1),v(this,`type`,0),v(this,`api_id`,null),v(this,`api_key`,null),v(this,`timestamp_create`,Date.now()),v(this,`timestamp_update`,Date.now()),e&&Object.assign(this,e)}};let rt=function(e){return e.STARTED=`payment_started`,e.COMPLETED=`payment_completed`,e.FAILED=`payment_failed`,e.CANCELLED=`payment_cancelled`,e}({});var it=class extends T{constructor(){super()}},at=class extends it{constructor(){super()}},ot=class extends T{constructor(){super(),v(this,`note_group_uid`,``),v(this,`related_model`,oe.Invoice),v(this,`usage`,0)}},st=class extends ot{constructor(){super()}};let H=function(e){return e.DineIn=`dine_in`,e.TakeOut=`take_out`,e.Delivery=`delivery`,e}({}),ct=function(e){return e.PayToOrder=`pay_to_order`,e.OrderFirstAndPayLater=`order_first_and_pay_later`,e.OnSelection=`on_selection`,e}({}),lt=function(e){return e.Inclusive=`inclusive`,e.Exclusive=`exclusive`,e}({}),U=function(e){return e.Open=`open`,e.OnHold=`on_hold`,e.Paying=`paying`,e.Paid=`paid`,e.Void=`void`,e.PayAtCounter=`pay_at_counter`,e}({}),ut=function(e){return e.Calibration=`calibration`,e.Create=`create`,e.Update=`update`,e.Cancel=`cancel`,e.Hold=`hold`,e.PaymentAsync=`payment_async`,e.Check=`check`,e.Void=`void`,e.Switch=`switch`,e.Reprint=`reprint`,e.Display=`display`,e.Merge=`merge`,e.Calculate=`calculate`,e.Delivery=`delivery`,e.Payment=`payment`,e.ChangePayment=`change_payment`,e.AddCustomer=`add_customer`,e.VoidAndDuplicate=`void_and_duplicate`,e.Duplicate=`duplicate`,e.PayAtCounter=`pay_at_counter`,e.PayInvoice=`pay_invoice`,e.SettleOnlineDeliveryOrder=`settle_online_delivery_order`,e}({}),dt=function(e){return e.quantity=`quantity`,e.weight=`weight`,e}({}),W=function(e){return e.Flat=`flat`,e.Percent=`percent`,e}({}),G=function(e){return e.AfterSubtotal=`after_subtotal`,e.AfterServiceCharge=`after_service_charge`,e.AfterGrantTotal=`after_grant_total`,e}({}),ft=function(e){return e.Custom=`custom`,e.Voucher=`voucher`,e.Coupon=`coupon`,e}({});var pt=class{constructor(){v(this,`uid`,E.InvoiceCharge+t()),v(this,`name`,``),v(this,`percentage`,0),v(this,`amount`,0),v(this,`calc_flow`,G.AfterSubtotal)}},mt=class{constructor(){v(this,`action`,ut.Create),v(this,`action_by`,``),v(this,`device_uid`,``),v(this,`action_at`,new Date)}},ht=class{constructor(){v(this,`uid`,E.Charge+t()),v(this,`name`,``),v(this,`percent`,0),v(this,`calc_flow`,G.AfterSubtotal),v(this,`trigger_condition`,``)}},gt=class{constructor(){v(this,`calc_type`,W.Flat),v(this,`amount`,0),v(this,`percent`,0),v(this,`percent_amount`,0),v(this,`type`,ft.Custom),v(this,`calc_flow`,G.AfterSubtotal),v(this,`applying_item_uids`,[]),v(this,`name`,``),v(this,`name_translation`,{}),v(this,`voucher_uid`,``),v(this,`coupon_uid`,``),v(this,`uid`,E.InvoiceDiscount+t())}},_t=class{constructor(){v(this,`item_uid`,``),v(this,`item`,new Ce),v(this,`price`,0),v(this,`unit_of_measure`,dt.quantity),v(this,`quantity`,0),v(this,`sent`,0),v(this,`kds_done`,0),v(this,`kds_prepared`,0),v(this,`kds_batch`,0),v(this,`is_cancel_printed`,!1),v(this,`is_cancel_slip_printed`,!1),v(this,`selected`,!1),v(this,`sales_user_uid`,``),v(this,`salespersons`,void 0),v(this,`is_auto_applied`,!1)}},vt=class extends w{constructor(){super(),v(this,`item_uid`,``),v(this,`price`,0),v(this,`unit_of_measure`,dt.quantity),v(this,`quantity`,0),v(this,`remark`,``),v(this,`invoice_uid`,``),v(this,`discount_calc_type`,W.Flat),v(this,`discount_amount`,0),v(this,`discount_percent`,0),v(this,`subtotal`,0),v(this,`subtotal_before_discount`,0),v(this,`item`,new we),v(this,`point`,0),v(this,`point_subtotal`,0),v(this,`up_size`,!1),v(this,`is_take_out`,!1),v(this,`is_duplicate`,!1),v(this,`is_combo`,!1),v(this,`is_combo_item`,!1),v(this,`combo_group_uid`,``),v(this,`combo_line_uid`,``),v(this,`modifiers`,[]),v(this,`duplicated_from_uid`,``),v(this,`sent`,0),v(this,`kds_done`,0),v(this,`kds_prepared`,0),v(this,`kds_batch`,0),v(this,`is_cancel_printed`,!1),v(this,`is_cancel_slip_printed`,!1),v(this,`selected`,!1),v(this,`sales_user_uid`,``),v(this,`salespersons`,void 0),v(this,`meta`,{}),v(this,`attached_to_line_uid`,void 0)}},yt=class extends w{constructor(){super(),v(this,`ref_id`,``),v(this,`call_num`,``),v(this,`table_uid`,``),v(this,`table_name`,``),v(this,`type`,H.DineIn),v(this,`pax`,0),v(this,`adult_pax`,0),v(this,`child_pax`,0),v(this,`baby_pax`,0),v(this,`subtotal`,0),v(this,`point_subtotal`,0),v(this,`service_chargeable_subtotal`,0),v(this,`discountable_subtotal`,0),v(this,`service_charge`,0),v(this,`delivery_id`,0),v(this,`delivery_charge`,0),v(this,`delivery_type`,``),v(this,`delivery_by`,``),v(this,`use_customer_point`,!1),v(this,`add_point`,0),v(this,`minus_point`,0),v(this,`rewarded_point_rate`,0),v(this,`rewarded_point`,0),v(this,`use_customer_balance`,!1),v(this,`add_credit`,0),v(this,`minus_credit`,0),v(this,`rewarded_credit_rate`,0),v(this,`rewarded_credit`,0),v(this,`discounts`,[]),v(this,`discount_amount`,0),v(this,`tax`,0),v(this,`rounding`,0),v(this,`tip`,0),v(this,`grand_total`,0),v(this,`customer_id`,0),v(this,`remark`,``),v(this,`sales_user_uid`,``),v(this,`salespersons`,void 0),v(this,`status`,U.Open),v(this,`paid_at`,new Date(0)),v(this,`voided_at`,new Date(0)),v(this,`humanized_paid_at`,``),v(this,`humanized_voided_at`,``),v(this,`humanized_created_at`,``),v(this,`order_id`,0),v(this,`to_address`,new y),v(this,`payment_source_method`,``),v(this,`payment_source_last4`,``),v(this,`payment_source_charge_ref`,``),v(this,`is_sales_exclusive`,!1),v(this,`etc`,{}),v(this,`action`,void 0),v(this,`lines`,[]),v(this,`deleted_lines`,[]),v(this,`payment_has_cash`,!1),v(this,`payments`,[]),v(this,`table_switch_id`,0),v(this,`employee_uid`,``),v(this,`employee_name`,``),v(this,`receipt_print_override`,!1),v(this,`customer`,new x),v(this,`is_duplicate`,!1),v(this,`kitchen_print_override`,!1),v(this,`otp`,``),v(this,`activities`,[]),v(this,`receipt_print_job_uid`,``),v(this,`kitchen_print_job_uids`,[]),v(this,`label_print_job_uids`,[]),v(this,`order_print_job_uids`,[]),v(this,`charges`,[]),v(this,`is_charge_triggered`,!1),v(this,`uid`,E.Invoice+t()),v(this,`meta`,{}),v(this,`price_lookup_key`,``)}},bt=class extends w{constructor(){super(),v(this,`user_uid`,void 0),v(this,`name`,void 0),v(this,`email`,void 0),v(this,`password`,void 0),v(this,`uid`,E.Employee+t()),v(this,`role_uid`,``),v(this,`language`,`en`),v(this,`can_login`,!0)}},xt=class extends w{constructor(){super(),v(this,`config`,new Mt),v(this,`cache`,new St),v(this,`storage`,{pricing_lookup_keys:[],pay_in_reasons:[],pay_out_reasons:[]})}},St=class{constructor(){v(this,`printers`,[])}},Ct=class{constructor(){}},wt=class{constructor(){v(this,`enable_appointment_module`,!1)}},Tt=class{constructor(){v(this,`enable_price_tiers`,!1),v(this,`rewarded_credit_rate`,0),v(this,`rewarded_point_rate`,0),v(this,`inclusive_service_charge`,!1),v(this,`inclusive_tax`,!1),v(this,`default_country_code`,`+65`),v(this,`disable_member_price_prompt`,!1),v(this,`disable_member_price_on_credit_payment`,!1)}},Et=class{constructor(){v(this,`enabled`,!1),v(this,`full_screen_assets`,[]),v(this,`half_screen_assets`,[]),v(this,`is_logo_hidden`,!1),v(this,`order_list_font_size`,`1.875rem`),v(this,`order_modifier_font_size`,`1.25rem`),v(this,`screen_width`,1024),v(this,`screen_height`,768),v(this,`order_display_duration`,60),v(this,`language`,`en`)}};let Dt=function(e){return e.SmoochPay=`SPCD`,e.YeahPay=`YEAP`,e.Shouqianba=`CRES`,e}({}),Ot=function(e){return e.YeahPayWechat=`YPWP`,e.YeahPayWechatOnline=`YPWO`,e.Shouqianba=`WCPH`,e}({}),kt=function(e){return e.YeahPayAlipay=`YPAP`,e.YeahPayAlipayOnline=`YPAO`,e.Shouqianba=`ALPH`,e}({});var At=class{constructor(){v(this,`takeaway_only`,!1),v(this,`guest_order_only`,!1),v(this,`disable_paynow_payment`,!1),v(this,`disable_card_payment`,!1),v(this,`disable_wechat_payment`,!1),v(this,`disable_alipay_payment`,!1),v(this,`disable_receipt_printer_receipt`,!1),v(this,`enable_grabfood_dinein`,!1),v(this,`landing_image`,``),v(this,`menu_banner_image`,``),v(this,`home_page_images`,[]),v(this,`paynow_method`,Nt.WyoPaynow),v(this,`card_payment_code`,Dt.SmoochPay),v(this,`wechat_method`,Ot.YeahPayWechat),v(this,`alipay_method`,kt.YeahPayAlipay)}},jt=class{constructor(){v(this,`point`,{sms_notification:!1,above_invoice_amount:0,conversion_rate:0,inclusive_service_charge:!1,inclusive_tax:!1}),v(this,`credit`,{sms_notification:!1,above_invoice_amount:0,conversion_rate:0,inclusive_service_charge:!1,inclusive_tax:!1})}},Mt=class{constructor(){v(this,`general`,new Rt),v(this,`product`,new Lt),v(this,`till`,new zt),v(this,`report`,new Bt),v(this,`receipt`,new Vt),v(this,`kitchen`,new Ht),v(this,`kds`,new Ut),v(this,`label`,new Wt),v(this,`order`,new Gt),v(this,`ods`,new Kt),v(this,`payment`,new qt),v(this,`user`,new Jt),v(this,`tax`,new Yt),v(this,`rounding`,new Qt),v(this,`inventory`,new $t),v(this,`pax_config`,new en),v(this,`gto`,new tn),v(this,`cash_drawer`,new nn),v(this,`marketing`,new jt),v(this,`charges`,new Xt),v(this,`currency`,new Zt),v(this,`cds`,new Et),v(this,`kiosk`,new At),v(this,`online_order`,new Pt),v(this,`loyalty_program`,new Tt),v(this,`crm`,new Ct),v(this,`system`,new wt)}};let Nt=function(e){return e.FomoOnlinePaynow=`PNWO`,e.WyoPaynow=`WPPN`,e.YeahPayPaynow=`YPPN`,e}({});var Pt=class{constructor(){v(this,`enable_membership`,!1),v(this,`login_call_to_action_text`,``),v(this,`menu_banner_image_url`,``),v(this,`menu_popup_image_url`,``),v(this,`paynow_method`,void 0),v(this,`disable_pay_at_counter`,!1),v(this,`disable_verify_at_counter`,!1),v(this,`disable_paynow_payment`,!1),v(this,`default_language`,`en`),v(this,`category_selector_mode`,`photo_mode`),v(this,`dynamic_order_qr`,{default_order_flow:ct.OrderFirstAndPayLater,select_order_flow:!1,select_menus:!1,expiry_in_minutes:0}),v(this,`max_dining_time`,0),v(this,`disable_logo_for_item_photo_fallback`,!1),v(this,`whatsapp_login_only`,!1),v(this,`enable_whatsapp_login`,!1),v(this,`assets`,{}),v(this,`disable_order_remark`,!1),v(this,`disable_order_now_when_closed`,!1)}};let Ft=function(e){return e.PROD=`prod`,e.DEV=`dev`,e}({});const It=e=>e===`compact`||e===`rectangle`?e:`square`;var Lt=class{constructor(){v(this,`enable_codename_search`,!1),v(this,`item_name_font_size`,14),v(this,`item_name_bg_opacity`,75),v(this,`category_button_shape`,`square`)}},Rt=class{constructor(){v(this,`company_name`,``),v(this,`company_name_alias`,``),v(this,`company_logo`,``),v(this,`company_tax_reg_no`,``),v(this,`company_postcode`,``),v(this,`company_address`,``),v(this,`company_country`,``),v(this,`company_tel`,``),v(this,`business_day_cutoff_hour`,0),v(this,`floor_plan_table_name`,`table`),v(this,`deploy_channel`,Ft.PROD),v(this,`language`,`en`),v(this,`debug`,!1),v(this,`logging`,!1),v(this,`offline_mode`,!1),v(this,`opening_schedules`,[{opening_hours:{open:`10:00`,close:`22:00`}}])}},zt=class{constructor(){v(this,`control`,!0),v(this,`slip`,!0),v(this,`auto_start_shift`,!1),v(this,`auto_shift_amount`,0)}},Bt=class{constructor(){v(this,`itemized_consolidated`,!0),v(this,`itemized_separated`,``),v(this,`shift_itemized`,!0),v(this,`start_time`,`09:00:01`),v(this,`end_time`,`23:59:59`),v(this,`shift_print_time`,1),v(this,`shift_disable`,!1),v(this,`email`,!1),v(this,`day_boundary_offset`,0)}},Vt=class{constructor(){v(this,`enabled`,!0),v(this,`show_print_dialog`,!1),v(this,`print_docket`,!1),v(this,`print_cancel_slip`,!1),v(this,`print_cancel_whole_invoice`,!1),v(this,`hide_non_price_item`,!1),v(this,`receipt_no_reset_daily`,!1),v(this,`language`,`en`),v(this,`disable_persistent_tcp`,!1)}},Ht=class{constructor(){v(this,`enabled`,!0),v(this,`print_item_price`,!1),v(this,`print_cancel_slip`,!1),v(this,`print_cancel_whole_invoice`,!1),v(this,`language`,`en`)}},Ut=class{constructor(){v(this,`enabled`,!0),v(this,`display_order_after_payment`,!1),v(this,`print_slip_upon_completed`,!1),v(this,`warn_mins`,30),v(this,`over_mins`,45),v(this,`color_normal`,`#409CD5`),v(this,`color_warning`,`#CB8336`),v(this,`color_overdue`,`#E53030`),v(this,`color_completed`,`#538235`),v(this,`enable_kds_status_on_pos`,!1)}},Wt=class{constructor(){v(this,`print`,!1),v(this,`text_to_raster`,!1)}},Gt=class{constructor(){v(this,`separation_line`,!1),v(this,`slip`,!0),v(this,`slip_font_size_ratio`,1),v(this,`max_dinning`,0),v(this,`exit_menu_after_payment`,!1),v(this,`hide_combo_item_on_receipt`,!1),v(this,`hide_combo_item_on_interactive_view`,!1),v(this,`hide_categories_when_ordering`,!1),v(this,`end_shift_with_open_tables`,!1),v(this,`datetime_format`,`YYYY-MMM-DD HH:mm:ss`),v(this,`ref_prefix`,`01`),v(this,`always_show_modifier`,!0),v(this,`enable_quick_check_button`,!1),v(this,`clear_order_note_on_add_item`,!1),v(this,`order_font_size`,14),v(this,`booking_slot_limit`,0),v(this,`booking_use_real_table`,!1),v(this,`booking_simple_mode`,!1)}},Kt=class{constructor(){v(this,`enabled`,!1),v(this,`language`,`en`)}},qt=class{constructor(){v(this,`quick_cash_payment`,!1),v(this,`notification`,!0),v(this,`quick`,!1),v(this,`payment_auto_redirect_seconds`,5)}},Jt=class{constructor(){v(this,`control`,!0)}},Yt=class{constructor(){v(this,`enabled`,!0),v(this,`method`,lt.Inclusive),v(this,`rate`,7),v(this,`name`,`GST`)}},Xt=class{constructor(){v(this,`service_charge`,!1),v(this,`service_charge_rate`,10)}},Zt=class{constructor(){v(this,`currency_symbol`,`$`),v(this,`is_symbol_after_amount`,!1)}},Qt=class{constructor(){v(this,`base`,.1),v(this,`up`,!0),v(this,`cashless`,!1),v(this,`prepayment_rounding`,!1)}},$t=class{constructor(){v(this,`inventory_control`,!1),v(this,`sold_out_for_today_only`,!1)}},en=class{constructor(){v(this,`pax`,!0),v(this,`detail`,!1)}},tn=class{constructor(){v(this,`interface`,``),v(this,`genesis_date`,``),v(this,`upload_time`,``),v(this,`ftp_svr`,``),v(this,`ftp_usr`,``),v(this,`ftp_port`,``),v(this,`ftp_path`,``),v(this,`ftp_pwd`,``),v(this,`mall_id`,``),v(this,`machine_id`,``),v(this,`ftp_type`,`ftp`)}},nn=class{constructor(){v(this,`kick_code`,`27, 112, 48, 55, 121`),v(this,`connection_mode`,`via_receipt_printer`)}},rn=class{constructor(e){v(this,`name`,``),v(this,`base64`,``),v(this,`extension`,`png`),Object.assign(this,e)}};const an=e=>e===``||e===void 0,on=e=>t=>an(e)||t.includes(e),sn=e=>t=>an(e)||e.includes(t),cn=(e,t)=>n=>n>e&&n<t,ln=e=>typeof e==`function`?(t,n)=>!e(t,n):t=>t!=e,un=e=>e,dn=e=>t=>!t.deleted_at&&Object.keys(e).every(n=>{if(an(e[n])||t[n]===e[n])return!0;if(typeof e[n]==`function`)return e[n](t[n],t)});var fn=class{constructor(){v(this,`db`,void 0),v(this,`moduleName`,void 0)}get table(){return this.db.table(this.moduleName)}liveQuery(e){return i(e)}async saveOne(e){let n={...e};return n.created_at||(n.created_at=new Date),n.uid||(n.uid=t()),n.updated_at=new Date,await this.db.table(this.moduleName).put(n),n}async saveMany(e){let n=e.map(e=>(e.uid||(e.uid=t(),e.created_at=new Date),e.updated_at=new Date,e));return await this.db.table(this.moduleName).bulkPut(n),n}async hasAny(){return await this.db.table(this.moduleName).count()>0}async getOne(e){return await this.db.table(this.moduleName).get(e)||null}async getOneByParams(e){return this.db.table(this.moduleName).filter(dn(e)).first()}async getDefaultOne(){return this.moduleName?this.db.table(this.moduleName).filter(e=>e.deleted_at===null||e.deleted_at===void 0).first():null}async getAll(){return this.db.table(this.moduleName).toArray()}async getMany(e={},t={}){let{page:n=1,pageSize:r=10,...i}=t||{},a=await this.db.table(this.moduleName).filter(dn(e)).count(),o=this.db.table(this.moduleName).filter(dn(e));return r!==-1&&o.offset((n-1)*r).limit(r),{list:await o.toArray(),count:a,page:n,pageSize:r}}},pn=class extends fn{async updateOne(e,t){throw Error(`Method not implemented.`)}async deleteOne(e){throw Error(`Method not implemented.`)}},K=class extends fn{constructor(...e){super(...e),v(this,`http`,void 0),v(this,`methodName`,void 0),v(this,`options`,void 0)}async addOne(e){return this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${this.methodName}`,e)}async updateOne(e,t){return this.http.patch(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${e}`,t)}async updateMany(e){return this.http.patch(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}`,e)}async deleteOne(e){return e.deleted_at=new Date,this.http.delete(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${e.id_in_server}`)}async hardDeleteOne(e){return await this.db.table(this.moduleName).delete(e.uid),e}};let mn=function(e){return e[e.printable=0]=`printable`,e[e.generative=1]=`generative`,e}({});var hn=class{constructor(){v(this,`uid`,E.ReportCategory+ +t()),v(this,`name`,``),v(this,`name_translations`,{}),v(this,`reports`,[]),v(this,`created_at`,new Date),v(this,`created_at_timestamp`,new Date().getTime()),v(this,`updated_at`,new Date),v(this,`deleted_at`,null)}},gn=class{constructor(){v(this,`uid`,E.Report+t()),v(this,`name`,``),v(this,`name_translations`,{}),v(this,`type`,void 0),v(this,`codename`,``),v(this,`created_at`,new Date),v(this,`created_at_timestamp`,new Date().getTime()),v(this,`updated_at`,new Date),v(this,`deleted_at`,null)}},_n=class extends w{constructor(){super(),v(this,`uid`,E.AppReport+t()),v(this,`reports`,[]),v(this,`version`,1)}},vn=class{constructor(){v(this,`start_datetime`,``),v(this,`humanized_start_datetime`,``),v(this,`end_datetime`,``),v(this,`humanized_end_datetime`,``),v(this,`humanized_printed_datetime`,``),v(this,`sales_summary`,new yn),v(this,`drawer_summary`,new bn),v(this,`payments_summary`,[]),v(this,`loyalty_program_summary`,new Sn),v(this,`item_sales_summary`,[]),v(this,`item_sales_summary_total`,0),v(this,`item_sales_summary_total_count`,0),v(this,`item_sales_summary_by_category`,[]),v(this,`modifier_sales_summary`,[]),v(this,`modifier_sales_summary_total`,0),v(this,`modifier_sales_summary_total_count`,0),v(this,`config`,{}),v(this,`invoice_discount_summary`,[]),v(this,`item_discount_summary`,[]),v(this,`order_type_summary`,[])}},yn=class{constructor(){v(this,`sales_total`,0),v(this,`foc_sales_total`,0),v(this,`foc_sales_count`,0),v(this,`foc_rounding_total`,0),v(this,`foc_tax_total`,0),v(this,`foc_service_charge_total`,0),v(this,`rounding_total`,0),v(this,`tax_total`,0),v(this,`service_charge_total`,0),v(this,`discount_total`,0),v(this,`voucher_total`,0),v(this,`voucher_count`,0),v(this,`coupon_total`,0),v(this,`coupon_count`,0),v(this,`paid_invoice_count`,0),v(this,`paid_invoice_total`,0),v(this,`void_invoice_count`,0),v(this,`void_invoice_total`,0),v(this,`total_pax`,0),v(this,`pax_sales_total`,0)}},bn=class{constructor(){v(this,`open_amount`,0),v(this,`declared_amount`,0),v(this,`drawer_amount`,0),v(this,`difference`,0),v(this,`pay_in_total`,0),v(this,`pay_in_count`,0),v(this,`cash_invoice_total`,0),v(this,`cash_invoice_count`,0),v(this,`pay_out_total`,0),v(this,`pay_out_count`,0)}},xn=class{constructor(){v(this,`code`,``),v(this,`name`,``),v(this,`total`,0),v(this,`count`,0)}},Sn=class{constructor(){v(this,`add_credit_total`,0),v(this,`add_credit_count`,0),v(this,`topup_paid_total`,0),v(this,`topup_paid_count`,0),v(this,`rewarded_credit_total`,0),v(this,`rewarded_credit_count`,0),v(this,`minus_credit_total`,0),v(this,`minus_credit_count`,0),v(this,`rewarded_point_total`,0),v(this,`rewarded_point_count`,0),v(this,`minus_point_total`,0),v(this,`minus_point_count`,0)}},Cn=class{constructor(){v(this,`item`,{}),v(this,`quantity`,0),v(this,`total_amount`,0),v(this,`modifiers`,[])}},wn=class{constructor(){v(this,`item`,{}),v(this,`quantity`,0),v(this,`total_amount`,0)}},Tn=class{constructor(){v(this,`category`,null),v(this,`items`,[]),v(this,`total_quantity`,0),v(this,`total_amount`,0)}},En=class extends K{constructor(e,t,n,r=`printers`,i=`printer`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i,v(this,`configService`,void 0),v(this,`printJobService`,void 0),v(this,`printersFromCache`,void 0),this.configService=new Br(e,t,n,`configs`,`config`),this.printJobService=new Xr(e,t,n,`print_jobs`,`print_job`),this.init().catch(e=>console.error(e))}async init(){this.printersFromCache||(this.printersFromCache=(await this.configService.getDefaultOne())?.cache?.printers??[])}async getPhysicalPrintersFromNode(){return(await this.http.get(`api/v5/merchants/`+this.options.merchant_uid+`/`+this.moduleName+`/get_physical_printers`)).data}async getUnpairedNode(){return this.http.get(`api/v5/merchants/`+this.options.merchant_uid+`/node`)}async pairNode(e){return this.http.get(`api/v5/merchants/`+this.options.merchant_uid+`/nodes/${e}/pair-node`)}async getDefaultPrinter(e){let t=await this.db.table(`printers`).filter(t=>t.type===e&&t.deleted_at==null).toArray();return t.find(e=>!e.is_not_default)||t[0]||null}async getDefaultReceiptPrinter(){return this.getDefaultPrinter(R.ReceiptPrinter)}async getDefaultPrinterByType(e){return this.getDefaultPrinter(e)}async getDefaultKioskPrinter(){return this.getDefaultPrinter(R.KioskPrinter)}async getDefaultCheckPrinter(){return this.getDefaultPrinter(R.CheckPrinter)}async getDefaultKitchenPrinter(){return this.getDefaultPrinter(R.KitchenPrinter)}async getDefaultOrderPrinter(){return this.getDefaultPrinter(R.OrderPrinter)}async getDefaultKitchenDisplayPrinter(){return this.getDefaultPrinter(R.KitchenDisplayPrinter)}async getPrintersByUids(e){return this.db.table(`printers`).where(`uid`).anyOf(e).filter(e=>e.deleted_at==null).toArray()}async searchPrinters(e=!1,t=9100){if(this.printersFromCache&&!e)return this.printersFromCache;let n=[],r=await u.getWiFiIPAddress();console.log(`ipAddress`,r);let i=r.subnet.split(`.`).map(Number),a=r.ip.split(`.`).map(Number);a[3]=0;let o=i.reduce((e,t,n)=>e+(t^255)*256**(3-n),0);for(let e=1;e<o;e++){let r=[...a],i=3,o=e;for(;o>0;){let e=o%256;for(o=Math.floor(o/256),r[i]+=e;r[i]>254&&i>0;)r[i]-=256,r[--i]++}let s=r.join(`.`);console.log(`ip`,s),await new Ne().connect(s,t,200)&&n.push(s)}return await this.configService.updateCache({printers:n}),n}async openCashDrawer(){let e=await this.getDefaultReceiptPrinter(),t=new I;t.items.push({type:F.OpenCashDrawer});let n=new B(e,t,!1,1);await this.printJobService.addOne(n)}};function q(e,t=2){let n=10**t;return Math.round(e*n)/n}function Dn(e){let t=e.name,n=t.lastIndexOf(`.`);return n===-1||n===t.length-1?``:t.slice(n+1)}function On(e){return new Promise((t,n)=>{let r=new FileReader;r.onloadend=()=>{typeof r.result==`string`?t(r.result.split(`,`)[1]):n(Error(`Could not convert file to Base64.`))},r.onerror=()=>n(Error(`File reading failed.`)),r.readAsDataURL(e)})}const J=(e,t)=>e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/[_\-\.]+/g,` `).toLowerCase().replace(/[\s]+(\w)/g,(e,n)=>t(n)),kn=e=>e.replace(/^\W+|\W+$/g,``),An=e=>typeof e==`string`?J(e,e=>e.toUpperCase()):``,jn=e=>typeof e==`string`?e.charAt(0).toUpperCase()+e.slice(1):``,Mn=e=>typeof e==`string`?e.replace(/\w\S*/g,e=>jn(e)):``,Nn=e=>typeof e==`string`?J(e,e=>`-`+e):``,Pn=e=>typeof e==`string`?J(e,e=>`.`+e):``,Fn=e=>In(e),In=e=>typeof e==`string`?e.toLowerCase():``,Ln=e=>{if(typeof e!=`string`)return``;let t=J(e,e=>e.toUpperCase());return t.charAt(0).toUpperCase()+t.slice(1)},Rn=e=>typeof e==`string`?J(e,e=>`/`+e):``,zn=e=>typeof e==`string`?e.replace(/((?:\S[^\.\?\!]*)[\.\?\!]*)/g,e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()):``,Bn=e=>typeof e==`string`?J(e,e=>`_`+e):``,Vn=e=>typeof e==`string`?e.replace(/[- _]+/g,` `).split(` `).map(e=>jn(e)).join(` `):``,Hn=e=>Un(e),Un=e=>typeof e==`string`?e.toUpperCase():``,Wn=(e,t)=>typeof e==`string`&&typeof t==`string`?e+t:e,Gn=(e,t)=>{if(typeof e!=`string`)return``;let n=``;for(let e=0;e<t;e++)n+=` `;return n+e+n},Kn=e=>typeof e==`string`?kn(e):``,qn=e=>typeof e==`string`?e.split(` `).join(`-`):``,Jn=(e,t=` `)=>typeof e==`string`?(typeof t!=`string`&&(t=` `),e.split(t).join(`+`)):``,Yn=(e,t)=>typeof e==`string`&&typeof t==`string`?t+e:e,Xn=(e,t)=>typeof e==`string`?typeof t==`string`?e.split(t).join(``):e:``,Zn=(e,t)=>typeof e==`string`?typeof t==`string`?e.replace(t,``):e:``,Qn=(e,t,n)=>typeof e==`string`?typeof t==`string`?(typeof n!=`string`&&(n=``),e.split(t).join(n)):e:``,$n=(e,t,n)=>typeof e==`string`?typeof t==`string`?(typeof n!=`string`&&(n=``),e.replace(t,n)):e:``,er=e=>typeof e==`string`?e.split(``).reverse().join(``):``,tr=(e,t=`,`)=>typeof e==`string`?(typeof t!=`string`&&(t=`,`),e.split(t)):[],nr=(e,t)=>typeof e==`string`?e.length<=t?e:or(e,t)+`…`:``,rr=e=>typeof e==`string`?e.trim():``,ir=e=>typeof e==`string`?e.replace(/^\s+/,``):``,ar=e=>typeof e==`string`?e.replace(/\s+$/,``):``,or=(e,t,n=``)=>typeof e==`string`?(typeof n!=`string`&&(n=``),e.length>t?e.slice(0,t-n.length)+n:e):``;var sr={camelcase:An,capitalize:jn,capitalizeAll:Mn,dashcase:Nn,dotcase:Pn,downcase:Fn,lowercase:In,pascalcase:Ln,pathcase:Rn,sentence:zn,snakecase:Bn,titleize:Vn,upcase:Hn,uppercase:Un,append:Wn,center:Gn,chop:Kn,hyphenate:qn,plusify:Jn,prepend:Yn,remove:Xn,removeFirst:Zn,replace:Qn,replaceFirst:$n,reverse:er,split:tr,ellipsis:nr,trim:rr,trimLeft:ir,trimRight:ar,truncate:or,truncateWords:(e,t,n=`…`)=>{if(typeof e==`string`&&typeof t==`number`){typeof n!=`string`&&(n=`…`);let r=e.split(/[ \t]/);return(t>r.length?r:r.slice(0,t)).join(` `).trim()+n}return``},isString:e=>typeof e==`string`,occurrences:(e,t)=>{if(typeof e!=`string`)return 0;let n=t.length,r=0,i=0;for(;(r=e.indexOf(t,r))>-1;)i++,r+=n;return i}};const cr=e=>e&&typeof e==`object`&&typeof e.fn==`function`,Y=(e,t,n)=>cr(n)?e?n.fn?n.fn(t):!0:n.inverse?n.inverse(t):!1:e,lr=function(...e){let t=e.pop();return Y(e.every(e=>!!e),this,t)},ur=function(...e){let t=e.pop();return Y(e.some(e=>!!e),this,t)},dr=function(e,t){return Y(!e,this,t)},fr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),Y(e===t,this,n)},pr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),Y(e==t,this,n)},mr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),Y(e!==t,this,n)},hr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),Y(e!=t,this,n)},gr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),Y(e>t,this,n)},_r=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),Y(e>=t,this,n)},vr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),Y(e<t,this,n)},yr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),Y(e<=t,this,n)},br=function(e,t,n,r){if(arguments.length<4)throw Error(`Helper {{compare}} expects 4 arguments`);let i;switch(t){case`==`:i=e==n;break;case`===`:i=e===n;break;case`!=`:i=e!=n;break;case`!==`:i=e!==n;break;case`<`:i=e<n;break;case`>`:i=e>n;break;case`<=`:i=e<=n;break;case`>=`:i=e>=n;break;case`typeof`:i=typeof e===n;break;default:throw Error(`Helper {{compare}}: invalid operator: \`${t}\``)}return Y(i,this,r)},xr=function(e,t,n){return typeof n==`number`&&(n=arguments[3]),Y(e==null?!1:Array.isArray(e)||typeof e==`string`?e.includes(t):typeof e==`object`?t in e:!1,this,n)},Sr=xr,Cr=function(e,...t){let n=t.pop();return Y(t.includes(e),this,n)},wr=(e,t)=>{if(!(!e||!t))return t.split(`.`).reduce((e,t)=>e?.[t],e)},Tr=e=>{let t=[];for(let n=0;n<e.length-1;n+=2)typeof e[n]==`string`&&!cr(e[n+1])&&t.push({prop:e[n],value:e[n+1]});return t};var Er={and:lr,or:ur,not:dr,eq:fr,is:pr,neq:mr,isnt:hr,gt:gr,gte:_r,lt:vr,lte:yr,compare:br,contains:xr,includes:Sr,in:Cr,findAnd:function(e,...t){if(!Array.isArray(e))return null;let n=Tr(t);return e.find(e=>n.every(t=>wr(e,t.prop)===t.value))||null},findOr:function(e,...t){if(!Array.isArray(e))return null;let n=Tr(t);return e.find(e=>n.some(t=>wr(e,t.prop)===t.value))||null},filterAnd:function(e,...t){if(!Array.isArray(e))return[];let n=Tr(t);return e.filter(e=>n.every(t=>wr(e,t.prop)===t.value))},filterOr:function(e,...t){if(!Array.isArray(e))return[];let n=Tr(t);return e.filter(e=>n.some(t=>wr(e,t.prop)===t.value))},default:function(...e){for(let t=0;t<e.length-1;t++)if(e[t]!=null)return e[t];return``},neither:function(e,t,n){return Y(!e&&!t,this,n)},ifEven:function(e,t){return Y(e%2==0,this,t)},ifOdd:function(e,t){return Y(e%2!=0,this,t)},ifNth:function(e,t,n){return Y(typeof e==`number`&&typeof t==`number`&&t%e===0,this,n)}};function Dr(e){let t=e?.handlebars||e?.hbs||m(`handlebars`);return Object.keys(sr).forEach(e=>{t.registerHelper(e,sr[e])}),Object.keys(Er).forEach(e=>{t.registerHelper(e,Er[e])}),t.helpers}var Or=Dr,kr=class extends w{constructor(){super(),v(this,`uid`,E.OrderDisplaySystem+t()),v(this,`order_number`,``),v(this,`status`,X.Preparing)}};let X=function(e){return e.Preparing=`preparing`,e.ReadyForPickup=`ready_for_pickup`,e}({});var Ar=class extends K{constructor(e,t,n,r=`order_displays`,i=`order_display`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async toPickUp(e){let t=await this.getOne(e);if(!t)throw new D(`Display order not found`);if(t.status==`ready_for_pickup`)throw new D(`Order is already ready for pickup`);if(t.status=X.ReadyForPickup,t.updated_at=new Date,t.id_in_server==0)throw new D(`Order is not synced with server`);return await this.updateOne(t.id_in_server,t),t}async toPreparing(e){let t=await this.getOne(e);if(!t)throw new D(`Display order not found`);if(t.status==`preparing`)throw new D(`Order is already preparing`);if(t.status=X.Preparing,t.updated_at=new Date,t.id_in_server==0)throw new D(`Order is not synced with server`);return await this.updateOne(t.id_in_server,t),t}async undo(){let e=await this.db.table(this.moduleName).filter(e=>e.status==X.ReadyForPickup).reverse().limit(100).toArray();if(e.length===0)throw new D(`No order to undo`);e.sort((e,t)=>{let n=new Date(e.updated_at).getTime();return new Date(t.updated_at).getTime()-n});let t=e[0];if(t.status=X.Preparing,t.updated_at=new Date,t.id_in_server==0)throw new D(`Order is not synced with server`);return await this.updateOne(t.id_in_server,t),t}};Or({handlebars:d});const jr={quantity:1,price:0,remark:``};var Mr=class extends K{constructor(e,t,n,r=`invoices`,i=`invoice`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i,v(this,`tillService`,void 0),v(this,`sectionItemService`,void 0),v(this,`sectionService`,void 0),v(this,`configService`,void 0),v(this,`printTemplateService`,void 0),v(this,`printerService`,void 0),v(this,`printJobService`,void 0),v(this,`itemService`,void 0),v(this,`orderDisplayService`,void 0),this.tillService=new Gr(e,t,n,`tills`,`till`),this.sectionItemService=new Hr(e,t,n,`section_items`,`section_item`),this.sectionService=new Vr(e,t,n,`sections`,`section`),this.configService=new Br(e,t,n,`configs`,`config`),this.printTemplateService=new Qr(e,t,n,`print_templates`,`print_template`),this.printerService=new En(e,t,n,`printers`,`printer`),this.printJobService=new Xr(e,t,n,`print_jobs`,`print_job`),this.itemService=new Rr(e,t,n,`items`,`item`),this.orderDisplayService=new Ar(e,t,n)}calculate(e,t,n=!1){if(e.lines==null||e.lines.length<1)return this.resetInvoiceCalculations(e),e;if(this.calculateLines(e),this.calculatePointSubtotal(e),this.calculateInvoiceServiceChargeableSubtotal(e),e.discount_amount=0,this.calculateDiscount(e,G.AfterSubtotal),e.grand_total<0&&(e.grand_total=0,e.service_chargeable_subtotal=0),this.calculateInvoiceCharges(e,G.AfterSubtotal),e.subtotal>0&&e.discount_amount>0){let t=1-e.discount_amount/e.subtotal;e.service_chargeable_subtotal=q(Math.max(0,e.service_chargeable_subtotal*t),2)}else e.discount_amount>=e.subtotal&&(e.service_chargeable_subtotal=0);let r=t.config.charges.service_charge?t.config.charges.service_charge_rate:0;this.calculateServiceCharge(e,r),this.calculateDiscount(e,G.AfterServiceCharge),e.grand_total<0&&(e.grand_total=0),this.calculateInvoiceCharges(e,G.AfterServiceCharge);let i=t.config.tax.enabled?t.config.tax.rate:0;return this.calculateTax(e,i,t.config.tax.method),this.calculateDeliveryCharge(e),this.calculateCreditDeduction(e),this.calculateTip(e),n?e.rounding=0:this.calculateRounding(e,t.config.rounding.base,t.config.rounding.up,t.config.rounding.cashless,t.config.rounding.nearest),this.calculateDiscount(e,G.AfterGrantTotal),e.grand_total<0&&(e.grand_total=0),this.calculateInvoiceCharges(e,G.AfterGrantTotal),e.grand_total=q(e.grand_total),e.rewarded_credit_rate=t.config?.loyalty_program?.rewarded_credit_rate??0,this.calculateRewardCredit(e,0,t.config?.loyalty_program?.inclusive_service_charge,t.config?.loyalty_program?.inclusive_tax),this.calculateAddCredit(e),this.calculateAddPoint(e),e.rewarded_point_rate=t.config?.loyalty_program?.rewarded_point_rate??0,this.calculateRewardPoint(e,t.config?.loyalty_program?.rewarded_point_rate,t.config?.loyalty_program?.inclusive_service_charge,t.config?.loyalty_program?.inclusive_tax),e.grand_total<0&&(e.grand_total=0),this.calculateChangeAmount(e),e}calculateLines(e){e.subtotal=0,e.point_subtotal=0;let t=0;for(let n of e.lines)this.calculateLine(n),t+=n.subtotal,e.subtotal+=q(n.subtotal,2),e.point_subtotal+=n.point_subtotal;e.subtotal=q(t,2),e.grand_total=q(e.subtotal,2)}calculateLine(e){this.resetLineCalculations(e),e.point_subtotal=e.quantity*e.point;let t=0;e.modifiers&&(t=e.modifiers.reduce((e,t)=>e+t.price*t.quantity,0)),e.subtotal=e.subtotal_before_discount=q(e.quantity*(e.price+t),2),e.item.discountable&&(e.discount_amount>0||e.discount_percent>0)&&(e.discount_calc_type==W.Flat||(e.discount_amount=q(e.subtotal*e.discount_percent,2)),e.subtotal-=e.discount_amount),e.subtotal=q(e.subtotal,2)}calculatePointSubtotal(e){if(e.point_subtotal=0,!(e.lines==null||e.lines.length<1)){for(let t of e.lines)t.point_subtotal=t.quantity*t.point,e.point_subtotal+=t.point_subtotal;e.minus_point=e.point_subtotal}}calculateInvoiceServiceChargeableSubtotal(e){(e.lines==null||e.lines.length<1)&&(e.service_chargeable_subtotal=0),e.service_chargeable_subtotal=q(q(e.lines.filter(e=>!e.is_take_out&&!e.item.is_service_charge_exempt).reduce((e,t)=>e+t.subtotal,0)),2)}calculateDiscount(e,t){if(!e?.lines?.length)return;let n=0;if(e.discountable_subtotal=q(e.lines.filter(e=>e.item.discountable).reduce((e,t)=>e+t.subtotal,0),2),e.discounts?.length){for(let r of e.discounts.filter(e=>e.calc_flow==t))if(!r.applying_item_uids?.length)r.calc_type==W.Flat?n+=r.amount:(r.percent_amount=q((e.discountable_subtotal-e.discount_amount-n)*r.percent),n+=r.percent_amount);else{let t=0,i=!1;for(let n of e.lines)r.applying_item_uids.includes(n.item_uid)&&n.price>t&&(t=n.price,i=!0);if(!i){e.discounts=e.discounts.filter(e=>e.uid!=r.uid);continue}r.calc_type==W.Flat?(r.amount=q(r.amount>t?t:r.amount),n+=r.amount):(r.percent_amount=q(t*r.percent),n+=r.percent_amount)}e.discount_amount+=q(n),e.grand_total=q(e.grand_total-n)}}calculateRounding(e,t,n,r,i){if(e.rounding=0,!t||!r&&!e.payment_has_cash)return;let a=(e.payments?.filter(e=>!e.payment_method?.is_cash)||[]).reduce((e,t)=>e+t.tender_amount-t.change_amount,0),o=a>0?e.grand_total-a:e.grand_total;e.rounding=q(this.roundingStep(o,t,n,i)),e.grand_total+=e.rounding}roundingStep(e,t,n,r){let i=Math.round(e*100),a=Math.round(t*100),o=i%a;if(o===0)return 0;let s;return s=r?o>=a/2?a-o:-o:n?a-o:-o,q(s/100)}calculateDeliveryCharge(e){e.delivery_charge>0&&e.type===H.Delivery&&(e.grand_total+=e.delivery_charge,e.grand_total=q(e.grand_total,2))}calculateServiceCharge(e,t){let n=0;e.service_charge=0,!(e.lines==null||e.lines.length<1)&&(e.type==H.Delivery||e.type==H.TakeOut||(t>0&&(n=e.service_chargeable_subtotal*(t/100)),e.service_charge=q(n,2),e.grand_total+=e.service_charge,e.grand_total=q(e.grand_total,2)))}calculateTax(e,t,n){if(e.tax=0,t<=0)return;let r=this.calculateTaxSubtotalRatio(e),i=e.grand_total-e.service_charge;n===lt.Inclusive?e.tax=q(i*r*t/(100+t)+e.service_charge*t/(100+t),2):(e.tax=q(i*r*t/100+e.service_charge*t/100,2),e.grand_total=q(e.grand_total+e.tax,2))}calculateCreditDeduction(e){e.minus_credit||(e.minus_credit=0),!(e.minus_credit<=0)&&(e.minus_credit=q(e.minus_credit),e.minus_credit>e.grand_total&&(e.minus_credit=q(e.grand_total)),e.grand_total=q(e.grand_total-e.minus_credit))}calculateTip(e){e.tip>0&&(e.grand_total=q(e.grand_total+e.tip,2))}calculateTaxSubtotalRatio(e){let t=1;return!e.lines||!e.lines.some(e=>e.item.is_tax_exempt)||e.grand_total===0||e.subtotal===0||(t=1-e.lines.filter(e=>e.item.is_tax_exempt).reduce((e,t)=>e+t.subtotal,0)/e.subtotal),t}calculateRewardCredit(e,t,n,r){if(e.rewarded_credit=0,e.grand_total<=0||t>0&&t>e.grand_total)return;let i=e.rewarded_credit_rate,a=e.grand_total;n||(a-=e.service_charge),r||(a-=e.tax),a-=e.lines.filter(e=>e.item.is_credit_reward_exempt).reduce((e,t)=>e+t.subtotal,0),e.rewarded_credit=q(a*i,2)}calculateAddCredit(e){let t=0;if(e.add_credit=0,!(!e.lines||e.lines.length<=0)){for(let n of e.lines.filter(e=>e.item.add_credit>0))t+=n.item.add_credit*n.quantity;e.add_credit=t}}calculateAddPoint(e){let t=0;if(e.add_point=0,!(!e.lines||e.lines.length<=0)){for(let n of e.lines.filter(e=>e.item.add_point>0))t+=n.item.add_point*n.quantity;e.add_point=t}}calculateRewardPoint(e,t,n,r){if(e.rewarded_point=0,e.rewarded_point_rate<=0||e.grand_total<=0)return;let i=e.grand_total;n||(i-=e.service_charge),r||(i-=e.tax),i-=e.lines.filter(e=>e.item.is_point_reward_exempt).reduce((e,t)=>e+t.subtotal,0),e.rewarded_point=Math.floor(i*e.rewarded_point_rate)}calculateDiscountFromTargetTotal(e,t,n){if(this.calculate(e,n),t>=e.grand_total)return 0;let r=n.config.rounding.base||.01,i=0,a=e.grand_total-t+r*10;for(;a-i>r/2;){let r=q((i+a)/2,2);if(r===i||r===a)break;let s=o.cloneDeep(e);s.discounts||(s.discounts=[]),s.discounts.push({...new gt,calc_type:W.Flat,calc_flow:G.AfterServiceCharge,amount:r}),this.calculate(s,n),s.grand_total<=t?a=r:i=r}let s=o.cloneDeep(e);if(s.discounts=[...s.discounts||[],{...new gt,calc_type:W.Flat,calc_flow:G.AfterServiceCharge,amount:a}],this.calculate(s,n),s.grand_total>t)throw Error(`Target grand total ${t} is unreachable`);return q(a,2)}resetInvoiceCalculations(e){e.subtotal=0,e.point_subtotal=0,e.service_chargeable_subtotal=0,e.service_charge=0,e.tax=0,e.grand_total=0,e.rounding=0,e.discount_amount=0,e.minus_credit=0,e.rewarded_credit=0,e.rewarded_point=0,e.add_credit=0,e.add_point=0,e.charges&&e.charges.length>0&&e.charges.forEach(e=>{e.amount=0})}resetLineCalculations(e){e.subtotal=0,e.subtotal_before_discount=0,e.point_subtotal=0}calculateChangeAmount(e){if(e.payments.length<=0||e.payments.every(e=>!e.payment_method.is_cash))return;let t=e.grand_total;e.payments.forEach(e=>{e.payment_method.is_cash?(e.change_amount=q(Math.max(0,e.tender_amount-Math.max(0,t))),t=q(t-e.tender_amount)):e.payment_method.allow_custom_amount?(t=q(t-Math.min(e.tender_amount,Math.max(0,t))),e.change_amount=0):(e.change_amount=0,t=q(t-e.tender_amount))})}calculateInvoiceCharges(e,t){if(!(!e.charges||e.charges.length===0))for(let n of e.charges.filter(e=>e.calc_flow===t)){let t=0;switch(n.calc_flow){case G.AfterSubtotal:t=e.subtotal;break;case G.AfterServiceCharge:t=e.subtotal+e.service_charge;break;case G.AfterGrantTotal:t=e.grand_total;break;default:t=e.subtotal}n.percentage>0&&(n.amount=q(t*(n.percentage/100),2)),e.grand_total+=n.amount,e.grand_total=q(e.grand_total,2)}}},Nr=class extends Mr{addItemToLine(e,n,r,i,a,o,s,c,l){let u={...jr,...o};e.lines??(e.lines=[]);let d=this.findOrCreateLine(e,i,u.quantity,u.price,a,u.remark,s,c,l);return i.type==N.Combo&&(d.is_combo=!0),d.uid?(d.quantity+=u.quantity,d.quantity<=0&&(e.lines=e.lines.filter(e=>e.uid!==d.uid))):u.quantity>0&&(d.uid=E.InvoiceLine+t(),e.lines.push(d)),d}duplicateLine(e,n){let r=o.cloneDeep(n);r.is_duplicate=!0,r.duplicated_from_uid=n.uid,r.uid=E.InvoiceLine+t(),e.lines.push(r);for(let i of this.getAttachedLines(e,n.uid)){let n=o.cloneDeep(i);n.uid=E.InvoiceLine+t(),n.attached_to_line_uid=r.uid,e.lines.push(n)}return e}addAttachedItemsToLine(e,t,n,r,i){if(!n?.length)return[];let a=[];for(let o of n){let n=this.addItemToLine(e,r,i,o,[],{quantity:t.quantity},!0);n.attached_to_line_uid=t.uid,a.push(n)}return a}getAttachedLines(e,t){return e.lines?.filter(e=>e.attached_to_line_uid===t)||[]}calibrateDuplicates(e){if(!e.lines||e.lines.length<=0)return e;let t=e.lines.filter(e=>e.is_duplicate);for(let n of t){let t=e.lines.find(e=>e.uid===n.duplicated_from_uid&&!e.is_duplicate);t&&this.compareLines(t,n)?(t.quantity+=n.quantity,t.sent+=n.sent,e.lines=e.lines.filter(e=>e!==n)):n.is_duplicate=!1}return e}toInvoiceCoreLine(e,t=1){let n=new _t;return n.item=o.cloneDeep(e),n.item_uid=e.uid,n.quantity=t,n.price=e.price,n}addModifier(e,t){if(!e||e.length<=0)return[t];{let n=e.findIndex(e=>e.item_uid===t.item_uid&&e.price===t.price);return n<0?e.push(t):e[n].quantity+=t.quantity,e}}changeLinePrice(e,t){return e==null||(e.price=t),e}changeLineDiscount(e,t,n){if(e==null)return e;if(t==W.Percent&&n>100)throw new D(`Discount percent can not be more than 100%`);if(t==W.Flat&&n>e.subtotal)throw new D(`Discount amount can not be more than price`);return e.discount_calc_type=t,t==W.Flat?e.discount_amount=n:e.discount_percent=n,e}minusLineQuantity(e,t,n,r=!1){if(n<=0)throw new D(`Quantity can not be less than 0, input a positive quantity to minus the line quantity`);if(e.lines==null||e.lines.length<=0)return e;if(!t)throw new D(`Line can not be null or empty`);if(t.quantity-t.sent<Math.abs(n)){let i=Math.abs(n)-(t.quantity-t.sent),a=o.cloneDeep(t);a.quantity=i,a.sent=i,r||e.deleted_lines.push(a),t.sent-=i}t.quantity<=n&&(e.lines=e.lines.filter(e=>e.uid!==t.uid)),t.quantity-=n;let i=this.getAttachedLines(e,t.uid);if(t.quantity<=0){let t=new Set(i.map(e=>e.uid));e.lines=e.lines.filter(e=>!t.has(e.uid))}else for(let e of i)e.quantity=t.quantity}addLineQuantity(e,t,n){if(e.lines==null||e.lines.length<=0)return e;t.quantity+=n;for(let n of this.getAttachedLines(e,t.uid))n.quantity=t.quantity}minusModifierQuantity(e,t,n=0){if(!e||e.length<=0)return e;{n=n??0;let r=e.findIndex(e=>e.item_uid===t.item_uid&&e.price===t.price);return r<0||(e[r].quantity<=n?e.splice(r,1):e[r].quantity-=n),e}}changeModifierQuantity(e,t,n){if(!e||e.length<=0)return e;n=n??0;let r=e.findIndex(e=>e.item_uid===t.item_uid&&e.price===t.price);return r<0?e:(e[r].quantity+=n,e[r].quantity<=0&&e.splice(r,1),e)}addModifierQuantity(e,t,n=0){if(!e||e.length<=0)return e;{n=n??0;let r=e.findIndex(e=>e.item_uid===t.item_uid&&e.price===t.price);return r<0||(e[r].quantity+=n),e}}changeModifierPrice(e,t){return e&&(e.price=t,e)}overwriteNoteToLine(e,t){return t&&(e.remark=t),e}findOrCreateLine(e,t,n,r=0,i=[],a=``,o=!1,s,c){if(r=r??t.price,!e.lines||e.lines.length<=0||o)return this.createInvoiceLine(t,n,r,i,a);{let o=e.lines.filter(e=>e.item_uid===t.uid);if(!o||o.length<=0)return this.createInvoiceLine(t,n,r,i,a);if(s&&c){for(let e of o)if(e.is_combo_item&&this.compareModifiers(e.modifiers,i)&&e.remark===a&&e.price===r&&e.combo_line_uid===s&&e.combo_group_uid===c)return e}else for(let e of o)if(!e.is_combo_item&&this.compareModifiers(e.modifiers,i)&&e.remark===a&&e.price===r&&!e.is_take_out)return e;return this.createInvoiceLine(t,n,r,i,a)}}createInvoiceLine(e,t,n=0,r=[],i=``){let a=new vt;return a.item=o.cloneDeep(e),a.item_uid=e.uid,a.quantity=t,a.point=e.minus_point,a.price=n??e.price,a.quantity=t,a.modifiers=r,a.remark=i,a}compareModifiers(e,t){if(e.length!==t.length)return!1;for(let n of e)if(!t.some(e=>e.item_uid===n.item_uid&&e.price===n.price&&e.quantity===n.quantity))return!1;return!0}compareLines(e,t){return!(e.remark!=t.remark||e.price!=t.price||e.is_take_out!=t.is_take_out||e.discount_calc_type!=t.discount_calc_type||e.discount_amount!=t.discount_amount||e.discount_percent!=t.discount_percent||!this.compareModifiers(e.modifiers,t.modifiers))}addComboItemToLine(e,t,n,r,i,a,o,s){let c=this.addItemToLine(e,t,n,r,o,s,!1,i,a);return c.is_combo_item=!0,c.combo_line_uid=i,c.combo_group_uid=a,c}removeAllComboItems(e,t,n=!1){if(!e.lines||e.lines.length==0)return[];let r=e.lines.filter(e=>e.combo_line_uid==t&&e.is_combo_item);return e.lines=o.differenceBy(e.lines,r,`uid`),n||e.deleted_lines.push(...r),r}duplicateComboLines(e,n){if(!n.is_combo)throw new D(`Line is not a combo`);let r=o.cloneDeep(n);return r.uid=E.InvoiceLine+t(),r.is_duplicate=!0,r.duplicated_from_uid=n.uid,e.lines.push(r),e.lines.filter(e=>e.combo_line_uid===n.uid&&e.is_combo_item).forEach(n=>{let i=o.cloneDeep(n);i.uid=E.InvoiceLine+t(),i.combo_line_uid=r.uid,i.is_duplicate=!0,e.lines.push(i)}),e}},Pr=class extends Nr{async addInvoice(e){let t=await this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/add_invoice`,e);if(t.error==O.outdatedInvoice)throw await this.saveOne(t.data),new D(t.error);if(t.error)throw new D(t.error);return t.data}async createInvoice(e,t,n){e.status=U.Open,e.ref_id||(e.ref_id=await this.getRefId()),e.call_num||(e.call_num=e.ref_id.slice(-3)),e.table_name=t.name,e.table_uid=t.uid,t.invoice_uid=e.uid,t.status=M.OPENED,this.sectionItemService.syncInvoiceData(t,e),this.addEmployeeToInvoice(e,n),e.created_at=new Date,e.created_at_timestamp=e.created_at.getTime();let r=(await this.configService.getDefaultOne()).config?.order?.datetime_format;e.humanized_created_at=L(e.created_at,r),t.invoice_created_at=new Date;let i=await this.createKitchenPrintJobs(e),a=await this.createLabelPrintJobs(e),o=await this.createOrderPrintJobs(e),s=this.sortPrintJobsByPrinterSequence([...i,...a,...o]);e.kitchen_print_job_uids||(e.kitchen_print_job_uids=[]),e.label_print_job_uids||(e.label_print_job_uids=[]),e.order_print_job_uids||(e.order_print_job_uids=[]);let c=e.kitchen_print_job_uids.length,l=e.label_print_job_uids.length,u=e.order_print_job_uids.length,d=i.map(e=>e.uid),f=a.map(e=>e.uid),p=o.map(e=>e.uid);d.length>0&&e.kitchen_print_job_uids.push(d),f.length>0&&e.label_print_job_uids.push(f),p.length>0&&e.order_print_job_uids.push(p);let m=this.getItemStockChangeList(e);await this.preprocessInvoice(e);let h={invoice:e,section_item:t};s.length>0&&(h.print_jobs=s),m.length>0&&(h.items=await this.itemService.getItemsWithStockChanges(m));try{let e=await this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${this.methodName}`,h);if(e.error==O.outdatedInvoice)throw await this.saveOne(e.data),h.invoice=e.data,new D(e.error);if(e.error==O.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),h.section_item=e.data,new D(e.error);return h}catch(t){throw e.kitchen_print_job_uids.length=c,e.label_print_job_uids.length=l,e.order_print_job_uids.length=u,t}}async updateInvoice(e,t,n){this.sectionItemService.syncInvoiceData(t,e),this.addEmployeeToInvoice(e,n),e.updated_at=new Date;let r=await this.createKitchenPrintJobs(e),i=await this.createCancelKitchenPrintJobs(e,e.deleted_lines),a=await this.createVoidSlipPrintJobs(e,e.deleted_lines,t),o=await this.createLabelPrintJobs(e),s=await this.createOrderPrintJobs(e),c=this.sortPrintJobsByPrinterSequence([...r,...i,...a,...o,...s]);e.kitchen_print_job_uids||(e.kitchen_print_job_uids=[]),e.label_print_job_uids||(e.label_print_job_uids=[]),e.order_print_job_uids||(e.order_print_job_uids=[]);let l=e.kitchen_print_job_uids.length,u=e.label_print_job_uids.length,d=e.order_print_job_uids.length,f=r.map(e=>e.uid),p=o.map(e=>e.uid),m=s.map(e=>e.uid);f.length>0&&e.kitchen_print_job_uids.push(f),p.length>0&&e.label_print_job_uids.push(p),m.length>0&&e.order_print_job_uids.push(m);let h=this.getItemStockChangeList(e);await this.preprocessInvoice(e);let g={invoice:e,section_item:t};c.length>0&&(g.print_jobs=c),h.length>0&&(g.items=await this.itemService.getItemsWithStockChanges(h));try{let e=await this.http.patch(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/update_invoice`,g);if(e.error==O.outdatedInvoice)throw await this.saveOne(e.data),new D(`${e.error}, system has updated the data, please try again`);if(e.error==O.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),g.section_item=e.data,new D(`${e.error}, system has updated the data, please try again`);return g}catch(t){throw e.kitchen_print_job_uids.length=l,e.label_print_job_uids.length=u,e.order_print_job_uids.length=d,t}}async cancelInvoice(e,t,n){if(e.id_in_server==0&&e.lines.length<=0)throw new D(`The invoice is empty and nothing can be canceled.`);if(e.id_in_server==0)return e.lines=[],{invoice:e,section_item:t};e.status=U.Void,t.invoice_uid=``,t.status=M.CLOSED,this.sectionItemService.reset(t),this.addEmployeeToInvoice(e,n);let r=await this.createReceiptPrintJob(e,R.ReceiptPrinter,!0),i={invoice:e,section_item:t};r&&(i.print_jobs=[r]);let a=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/cancel_invoice`,i);if(a.error==O.outdatedInvoice)throw await this.saveOne(a.data),i.invoice=a.data,new D(a.error);if(a.error==O.outdatedSectionItem)throw await this.sectionItemService.saveOne(a.data),i.section_item=a.data,new D(a.error);return i}async checkInvoice(e,t,n,r){t.status=M.PAYMENT,this.addEmployeeToInvoice(e,n);let i=await this.createReceiptPrintJob(e,R.CheckPrinter,!1,0,r),a=await this.createLabelPrintJobs(e),o=await this.createKitchenPrintJobs(e),s=await this.createOrderPrintJobs(e),c=[...a,...o,...s];i&&c.push(i);let l=this.sortPrintJobsByPrinterSequence(c);e.kitchen_print_job_uids||(e.kitchen_print_job_uids=[]),e.label_print_job_uids||(e.label_print_job_uids=[]),e.order_print_job_uids||(e.order_print_job_uids=[]);let u=e.kitchen_print_job_uids.length,d=e.label_print_job_uids.length,f=e.order_print_job_uids.length,p=o.map(e=>e.uid),m=a.map(e=>e.uid),h=s.map(e=>e.uid);p.length>0&&e.kitchen_print_job_uids.push(p),m.length>0&&e.label_print_job_uids.push(m),h.length>0&&e.order_print_job_uids.push(h);let g=this.getItemStockChangeList(e);await this.preprocessInvoice(e);let _={invoice:e,section_item:t};l.length>0&&(_.print_jobs=l),g.length>0&&(_.items=await this.itemService.getItemsWithStockChanges(g));try{let e=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/check_invoice`,_);if(e.error==O.outdatedInvoice)throw await this.saveOne(e.data),_.invoice=e.data,new D(e.error);if(e.error==O.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),_.section_item=e.data,new D(e.error);return _}catch(t){throw e.kitchen_print_job_uids.length=u,e.label_print_job_uids.length=d,e.order_print_job_uids.length=f,t}}async switchInvoice(e,t,n,r){if(t.uid==n.uid)throw new D(`source and target table can not be the same`);if(t.status!=M.CLOSED)throw new D(`target table is occupied`);if(e.lines==null||e.lines.length<=0)throw new D(`source table has nothing to switch`);t.invoice_uid=e.uid,t.status=n.status,this.sectionItemService.syncInvoiceData(t,e),n.invoice_uid=``,n.status=M.CLOSED,this.sectionItemService.reset(n),e.table_uid=t.uid,e.table_name=t.name,this.addEmployeeToInvoice(e,r);let i={invoice:e,target_section_item:t,source_section_item:n},a=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/switch_invoice`,i);if(a.error==O.outdatedInvoice)throw await this.saveOne(a.data),i.invoice=a.data,new D(a.error);if(a.error==O.outdatedSourceSectionItem)throw await this.sectionItemService.saveOne(a.data),i.source_section_item=a.data,new D(a.error);if(a.error==O.outdatedTargetSectionItem)throw await this.sectionItemService.saveOne(a.data),i.target_section_item=a.data,new D(a.error);return i}async payInvoice(e,t,n,r,i){e.status=U.Paid,t.invoice_uid=``,t.status=M.CLOSED,this.sectionItemService.reset(t),this.addEmployeeToInvoice(e,r),e.paid_at=new Date;let a=(await this.configService.getDefaultOne()).config,o=a?.order?.datetime_format;e.humanized_paid_at=L(e.paid_at,o),e.payment_has_cash=e.payments?.some(e=>e.payment_method?.is_cash===!0);let s=this.mergeStockChangeLists(this.getItemStockChangeList(e),this.getModifierStockChangeList(e)),c=await this.sectionService.getOne(t.section_uid),l=await this.createLabelPrintJobs(e),u=await this.createReceiptPrintJob(e,R.ReceiptPrinter,c?.disable_auto_print_receipt||!1,0,i),d=await this.createKitchenPrintJobs(e),f=await this.createCancelKitchenPrintJobs(e,e.deleted_lines),p=await this.createVoidSlipPrintJobs(e,e.deleted_lines,t),m=await this.createOrderPrintJobs(e),h=[...l,...d,...f,...p,...m];u&&h.push(u);let g=this.sortPrintJobsByPrinterSequence(h);e.kitchen_print_job_uids||(e.kitchen_print_job_uids=[]),e.label_print_job_uids||(e.label_print_job_uids=[]),e.order_print_job_uids||(e.order_print_job_uids=[]);let _=e.kitchen_print_job_uids.length,v=e.label_print_job_uids.length,y=e.order_print_job_uids.length,b=d.map(e=>e.uid),x=l.map(e=>e.uid),S=m.map(e=>e.uid);b.length>0&&e.kitchen_print_job_uids.push(b),x.length>0&&e.label_print_job_uids.push(x),S.length>0&&e.order_print_job_uids.push(S),await this.preprocessInvoice(e);let C={invoice:e,section_item:t,till:n};g.length>0&&(C.print_jobs=g),s.length>0&&(C.items=await this.itemService.getItemsWithStockChanges(s));try{let t=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/pay_invoice`,C);if(t.error==O.outdatedInvoice)throw await this.saveOne(t.data),C.invoice=t.data,new D(`${t.error}, system has updated the data and please try again`);if(t.error==O.outdatedSectionItem)throw await this.sectionItemService.saveOne(t.data),C.section_item=t.data,new D(`${t.error}, system has updated the data and please try again`);if(e.call_num&&a?.ods?.enabled){let t=new kr;t.order_number=e.call_num,await this.orderDisplayService.addOne(t)}return C}catch(t){throw e.kitchen_print_job_uids.length=_,e.label_print_job_uids.length=v,e.order_print_job_uids.length=y,t}}async directPayInvoice(e,t,n,r,i,a=!1){e.status=U.Paid,n!=null&&this.addEmployeeToInvoice(e,n),e.paid_at=new Date;let o=(await this.configService.getDefaultOne()).config,s=o?.order?.datetime_format;e.humanized_paid_at=L(e.paid_at,s),e.created_at=new Date,e.created_at_timestamp=e.created_at.getTime(),e.humanized_created_at=L(e.created_at,s),e.ref_id||(e.ref_id=await this.getRefId()),e.call_num||(e.call_num=e.ref_id.slice(-3)),e.payment_has_cash=e.payments?.some(e=>e.payment_method?.is_cash===!0);let c=this.mergeStockChangeLists(this.getItemStockChangeList(e),this.getModifierStockChangeList(e)),l=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,u=(l?.section_uid?await this.sectionService.getOne(l.section_uid):null)?.disable_auto_print_receipt||!1,d=null,f=null;if(r&&r.type==R.KioskPrinter){let t=!!o?.kiosk?.disable_receipt_printer_receipt||u;d=await this.createReceiptPrintJob(e,R.ReceiptPrinter,t),f=await this.createReceiptPrintJob(e,R.KioskPrinter,!1,0,r,i)}else d=await this.createReceiptPrintJob(e,R.ReceiptPrinter,u,0,r);let p=await this.createLabelPrintJobs(e),m=await this.createKitchenPrintJobs(e,a),h=await this.createOrderPrintJobs(e),g=[...p,...m,...h];d&&g.push(d),f&&g.push(f);let _=this.sortPrintJobsByPrinterSequence(g),v=m.map(e=>e.uid),y=p.map(e=>e.uid),b=h.map(e=>e.uid);v.length>0&&(e.kitchen_print_job_uids=[v]),y.length>0&&(e.label_print_job_uids=[y]),b.length>0&&(e.order_print_job_uids=[b]),await this.preprocessInvoice(e);let x={invoice:e,till:t};_.length>0&&(x.print_jobs=_),c.length>0&&(x.items=await this.itemService.getItemsWithStockChanges(c));let S=await this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/direct_pay_invoice`,x);if(S.error==O.outdatedInvoice)throw await this.saveOne(S.data),x.invoice=S.data,new D(S.error);if(e.call_num&&o?.ods?.enabled){let t=new kr;t.order_number=e.call_num,await this.orderDisplayService.addOne(t)}return x}async voidInvoice(e,t,n,r){n&&(e.etc.void_reason=n);let i=e.status;e.status=U.Void,e.voided_at=new Date;let a=(await this.configService.getDefaultOne()).config?.order?.datetime_format;e.humanized_voided_at=L(e.voided_at,a),t&&(t.deleted_at=new Date),this.addEmployeeToInvoice(e,r);let o=(await this.configService.getDefaultOne()).config,s=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,c=await this.createReceiptPrintJob(e,R.ReceiptPrinter,!0),l=[];o.kitchen.print_cancel_whole_invoice&&(l=await this.createCancelKitchenPrintJobs(e,e.lines)||[]);let u=[];o.receipt.print_cancel_whole_invoice&&(u=await this.createVoidSlipPrintJobs(e,e.lines,s)||[]);let d=[...l,...u];c&&d.push(c);let f={invoice:e,till:t};d.length>0&&(f.print_jobs=d);let p=await this.tillService.db.table(`tills`).where({invoice_uid:e.uid}).toArray(),m=p.filter(e=>e.type===A.CashInvoice&&!e.deleted_at).reduce((e,t)=>e+t.amount,0);if(m>0){let t=new j;t.type=A.CashInvoice,t.amount=-m,t.invoice_uid=e.uid,t.shift_uid=p[0]?.shift_uid,t.user_uid=r?.uid||p[0]?.user_uid,f.till=t}s&&s.status!=M.CLOSED&&s.invoice_uid===e.uid&&(s.invoice_uid=``,s.status=M.CLOSED,f.section_item=s);let h=this.getItemStockChangeList(e,!0),g=i==U.Paid?this.mergeStockChangeLists(h,this.getModifierStockChangeList(e,!0)):h;g.length>0&&(f.items=await this.itemService.getItemsWithStockChanges(g));let _=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/void_invoice`,f);if(_.error==O.outdatedInvoice)throw await this.saveOne(_.data),f.invoice=_.data,new D(_.error);return f}async duplicateInvoice(e,n){if(e.status!=U.Paid)throw new D(`invalid invoice status`);let r=o.cloneDeep(e);if(r.etc.is_duplicate=!0,r.etc.duplicated_from_uid=r.uid,r.uid=E.Invoice+t(),r.status=U.Open,r.ref_id=await this.getRefId(),this.addEmployeeToInvoice(r,n),r.lines)for(let e of r.lines)e.uid=E.InvoiceLine+t();if(r.payments)for(let e of r.payments)e.uid=E.Payment+t();return r}async reprintReceipt(e,n=!1,r){if(!e?.receipt_print_job_uid)throw new D(`The invoice does not have a receipt`);let i=await this.printJobService.getOne(e.receipt_print_job_uid);if(!i){let t=new f().addParam(`uid`,`EqualTo`,e.receipt_print_job_uid),n=await this.printJobService.autoquery(t);if(!n.results||n.results.length<=0)throw new D(`The invoice does not have a receipt`);i=n.results[0]}let a=r;if(a||(a=await this.printerService.getOne(i.printer_uid)),a||(a=await this.printerService.getDefaultReceiptPrinter()),!a)throw new D(`Receipt printer not found`);return i=this.printJobService.replacePrinter(i,a),i.uid=E.PrintJob+t(),i.save_only=n,i.status=Ye.Queued,i.print_times=1,i.printed=0,i.retries=0,i.created_at_timestamp=Date.now(),await this.printJobService.addOne(i),i}async printLastKitchenSlips(e){let n=await this.getOne(e);if(!n)throw new D(`Invoice not found`);let r=n.kitchen_print_job_uids?.[n.kitchen_print_job_uids.length-1]||[],i=n.label_print_job_uids?.[n.label_print_job_uids.length-1]||[],a=[...r,...i];if(a.length===0)throw new D(`No kitchen or label print found`);let o=new f().addParam(`uid`,`In`,a),s=await this.printJobService.autoquery(o);if(!s.results||s.results.length===0)throw new D(`Print jobs not found`);for(let e of s.results){let n=await this.printerService.getOne(e.printer_uid);if(!n)continue;let r=this.printJobService.replacePrinter(e,n),i=r.uid;r.uid=E.PrintJob+t(),r.save_only=!1,r.status=Ye.Queued,r.print_times=1,r.printed=0,r.retries=0,r.created_at_timestamp=Date.now(),r.meta||(r.meta={}),r.meta.is_reprint=!0,r.meta.parent_uid=i,await this.printJobService.addOne(r)}return!0}async printLastOrderDocket(e){let n=await this.getOne(e);if(!n)throw new D(`Invoice not found`);let r=n.order_print_job_uids?.[n.order_print_job_uids.length-1]||[];if(r.length===0)throw new D(`No order docket print found`);let i=new f().addParam(`uid`,`In`,r),a=await this.printJobService.autoquery(i);if(!a.results||a.results.length===0)throw new D(`Print jobs not found`);for(let e of a.results){let n=await this.printerService.getOne(e.printer_uid);if(!n)continue;let r=this.printJobService.replacePrinter(e,n),i=r.uid;r.uid=E.PrintJob+t(),r.save_only=!1,r.status=Ye.Queued,r.print_times=1,r.printed=0,r.retries=0,r.created_at_timestamp=Date.now(),r.meta||(r.meta={}),r.meta.is_reprint=!0,r.meta.parent_uid=i,await this.printJobService.addOne(r)}return!0}addInvoiceDiscount(e,t,n,r=G.AfterSubtotal,i=`custom`,a={}){if(e.discounts||(e.discounts=[]),t==W.Percent&&n>100)throw new D(`Discount percent can not be more than 100%`);let o=new gt;return o.calc_type=t,o.calc_flow=r,o.name=i,o.name_translation=a,t==W.Flat?o.amount=n:o.percent=n,e.discounts.push(o),e}addCouponToInvoice(e,t,n=G.AfterSubtotal){e.discounts||(e.discounts=[]);let r=new gt;if(r.calc_type=t.coupon.discount_calc_type==1?W.Flat:W.Percent,r.calc_flow=n,r.name=t.coupon.name,r.calc_type==W.Flat?r.amount=t.coupon.discount_amount:r.percent=t.coupon.discount_percent,r.coupon_uid=t.guid,t.coupon.applying_plus.applying_items?.length>0&&(r.applying_item_uids=t.coupon.applying_plus.applying_items,!e.lines||o.intersection(r.applying_item_uids,e.lines.map(e=>e.item_uid)).length===0))throw new D(`Coupon can not applied to any product in this order`);return e.discounts.push(r),e}removeInvoiceDiscount(e,t){return e.discounts&&(e.discounts=e.discounts.filter(e=>e.uid!==t)),e}overwriteNoteToInvoice(e,t){return t&&(e.remark=t),e}addSalesPersonToInvoice(e,t){return e.sales_user_uid=t,e}addPaxToInvoice(e,t){return e.pax=t,e}addCustomerToInvoice(e,t){if(!t)throw new D(`Customer object can not be null`);return e.customer_id=t.id,e.customer=o.cloneDeep(t),e}async autoQuery(e,t){return await this.http.get(`sapi/v5/merchants/${this.options.merchant_uid}/${this.moduleName}`,{params:e.build(),...t})}appendInvoice(e,t){if(e?.id_in_server==0)return t;for(let n of t.lines)if(n.is_combo||n.is_combo_item)n.quantity>0&&e.lines.push(n);else{let t=this.findOrCreateLine(e,n.item,n.quantity,n.price,n.modifiers,n.remark);t.uid?t.quantity+=n.quantity:n.quantity>0&&e.lines.push(n)}return t.remark&&(e.remark=t.remark),t.customer_id&&!e.customer_id&&(e.customer_id=t.customer_id),e}async mergeInvoice(e,t){if(t.lines?.length==0)throw new D(`Source invoice has no nothing to merge`);if(t.lines.some(e=>e.quantity!=e.sent))throw new D(`Please send first before merging`);if(!await this.getOne(e.uid))throw new D(`Target invoice not found`);if(!await this.getOne(t.uid))throw new D(`Source invoice not found`);if(e?.id_in_server==0)throw new D(`Target invoice is not synced to server`);if(t?.id_in_server==0)throw new D(`Source invoice is not synced to server`);for(let n of t.lines)if(n.is_combo||n.is_combo_item)n.quantity>0&&e.lines.push(n);else{let t=this.findOrCreateLine(e,n.item,n.quantity,n.price,n.modifiers,n.remark);t.uid?t.quantity+=n.quantity:n.quantity>0&&e.lines.push(n)}return e.customer_id||(e.customer_id=t.customer_id),e}async getRefId(){let e=(await this.configService.getDefaultOne()).config?.order?.ref_prefix||`01`,t=(await this.http.get(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${this.methodName}/get_invoice_counter`)).data.toString().padStart(9,`0`);return`${e}${this.formatDate(new Date)}${t}`}async changePayments(e,t){if(e.status!=U.Paid)throw new D(`invalid invoice status`);if(!t||t.length<1)throw new D(`invalid options`);for(let n of t){let t=e.payments.find(e=>e.uid==n.source_payment.uid);if(!t)throw new D(`payment not found`);t.payment_method_uid=n.target_payment_method.uid,t.payment_method_code=n.target_payment_method.payment_method_code,t.payment_method_name=n.target_payment_method.name,t.payment_method=o.cloneDeep(n.target_payment_method),t.payment_method_history=o.cloneDeep(n.target_payment_method),t.payment_method_history.changed_at=new Date}return e.is_sales_exclusive=e.payments.some(e=>e.payment_method.is_sales_exclusive),e}formatDate(e){let t=e.getFullYear().toString().slice(-2),n=(e.getMonth()+1).toString().padStart(2,`0`),r=e.getDate().toString().padStart(2,`0`);return t+n+r}addEmployeeToInvoice(e,t){return t?(e.employee_uid=t.uid,e.employee_name=t.name,e):e}async createReceiptPrintJob(e,t,n=!1,r=0,i=null,a){let o;if(i)o=i;else if(t==R.ReceiptPrinter||t==R.CheckPrinter){let n=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,r=t==R.ReceiptPrinter?n?.receipt_printer_uid:n?.check_printer_uid;r&&(o=await this.printerService.getOne(r)),o||(o=t==R.ReceiptPrinter?await this.printerService.getDefaultReceiptPrinter():await this.printerService.getDefaultCheckPrinter())}if(!o||!o.print_template_uid)return null;r||(r=o.print_times);let s=await this.configService.getDefaultOne(),c=await this.printTemplateService.getOneByParams({uid:o.print_template_uid});if(!c)throw new D(`Print template not found`);t==R.ReceiptPrinter&&!s.config?.receipt?.enabled&&(n=!0);let l=await this.printTemplateService.renderPrintTemplate(e,s.config,c,{...new V,printer_name:o.name}),u=new B(o,l,n,r);return t!=R.ReceiptPrinter&&(u.printer_type=t),o.connection_type!=qe.ETHERNET&&(u.connection_type=o.connection_type),t==R.ReceiptPrinter&&(e.receipt_print_job_uid=u.uid),a&&(u.device_uid_to_print=a),u}sortLinesByItemSequence(e){return o.chain(e||[]).groupBy(e=>e.is_combo_item?e.combo_line_uid:e.uid).map(e=>o.sortBy(e,[e=>!e.is_combo,e=>e.item.printing_sequence||e.item.sequence||999999])).sortBy(e=>e[0].item.printing_sequence||e[0].item.sequence||999999).flatten().value()}getSortedLines(e,t){return t.disable_printing_sequence?e:this.sortLinesByItemSequence(e)}sortLineModifiers(e){for(let t of e){if(!t.modifiers?.length||!t.item.modifiers?.length)continue;let e=new Map(t.item.modifier_categories?.map(e=>[e.uid,e.printing_sequence??999999])),n=new Map(t.item.modifiers.map(e=>[e.uid,e]));t.modifiers.sort((t,r)=>{let i=n.get(t.item_uid),a=n.get(r.item_uid);return(e.get(i?.category_uid)??999999)-(e.get(a?.category_uid)??999999)||(i?.sequence??0)-(a?.sequence??0)})}}async createKitchenPrintJobs(e,t=!1){let n=(await this.configService.getDefaultOne()).config;if(!n.kitchen.enabled&&!t||e.lines.every(e=>e.sent==e.quantity))return[];let r=[],{lines:i,printerUids:a}=this.filterLinesAndPrintersToPrint(e.lines,R.KitchenPrinter),s=await this.printerService.getPrintersByUids(a);for(let t of s){let a=await this.printTemplateService.getOneByParams({uid:t.print_template_uid});if(!a)continue;let s=i.filter(e=>e.item.kitchen_printers_uids.includes(t.uid)),c=this.getSortedLines(s,t);this.sortLineModifiers(c);let l=o.cloneDeep(e);if(t.kitchen_itemized_print)for(let e of c){l.lines=[e];let i=new B(t,await this.printTemplateService.renderPrintTemplate(l,n,a,{...new V,printer_name:t.name}),!1,t.print_times);r.push(i)}else{l.lines=c;let e=new B(t,await this.printTemplateService.renderPrintTemplate(l,n,a,{...new V,printer_name:t.name}),!1,t.print_times);r.push(e)}}return r}async createOrderPrintJobs(e){let t=(await this.configService.getDefaultOne()).config;if(!t.receipt.print_docket||e.lines.every(e=>e.sent==e.quantity))return[];let n=[],{lines:r,printerUids:i}=this.filterLinesAndPrintersToPrint(e.lines,R.OrderPrinter),a=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,s=await this.printerService.getPrintersByUids(i);for(let i of s){if(a?.order_printer_uids?.length>0&&!a.order_printer_uids.includes(i.uid))continue;let s=await this.printTemplateService.getOneByParams({uid:i.print_template_uid});if(!s)continue;let c=r.filter(e=>e.item.order_printers_uids.includes(i.uid)),l=this.getSortedLines(c,i);this.sortLineModifiers(l);let u=o.cloneDeep(e);u.lines=l;let d=new B(i,await this.printTemplateService.renderPrintTemplate(u,t,s,{...new V,printer_name:i.name}),!1,i.print_times);n.push(d)}return n}async createVoidSlipPrintJobs(e,t,n){if(!t||t.length===0||e.action===ut.PayAtCounter)return[];let r=(await this.configService.getDefaultOne()).config;if(!r.receipt.print_cancel_slip||(t=t.filter(e=>!e.is_cancel_slip_printed),t.length===0))return[];let i=new Set;for(let e of t)e.item?.order_printers_uids&&e.item.order_printers_uids.forEach(e=>i.add(e));let a=Array.from(i);if(a.length===0)return[];let s=await this.printerService.getPrintersByUids(a),c=[];for(let i of s){if(n?.order_printer_uids?.length>0&&!n.order_printer_uids.includes(i.uid))continue;let a=await this.printTemplateService.getOneByParams({uid:i.print_template_uid});if(!a)continue;let s=t.filter(e=>e.item?.order_printers_uids?.includes(i.uid));if(s.length===0)continue;let l=this.getSortedLines(s,i);this.sortLineModifiers(l);let u=o.cloneDeep(e);u.lines=l;let d=new B(i,await this.printTemplateService.renderPrintTemplate(u,r,a,{...new V,printer_name:i.name,is_cancel:!0}),!1,i.print_times);c.push(d)}for(let e of t)e.is_cancel_slip_printed=!0;return c}async createLabelPrintJobs(e){let t=(await this.configService.getDefaultOne()).config;if(e.lines.every(e=>e.sent==e.quantity))return[];let n=[],{lines:r,printerUids:i}=this.filterLinesAndPrintersToPrint(e.lines,R.LabelPrinter);if(i.length==0||r.length==0)return[];let a=await this.printerService.getPrintersByUids(i),s=o.cloneDeep(e);this.sortLineModifiers(r);let c=r.length,l=1;for(let e of r)e.meta.total_index=c,e.meta.index=l,l++;for(let e of a)for(let i of r){if(!i.item.label_printers_uids.includes(e.uid))continue;let r=await this.printTemplateService.getOneByParams({uid:e.print_template_uid});if(!r||!r.commands)continue;let a=d.compile(r.commands);s.lines=[i];let o=a({invoice:s,config:t}),c=new B(e,new I,!1,e.print_times);c.commands=o,n.push(c)}return n}filterLinesAndPrintersToPrint(e,t){let n;switch(t){case R.KitchenPrinter:n=`kitchen_printers_uids`;break;case R.OrderPrinter:n=`order_printers_uids`;break;case R.LabelPrinter:n=`label_printers_uids`;break;default:n=`kitchen_printers_uids`}let r=[],i=new Set;for(let a of e)if(a.quantity<=a.sent)continue;else if(!a.item[n]||a.item[n].length==0)continue;else{a.item[n].forEach(e=>i.add(e));let e=o.cloneDeep(a);if(e.quantity-=e.sent,t==R.LabelPrinter)for(let t=0;t<e.quantity;t++){let t=o.cloneDeep(e);t.quantity=1,r.push(t)}else r.push(e)}return{lines:r,printerUids:Array.from(i)}}filterDeletedLinesForCancelPrint(e){let t=[],n=new Set;for(let r of e){if(r.is_cancel_printed||!r.item.kitchen_printers_uids||r.item.kitchen_printers_uids.length==0)continue;r.item.kitchen_printers_uids.forEach(e=>n.add(e));let e=o.cloneDeep(r);t.push(e)}return{lines:t,printerUids:Array.from(n)}}async createCancelKitchenPrintJobs(e,t){let n=(await this.configService.getDefaultOne()).config;if(!n.kitchen.print_cancel_slip||!t||t.length===0||e.action===ut.PayAtCounter)return[];let{lines:r,printerUids:i}=this.filterDeletedLinesForCancelPrint(t);if(r.length===0)return[];let a=await this.printerService.getPrintersByUids(i),s=[];for(let t of a){let i=await this.printTemplateService.getOneByParams({uid:t.print_template_uid});if(!i)continue;let a=r.filter(e=>e.item.kitchen_printers_uids.includes(t.uid)),c=this.getSortedLines(a,t);this.sortLineModifiers(c);let l=o.cloneDeep(e);if(t.kitchen_itemized_print)for(let e of c){l.lines=[e];let r=new B(t,await this.printTemplateService.renderPrintTemplate(l,n,i,{printer_name:t.name,kitchen_itemized_print:t.kitchen_itemized_print,is_cancel:!0}),!1,t.print_times);s.push(r)}else{l.lines=c;let e=new B(t,await this.printTemplateService.renderPrintTemplate(l,n,i,{printer_name:t.name,kitchen_itemized_print:t.kitchen_itemized_print,is_cancel:!0}),!1,t.print_times);s.push(e)}}for(let t of e.deleted_lines)t.is_cancel_printed=!0;return s}sortPrintJobsByPrinterSequence(e){return e.sort((e,t)=>(e?.print_sequence??999)-(t?.print_sequence??999))}async preprocessInvoice(e){if(e.lines)for(let t of e.lines)t.sent=t.quantity;return e}addInvoiceCharge(e,t,n,r,i=G.AfterSubtotal){e.charges||(e.charges=[]);let a=new pt;return a.name=t,a.percentage=n,a.amount=r,a.calc_flow=i,e.charges.push(a),e}removeInvoiceCharge(e,t){return e.charges&&(e.charges=e.charges.filter(e=>e.uid!==t)),e}getItemStockChangeList(e,t=!1){let n=new Map;for(let r of e.lines||[]){let e=t?-(r.sent||0):r.quantity-(r.sent||0);if(e===0)continue;let i=n.get(r.item_uid)||new he(r.item_uid);i.quantity-=e,n.set(r.item_uid,i)}for(let t of e.deleted_lines||[]){let e=(t.sent||0)-(t.stock_reverted||0);if(e<=0)continue;let r=n.get(t.item_uid)||new he(t.item_uid);r.quantity+=e,n.set(t.item_uid,r),t.stock_reverted=t.sent}return Array.from(n.values())}getModifierStockChangeList(e,t=!1){if(!e.lines||e.lines.length===0)return[];let n=new Map;for(let r of e.lines){if(!r.modifiers||r.modifiers.length===0)continue;let e=n.get(r.item_uid)||new he(r.item_uid);for(let n of r.modifiers){let i=e.modifiers.find(e=>e.item_uid===n.item_uid);i||(i={item_uid:n.item_uid,quantity:0},e.modifiers.push(i)),i.quantity+=t?r.quantity*n.quantity:-(r.quantity*n.quantity)}n.set(r.item_uid,e)}return Array.from(n.values())}mergeStockChangeLists(...e){let t=new Map;for(let n of e)for(let e of n){let n=t.get(e.item_uid)||new he(e.item_uid);n.quantity+=e.quantity;for(let t of e.modifiers){let e=n.modifiers.find(e=>e.item_uid===t.item_uid);e||(e={item_uid:t.item_uid,quantity:0},n.modifiers.push(e)),e.quantity+=t.quantity}t.set(e.item_uid,n)}return Array.from(t.values())}sliceInvoice(e){if(!e||!e.lines||e.lines.length===0)return[];let t=[];for(let n of e.lines)for(let r=0;r<n.quantity;r++){let r=o.cloneDeep(e),i=o.cloneDeep(n);i.quantity=1,r.lines=[i],t.push(r)}return t}},Fr=class extends Pr{},Ir=class extends K{constructor(e,t,n,r=`employee_roles`,i=`employee_role`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Lr=class extends K{constructor(e,t,n,r=`employees`,i=`employee`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async login(e,t){try{let n=await this.getOne(e);if(n){if(await p.compare(t,n.password))return!0;throw new D(`Password is incorrect`)}else throw new D(`User not found`)}catch(e){throw e instanceof D?e:new D(`Unexpected error, login failed`)}}async createEmployee(e){try{if(await this.getOne(e.uid))throw new D(`User already exists`);return e.password&&(e.password=await p.hash(e.password,12)),this.addOne(e)}catch(e){throw e instanceof D?e:new D(`Unexpected error, creating employee failed`)}}async changePassword(e){try{return await p.hash(e,12)}catch{throw new D(`Unexpected error, changing password failed`)}}},Rr=class extends K{constructor(e,t,n,r=`items`,i=`item`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async search(e){return this.db.transaction(`r`,[this.db.table(this.moduleName),this.db.table(`categories`)],async()=>{let t=await this.db.table(this.moduleName).where(`name`).anyOfIgnoreCase(e).or(`codename`).anyOfIgnoreCase(e).or(`barcode`).anyOfIgnoreCase(e).toArray();if(!t.length)return t;let n=await this.db.table(`categories`).toArray(),r=new Map(n.map(e=>[e.uid,e]));return t.filter(e=>e.non_searchable!==!0&&r.get(e.category_uid)?.non_searchable!==!0)})}async addModifierCategory(e,n){return n.uid=E.ItemModifierCategory+t(),e.modifier_categories||(e.modifier_categories=[]),e.modifier_categories.push(n),e}async updateModifierCategory(e,t){if(!e.modifier_categories)throw e.modifier_categories=[],new D(`Item does not have any modifier categories`);let n=e.modifier_categories.findIndex(e=>e.uid===t.uid);if(n===-1)throw new D(`Modifier category not found`);return e.modifier_categories[n]=t,e}async removeModifierCategory(e,t){if(!e.modifier_categories)throw e.modifier_categories=[],new D(`Item does not have any modifier categories`);return e.modifier_categories=e.modifier_categories.filter(e=>e.uid!==t.uid),e}async addModifier(e,n){return e.modifiers||(e.modifiers=[]),n.uid=E.ItemModifier+t(),e.modifiers.push(n),e}async updateModifier(e,t){if(!e.modifiers)throw e.modifiers=[],new D(`Item does not have any modifiers`);let n=e.modifiers.findIndex(e=>e.uid===t.uid);if(n===-1)throw new D(`Modifier not found`);return e.modifiers[n]=t,e}async removeModifier(e,t){if(!e.modifiers)throw e.modifiers=[],new D(`Item does not have any modifiers`);return e.modifiers=e.modifiers.filter(e=>e.uid!==t.uid),e}async attachModifierToGroup(e,t,n){if(!e.modifier_categories)throw e.modifier_categories=[],new D(`Item does not have any modifier categories`);if(!e.modifier_categories.find(e=>e.uid===n))throw new D(`Modifier category not found`);let r=e.modifiers.find(e=>e.uid===t);if(!r)throw new D(`Modifier not found`);return r.category_uid=n,e}async addImageAsync(e,t){let n=a(),r=this.getFileExtension(e);await this.http.post(`api/v5/merchants/`+this.options.merchant_uid+`/upload-image`,new rn({base64:await this.convertFileToBase64(e),name:n,extension:this.getFileExtension(e)})),t.image_url=`${this.options.base_url}images/${n}.${r}`,t.image_thumbnail_url=`${this.options.base_url}images/${n}.thumbnail.${r}`}async changeToSoldOut(e){let t=await this.getOne(e);if(!t)throw new D(`Item not found`);return t.stock=0,t.is_sold_out=!0,this.updateOne(t.id_in_server,t)}async changeToAvailable(e,t=1){let n=await this.getOne(e);if(!n)throw new D(`Item not found`);return n.stock=t,n.is_sold_out=!1,this.updateOne(n.id_in_server,n)}async changeStock(e,t){let n=await this.getOne(e);if(!n)throw new D(`Item not found`);let r=Number(n.stock);return n.stock=(isNaN(r)?0:r)+t,this.updateOne(n.id_in_server,n)}async changeItemsStock(e){let t=[];for(let n of e){let e=await this.getOne(n.item_uid);if(!e)continue;let r=Number(e.stock);e.stock=(isNaN(r)?0:r)+n.quantity;for(let t of n.modifiers){let n=e.modifiers?.find(e=>e.uid===t.item_uid);if(!n)continue;let r=Number(n.stock);n.stock=(isNaN(r)?0:r)+Number(t.quantity)}t.push(e)}await this.updateMany(t)}async getItemsWithStockChanges(e){let t=[];for(let n of e){let e=await this.getOne(n.item_uid);if(e){e.stock=(Number(e.stock)||0)+n.quantity;for(let t of n.modifiers){let n=e.modifiers?.find(e=>e.uid===t.item_uid);n&&(n.stock=(Number(n.stock)||0)+t.quantity)}t.push(e)}}return t}convertFileToBase64(e){return new Promise((t,n)=>{let r=new FileReader;r.onloadend=()=>{typeof r.result==`string`?t(r.result.split(`,`)[1]):n(Error(`Could not convert file to Base64.`))},r.onerror=()=>n(Error(`File reading failed.`)),r.readAsDataURL(e)})}getFileExtension(e){let t=e.name,n=t.lastIndexOf(`.`);return n===-1||n===t.length-1?``:t.slice(n+1)}async cloneItem(e){let n=o.cloneDeep(e);if(n.uid=E.Item+t(),n.id_in_server=0,!n.modifier_categories||n.modifier_categories.length===0)return n;let r=[],i=[];for(let e of n.modifier_categories){let t=n.modifiers?.filter(t=>t.category_uid===e.uid);if(!t||t.length===0)continue;let{modifierCategory:a,modifiers:o}=await this.cloneModifiers(e,t);r.push(a),i.push(...o)}return n.modifier_categories=r,n.modifiers=i,n}async cloneModifiers(e,n){let r=o.cloneDeep(e);r.uid=E.ItemModifierCategory+t();let i=[];for(let e of n){let n=o.cloneDeep(e);n.uid=E.ItemModifier+t(),n.category_uid=r.uid,i.push(n)}return{modifierCategory:r,modifiers:i}}async copyModifierGroupToItems(e,t,n){if(!e||!t?.length||!n?.length)throw new D(`Invalid input parameters`);let r=[];for(let i of n){i.modifier_categories=i.modifier_categories||[],i.modifiers=i.modifiers||[];let{modifierCategory:n,modifiers:a}=await this.cloneModifiers(e,t);i.modifier_categories.push(n),i.modifiers.push(...a),r.push(i)}return await this.updateMany(r),r}sanitize(e){if(e.name&&(e.name=e.name.trim()),e.name_translations)for(let t in e.name_translations)e.name_translations[t]&&(e.name_translations[t]=e.name_translations[t].trim());if(e.type!==N.Combo)return e.combo_groups=[],e;if(!e.combo_groups?.length)return e;for(let t of e.combo_groups)for(let e of t.combo_items)delete e.combo_item;return e}},zr=class extends K{constructor(e,t,n,r=`categories`,i=`category`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async addSubcategory(e,t){return e.subcategories||(e.subcategories=[]),e.subcategories.push(t),e.has_subcategory||(e.has_subcategory=!0),e.id_in_server?await this.updateOne(e.id_in_server,e):await this.addOne(e),e}async updateSubcategory(e,t){if(!e.subcategories)throw e.subcategories=[],e.has_subcategory&&(e.has_subcategory=!1),new D(`Category does not have any subcategories`);let n=e.subcategories.findIndex(e=>e.uid===t.uid);if(n===-1)throw new D(`Subcategory not found`);return e.subcategories[n]=t,e.id_in_server?await this.updateOne(e.id_in_server,e):await this.addOne(e),e}async removeSubcategory(e,t){if(!e.subcategories)throw e.subcategories=[],e.has_subcategory&&(e.has_subcategory=!1),new D(`Category does not have any subcategories`);return e.subcategories=e.subcategories.filter(e=>e.uid!==t),e.id_in_server?await this.updateOne(e.id_in_server,e):await this.addOne(e),e}},Br=class extends K{constructor(e,t,n,r=`configs`,i=`config`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i,v(this,`configFactories`,{general:()=>new Rt,product:()=>new Lt,till:()=>new zt,report:()=>new Bt,receipt:()=>new Vt,kitchen:()=>new Ht,kds:()=>new Ut,label:()=>new Wt,order:()=>new Gt,payment:()=>new qt,user:()=>new Jt,tax:()=>new Yt,rounding:()=>new Qt,charges:()=>new Xt,currency:()=>new Zt,inventory:()=>new $t,pax_config:()=>new en,gto:()=>new tn,cash_drawer:()=>new nn,marketing:()=>new jt})}async updateConfig(e,t){let n=await this.getDefaultOne();n||(n=new xt);let r=this.configFactories[e],i=n.config[e]||{};return n.config[e]||(r&&typeof r==`function`?n.config[e]=r():n.config[e]={},i=n.config[e]),Object.keys(t).forEach(e=>{t[e]!==void 0&&(i[e]=t[e])}),n.id_in_server?this.updateOne(n.id_in_server,n):this.addOne(n)}async updateGeneralConfig(e){let t=await this.getDefaultOne();t||(t=new xt);let n=t.config.general;return Object.keys(e).forEach(t=>{e[t]!==void 0&&(n[t]=e[t])}),t.id_in_server?this.updateOne(t.id_in_server,t):this.addOne(t)}async updateCache(e){let t=await this.getDefaultOne();return t.cache={...t.cache,...e},t.id_in_server?this.updateOne(t.id_in_server,t):this.addOne(t)}async uploadFile(e){let t=a(),n=Dn(e);return await this.http.post(`api/v5/merchants/`+this.options.merchant_uid+`/upload-image`,new rn({base64:await On(e),name:t,extension:n})),{file_url:`${this.options.base_url}images/${t}.${n}`,thumbnail_url:`${this.options.base_url}images/${t}.thumbnail.${n}`}}},Vr=class extends K{constructor(e,t,n,r=`sections`,i=`section`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Hr=class extends K{constructor(e,t,n,r=`section_items`,i=`section_item`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async changeToTakeOut(e){let t=await this.getOne(e);if(!t)throw Error(`Item not found`);return t.is_take_out=!t.is_take_out,this.updateOne(t.id_in_server,t)}reset(e){e.total=0,e.pax=0,e.customer={}}syncInvoiceData(e,t){e.total=t.grand_total,e.pax=t.pax,e.customer={display_name:t.customer?.display_name||``,phone_number:t.customer?.phone_number||``}}},Ur=class extends K{constructor(e,t,n,r=`products`,i=`product`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Wr=class extends K{constructor(e,t,n,r=`shifts`,i=`shift`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i,v(this,`tillService`,void 0),this.tillService=new Gr(e,t,n)}async cashIn(e,t){let n=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status===k.Open).first();if(!n)throw new D(`No opening shift found`);let r=new j;return r.amount=e,r.type=A.CashIn,r.user_uid=n.user_uid,r.shift_uid=n.uid,r.note=t,this.tillService.addOne(r)}async cashOut(e,t){let n=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status===k.Open).first();if(!n)throw new D(`No opening shift found`);let r=new j;return r.amount=e,r.type=A.CashOut,r.user_uid=n.user_uid,r.shift_uid=n.uid,r.note=t,this.tillService.addOne(r)}async closeShift(e,t){let n=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status==k.Open).first();if(!n)throw new D(`No opening shift found`);return n.declared_amount=e,n.ended_at=new Date,n.user_uid=t,n.status=k.Closed,this.updateOne(n.id_in_server,n)}async openShift(e,t,n=``){console.log(`open shift entry`);let r=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status==k.Open).first();if(r)throw new D(`shift is already opened shift at ${r.started_at}`);let i=new de;if(i.started_at=new Date,i.user_uid=t,i.status=k.Open,await this.addOne(i),e>0){let r=new j;r.amount=e,r.type=A.OpenDeposit,r.user_uid=t,r.amount=e,r.shift_uid=i.uid,r.note=n,await this.tillService.addOne(r)}return console.log(`open shift end`),i}},Gr=class extends K{constructor(e,t,n,r=`tills`,i=`till`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}createCashInvoiceTill(e,t,n,r=``,i=``){let a=new j;return a.shift_uid=t,a.user_uid=n,a.note=r,a.invoice_uid=i,a.amount=q(e.filter(e=>e.payment_method.is_cash).map(e=>e.tender_amount-e.change_amount).reduce((e,t)=>e+t,0)),a.type=A.CashInvoice,a}},Kr=class extends K{constructor(e,t,n,r=`payment_methods`,i=`payment_method`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async syncStandardPaymentMethods(){try{let{data:e}=await this.http.get(`api/v5/merchants/`+this.options.merchant_uid+`/standard_payment_methods`),t=[];for(let n of e){let e=new nt(n),r=await this.getOneByParams({payment_method_code:e.payment_method_code}),i=e.toPaymentMethod();r?(i.uid=r.uid,i.id_in_server=r.id_in_server,i.sequence=r.sequence,i.is_disabled=r.is_disabled,i.is_integrated=r.is_integrated,i.api_id=r.api_id,i.api_key=r.api_key):(i.is_disabled=!0,await this.addOne(i)),t.push(i)}return t}catch(e){return console.error(`Failed to sync standard payment methods:`,e),[]}}async enablePaymentMethod(e){return e.is_disabled=!1,this.updateOne(e.id_in_server,e)}async disablePaymentMethod(e){return e.is_disabled=!0,this.updateOne(e.id_in_server,e)}async changeSequence(e,t){let n=(await this.db.table(this.moduleName).filter(e=>!e.is_disabled).sortBy(`sequence`)).filter(t=>t.id_in_server!==e.id_in_server);t<0&&(t=0),t>n.length&&(t=n.length),n.splice(t,0,e);let r=[];for(let e=0;e<n.length;e++)n[e].sequence!==e&&(n[e].sequence=e,r.push(n[e]));return r.length>0&&await this.updateMany(r),e}},qr=class extends K{constructor(e,t,n,r=`payments`,i=`payment`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async addPayment(e,t,n){let r=new $e;r.invoice_uid=e.uid,r.tender_amount=t;let i=e.payments.reduce((e,t)=>e+t.tender_amount,0)+t;return n.is_cash&&i>=e.grand_total&&(r.change_amount=q(i-e.grand_total)),r.payment_method_uid=n.uid,r.payment_method_code=n.payment_method_code,r.payment_method_name=n.name,r.payment_method=o.cloneDeep(n),e.payments.push(r),e}async removePayment(e,t){return e.payments=e.payments.filter(e=>e.uid!==t),e}},Jr=class{async calibrateSequence(e){let t=await e.getAll();t.sort((e,t)=>e.sequence-t.sequence);let n=[];for(let e=0;e<t.length;e++){let r=t[e];r.sequence!==e&&(r.sequence=e,n.push(r))}await e.updateMany(n)}async changeSequence(e,t,n){if(n<0)throw new D(`Invalid target index.`);let r=Array.isArray(e),i=r?e:await e.getAll();if(i=i.filter(e=>e.deleted_at===null).sort((e,t)=>e.sequence-t.sequence),n>=i.length)throw new D(`Invalid target index.`);let a=i.findIndex(e=>e.uid==t.uid),o=new Map(i.map(e=>[e.uid,e.sequence]));a<n&&(n+=1),i.splice(n,0,null);let s=i.filter(e=>!(e&&e.uid===t.uid)).map((e,n)=>e===null?(t.sequence=n+1,t):(e.sequence=n+1,e)).filter(e=>o.get(e.uid)!==e.sequence);return r||await e.updateMany(s),s}},Yr=class extends K{constructor(e,t,n,r=`reports`,i=`report`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i,v(this,`invoiceService`,void 0),v(this,`tillService`,void 0),v(this,`paymentService`,void 0),v(this,`printerService`,void 0),v(this,`printTemplateService`,void 0),v(this,`printJobService`,void 0),v(this,`configService`,void 0),this.invoiceService=new Fr(e,t,n,`invoices`,`invoice`),this.tillService=new Gr(e,t,n,`tills`,`till`),this.paymentService=new qr(e,t,n,`payments`,`payment`),this.printerService=new En(e,t,n,`printers`,`printer`),this.printTemplateService=new Qr(e,t,n,`print_templates`,`print_template`),this.printJobService=new Xr(e,t,n,`print_jobs`,`print_job`),this.configService=new Br(e,t,n,`configs`,`config`)}async syncStandardReports(){let e=await this.getDefaultOne();e||(e=new _n);let t=await this.http.get(`api/v5/merchants/`+this.options.merchant_uid+`/standard_reports`);return e={...e,...t.data},e.updated_at=new Date,e.id_in_server?await this.updateOne(e.id_in_server,e):await this.addOne(e),e}async printReport(e){e.copies=e.copies||1;let t=await this.printerService.getDefaultReceiptPrinter();if(!t)throw new D(`No default receipt printer found`);let n=await this.printTemplateService.getOneByParams({report_code_name:e.report_code_name});if(!n)throw new D(`No print template found`);let r=await this.configService.getDefaultOne(),i=await this.getReportData(e,r.config?.order?.datetime_format,r.config?.currency?.currency_symbol||`$`),a=new B(t,await this.printTemplateService.renderReportPrintTemplate(i,r.config,n),!1,e.copies);await this.printJobService.addOne(a)}async getReportData(e,t,n=`$`){let r=new vn;if(e.shift_uid){await this.db.table(`shifts`).where(`uid`).equals(e.shift_uid).and(e=>e.deleted_at==null||e.deleted_at==null).first(),r.drawer_summary.declared_amount=e.declared_amount;let t=await this.db.table(`tills`).where(`shift_uid`).equals(e.shift_uid).and(e=>e.deleted_at==null).toArray();r.drawer_summary.open_amount=q(t.filter(e=>e.type==A.OpenDeposit).reduce((e,t)=>e+t.amount,0)),r.drawer_summary.pay_in_total=q(t.filter(e=>e.type==A.CashIn).reduce((e,t)=>e+t.amount,0)),r.drawer_summary.cash_invoice_total=q(t.filter(e=>e.type==A.CashInvoice).reduce((e,t)=>e+t.amount,0)),r.drawer_summary.cash_invoice_count=t.filter(e=>e.type==A.CashInvoice).length,r.drawer_summary.pay_in_count=t.filter(e=>e.type==A.CashIn).length,r.drawer_summary.pay_out_total=q(t.filter(e=>e.type==A.CashOut).reduce((e,t)=>e+t.amount,0)),r.drawer_summary.pay_out_count=t.filter(e=>e.type==A.CashOut).length,r.drawer_summary.drawer_amount=q(r.drawer_summary.open_amount+r.drawer_summary.pay_in_total+r.drawer_summary.cash_invoice_total-r.drawer_summary.pay_out_total),r.drawer_summary.difference=q(r.drawer_summary.drawer_amount-r.drawer_summary.declared_amount)}r.start_datetime=new Date(e.start_datetime).toISOString(),r.end_datetime=new Date(e.end_datetime).toISOString(),r.humanized_start_datetime=L(new Date(e.start_datetime),t),r.humanized_end_datetime=L(new Date(e.end_datetime),t),r.humanized_printed_datetime=L(new Date,t);let i=new f().addParam(`paid_at`,`GreaterThanOrEqualTo`,new Date(e.start_datetime).toISOString()).addParam(`paid_at`,`LessThanOrEqualTo`,new Date(e.end_datetime).toISOString()).addParam(`deleted_at`,`IsNull`,!0).includeTotal(!0),a=(await this.invoiceService.autoQuery(i,{timeout:6e5})).results||[];return this.processReportInvoicesData(r,a,n)}async processReportInvoicesData(e,t=[],n=`$`){let r=new Map,i=new Map,a=await this.db.table(`categories`).toArray(),o=new Map(a.map(e=>[e.uid,e])),s=new Map,c=new Map,l=new Map,u=(e,t,n)=>`${e}|${t}|${n.toFixed(4)}`,d=(e,t,r,i)=>e||(t===W.Percent?`${q(i*100)}% Discount`:`${n}${q(r)} Discount`),f=(e,t,n,r,i,a)=>{let o=u(t,n,n===W.Percent?i:r),s=e.get(o);s?(s.count++,s.total=q(s.total+a)):e.set(o,{name:t,alias:d(t,n,r,i),calc_type:n,amount:r,percent:i,count:1,total:q(a)})};t.forEach(t=>{if(t.status==U.Paid){e.sales_summary.paid_invoice_total+=t.grand_total,e.sales_summary.sales_total+=t.grand_total,e.sales_summary.paid_invoice_count++,e.sales_summary.rounding_total+=t.rounding,e.sales_summary.tax_total+=t.tax,e.sales_summary.service_charge_total+=t.service_charge,e.sales_summary.discount_total+=t.discount_amount,t.add_credit>0&&(e.loyalty_program_summary.add_credit_total+=t.add_credit,e.loyalty_program_summary.add_credit_count++,e.loyalty_program_summary.topup_paid_count++),t.rewarded_credit>0&&(e.loyalty_program_summary.rewarded_credit_total+=t.rewarded_credit,e.loyalty_program_summary.rewarded_credit_count++),t.minus_credit>0&&(e.loyalty_program_summary.minus_credit_total+=t.minus_credit,e.loyalty_program_summary.minus_credit_count++),t.rewarded_point>0&&(e.loyalty_program_summary.rewarded_point_total+=t.rewarded_point,e.loyalty_program_summary.rewarded_point_count++),t.minus_point>0&&(e.loyalty_program_summary.minus_point_total+=t.minus_point,e.loyalty_program_summary.minus_point_count++),e.sales_summary.total_pax+=t.pax,t.pax>0&&(e.sales_summary.pax_sales_total+=t.grand_total);let n=t.type||H.DineIn,a=l.get(n);a?(a.count++,a.total+=t.grand_total):l.set(n,{type:n,count:1,total:t.grand_total}),t.lines.forEach(t=>{t.item.add_credit>0&&(e.loyalty_program_summary.topup_paid_total+=t.subtotal);let n=this.generateItemKey(t),a=r.get(n);if(a?(a.quantity+=t.quantity,a.total_amount=q(a.total_amount+t.subtotal),t.modifiers&&t.modifiers.length>0&&t.modifiers.forEach(e=>{let t=e.item.name.trim(),n=i.get(t);n?(n.quantity+=e.quantity,n.total_amount=q(n.total_amount+e.price*e.quantity)):(n=new wn,n.item=e.item,n.quantity=e.quantity,n.total_amount=q(e.price*e.quantity),i.set(t,n))})):(a=new Cn,a.item=t.item,a.quantity=t.quantity,a.total_amount=q(t.subtotal),a.modifiers=[],t.modifiers&&t.modifiers.length>0&&t.modifiers.forEach(e=>{let t={item:e.item,quantity:e.quantity,total_amount:q(e.price*e.quantity)};a.modifiers.push(t);let n=e.item.name.trim(),r=i.get(n);r?(r.quantity+=e.quantity,r.total_amount=q(r.total_amount+e.price*e.quantity)):(r=new wn,r.item=e.item,r.quantity=e.quantity,r.total_amount=q(e.price*e.quantity),i.set(n,r))}),r.set(n,a)),t.discount_amount||t.discount_percent){let e=t.subtotal_before_discount-t.subtotal;e>0&&f(c,``,t.discount_calc_type,t.discount_amount,t.discount_percent,e)}}),t.payments.forEach(t=>{let n=e.payments_summary.find(e=>e.code==t.payment_method_code);t.tender_amount||(t.tender_amount=t.change_amount),n?(n.count++,n.total=q(n.total+(t.tender_amount-t.change_amount))):e.payments_summary.push({code:t.payment_method_code,name:t.payment_method_name,count:1,total:q(t.tender_amount-t.change_amount)})}),t.discounts?.forEach(e=>{let t=e.applying_item_uids&&e.applying_item_uids.length>0,n=e.calc_type===W.Percent?e.percent_amount:e.amount;f(t?c:s,e.name||``,e.calc_type,e.amount,e.percent,n)})}t.status==U.Paid&&t.is_sales_exclusive&&(e.sales_summary.foc_sales_total+=t.grand_total,e.sales_summary.foc_sales_count++,e.sales_summary.foc_rounding_total+=t.rounding,e.sales_summary.foc_tax_total+=t.tax,e.sales_summary.foc_service_charge_total+=t.service_charge),t.status==U.Void&&(e.sales_summary.void_invoice_total+=t.grand_total,e.sales_summary.void_invoice_count++)});let p=Array.from(r.values());p.sort((e,t)=>{let n=o.get(e.item.category_uid),r=o.get(t.item.category_uid),i=n?.sequence??999999,a=r?.sequence??999999;return i===a?(e.item.sequence??999999)-(t.item.sequence??999999):i-a}),e.item_sales_summary=p;let m=0,h=0,g=new Map;p.forEach(e=>{if(m+=e.total_amount,h+=e.quantity,!e.item.category_uid)return;let t=e.item.category_uid,n=g.get(t);n||(n=new Tn,n.category=o.get(e.item.category_uid)||null,g.set(t,n)),n.items.push(e),n.total_quantity+=e.quantity,n.total_amount+=e.total_amount}),e.item_sales_summary_total=q(m),e.item_sales_summary_total_count=h;let _=Array.from(g.values());_.sort((e,t)=>(e.category?.sequence??999999)-(t.category?.sequence??999999)),_.forEach(e=>{e.total_amount=q(e.total_amount),e.items.sort((e,t)=>t.total_amount===e.total_amount?t.quantity-e.quantity:t.total_amount-e.total_amount)}),e.item_sales_summary_by_category=_;let v=Array.from(i.values());v.sort((e,t)=>t.quantity===e.quantity?t.total_amount-e.total_amount:t.quantity-e.quantity),e.modifier_sales_summary=v;let y=0,b=0;return e.modifier_sales_summary.forEach(e=>{y+=e.total_amount,b+=e.quantity}),e.modifier_sales_summary_total=q(y),e.modifier_sales_summary_total_count=b,e.invoice_discount_summary=Array.from(s.values()),e.item_discount_summary=Array.from(c.values()),e.order_type_summary=Array.from(l.values()).map(e=>({...e,total:q(e.total)})),e.sales_summary.paid_invoice_total=q(e.sales_summary.paid_invoice_total),e.sales_summary.sales_total=q(e.sales_summary.sales_total),e.sales_summary.rounding_total=q(e.sales_summary.rounding_total),e.sales_summary.tax_total=q(e.sales_summary.tax_total),e.sales_summary.service_charge_total=q(e.sales_summary.service_charge_total),e.sales_summary.discount_total=q(e.sales_summary.discount_total),e.sales_summary.foc_sales_total=q(e.sales_summary.foc_sales_total),e.sales_summary.foc_rounding_total=q(e.sales_summary.foc_rounding_total),e.sales_summary.foc_tax_total=q(e.sales_summary.foc_tax_total),e.sales_summary.foc_service_charge_total=q(e.sales_summary.foc_service_charge_total),e.sales_summary.void_invoice_total=q(e.sales_summary.void_invoice_total),e.sales_summary.pax_sales_total=q(e.sales_summary.pax_sales_total),e.loyalty_program_summary.add_credit_total=q(e.loyalty_program_summary.add_credit_total),e.loyalty_program_summary.topup_paid_total=q(e.loyalty_program_summary.topup_paid_total),e.loyalty_program_summary.rewarded_credit_total=q(e.loyalty_program_summary.rewarded_credit_total),e.loyalty_program_summary.minus_credit_total=q(e.loyalty_program_summary.minus_credit_total),e}generateItemKey(e){let t=e.item.uid;if(e.modifiers&&e.modifiers.length>0){let n=[...e.modifiers].sort((e,t)=>{let n=`${e.item.name.trim()}:${e.quantity}`,r=`${t.item.name.trim()}:${t.quantity}`;return n.localeCompare(r)}).map(e=>`${e.item.uid}:${e.quantity}`);t+=`-`+n.join(`-`)}return t}},Xr=class extends K{constructor(e,t,n,r=`print_jobs`,i=`print_job`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async autoquery(e){let t=e.build();return await this.http.get(`sapi/v5/merchants/${this.options.merchant_uid}/${this.moduleName}`,{params:{...t}})}replacePrinter(e,t){return e.printer_name=t.name,e.printer_ip=t.ip_address,e.printer_type=t.type,e.printer_uid=t.uid,e.driver_printer_name=t.driver_printer_name,t.protocol&&(e.protocol=t.protocol),t.connection_type&&(e.connection_type=t.connection_type),e.usb_serial_number=t.usb_serial_number,e.use_device_name=t.use_device_name,e.usb_device_name=t.usb_device_name,t.print_sequence!==void 0&&(e.print_sequence=t.print_sequence),e}},Zr=class extends K{constructor(e,t,n,r=`menus`,i=`menu`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Qr=class extends K{constructor(e,t,n,r=`print_templates`,i=`print_template`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i,v(this,`httpClient`,void 0),v(this,`secretKey`,`tKB84ZlZRzLzA2LcglNNLquucKZwtJApRTaPKjAJHFbDd8nJRD`),this.httpClient=s.create({baseURL:`https://revopos-cdn.sgp1.digitaloceanspaces.com`,timeout:3e3})}async initialize(){if(!await this.getOneByParams({printer_type:R.ReceiptPrinter})){let e=new z;e.name=`Default Receipt Template`,e.body=await this.getPrintTemplate(`rbt`),e.header=await this.getPrintTemplate(`rht`),e.footer=await this.getPrintTemplate(`rft`),e.printer_type=R.ReceiptPrinter,await this.addOne(e),console.log(`Default Receipt Template added`)}if(!await this.getOneByParams({printer_type:R.CheckPrinter})){let e=new z;e.name=`Default Check Template`,e.body=await this.getPrintTemplate(`cbt`),e.header=await this.getPrintTemplate(`cht`),e.footer=await this.getPrintTemplate(`cft`),e.printer_type=R.CheckPrinter,await this.addOne(e),console.log(`Default Check Template added`)}if(!await this.getOneByParams({printer_type:R.OrderPrinter})){let e=new z;e.name=`Default docket Template`,e.body=await this.getPrintTemplate(`obt`),e.header=await this.getPrintTemplate(`oht`),e.footer=await this.getPrintTemplate(`oft`),e.printer_type=R.OrderPrinter,await this.addOne(e),console.log(`Default Order Template added`)}if(!await this.getOneByParams({printer_type:R.KitchenPrinter})){let e=new z;e.name=`Default Kitchen Template`,e.body=await this.getPrintTemplate(`kbt`),e.header=await this.getPrintTemplate(`kht`),e.footer=await this.getPrintTemplate(`kft`),e.printer_type=R.KitchenPrinter,await this.addOne(e),console.log(`Default Kitchen Template added`)}if(!await this.getOneByParams({printer_type:R.KioskPrinter})){let e=new z;e.name=`Default Kiosk Template`,e.body=await this.getPrintTemplate(`kioskbt`),e.header=await this.getPrintTemplate(`kioskht`),e.footer=await this.getPrintTemplate(`kioskft`),e.printer_type=R.KioskPrinter,await this.addOne(e),console.log(`Default Kiosk Template added`)}if(!await this.getOneByParams({printer_type:R.KitchenDisplayPrinter})){let e=new z;e.name=`Default Kitchen Display Template`,e.body=await this.getPrintTemplate(`kdsbt`),e.header=await this.getPrintTemplate(`kdsht`),e.footer=await this.getPrintTemplate(`kdsft`),e.printer_type=R.KitchenDisplayPrinter,await this.addOne(e),console.log(`Default Kitchen Display Template added`)}if(!await this.getOneByParams({printer_type:R.LabelPrinter})){let e=new z;e.commands=await this.getPrintTemplate(`tspl_cmds`),e.name=`Default Label Template`,e.printer_type=R.LabelPrinter,await this.addOne(e)}if(!await this.getOneByParams({printer_type:R.QrCodePrinter})){let e=new z;e.name=`Default QR Code Template`,e.body=await this.getPrintTemplate(`qrbt`),e.header=await this.getPrintTemplate(`qrht`),e.footer=await this.getPrintTemplate(`qrft`),e.printer_type=R.QrCodePrinter,await this.addOne(e)}if(!await this.getOneByParams({report_code_name:`sales_summary_report`})){let e=new z;e.name=`Sales Summary Report`,e.body=await this.getPrintTemplate(`sumbt`),e.header=await this.getPrintTemplate(`sumht`),e.footer=await this.getPrintTemplate(`sumft`),e.report_code_name=`sales_summary_report`,await this.addOne(e),console.log(`Sales Summary Report Template added`)}if(!await this.getOneByParams({report_code_name:`shift_report`})){let e=new z;e.name=`Shift Report`,e.body=await this.getPrintTemplate(`sbt`),e.header=await this.getPrintTemplate(`sht`),e.footer=await this.getPrintTemplate(`sft`),e.report_code_name=`shift_report`,await this.addOne(e),console.log(`Shift Report Template added`)}if(!await this.getOneByParams({report_code_name:`item_sales_report`})){let e=new z;e.name=`Item Sales Report`,e.body=await this.getPrintTemplate(`isrbt`),e.header=await this.getPrintTemplate(`isrht`),e.footer=await this.getPrintTemplate(`isrft`),e.report_code_name=`item_sales_report`,await this.addOne(e),console.log(`Item Sales Report Template added`)}if(!await this.getOneByParams({report_code_name:`modifier_sales_report`})){let e=new z;e.name=`Modifier Sales Report`,e.body=await this.getPrintTemplate(`msrbt`),e.header=await this.getPrintTemplate(`msrht`),e.footer=await this.getPrintTemplate(`msrft`),e.report_code_name=`modifier_sales_report`,await this.addOne(e),console.log(`Modifier Sales Report Template added`)}}async renderPrintTemplate(e,t,n,r=new V){let i=new I;n.printer_type==R.KitchenPrinter||n.printer_type==R.OrderPrinter?i.codepage=n.codepage||this.getCodepageByCountryCode(t.kitchen.language):i.codepage=n.codepage||this.getCodepageByCountryCode(t.receipt.language);let a=new Qe;return a.invoice=e,a.config=t,a.normalized_printed_at=L(a.printed_at,t?.order?.datetime_format),a.printer_name=r.printer_name,r.is_cancel&&(a.is_cancel=r.is_cancel),i.items.push(...await this.renderPrintCommand(n.header,a)),i.items.push(...await this.renderPrintCommand(n.body,a)),i.items.push(...await this.renderPrintCommand(n.footer,a)),i}async renderReportPrintTemplate(e,t,n,r=new V){let i=new I,a=new Qe;return a.report_data=e,a.config=t,a.normalized_printed_at=L(a.printed_at,t?.order?.datetime_format),i.codepage=n.codepage||P.SimplifiedChinese,i.items.push(...await this.renderPrintCommand(n.header,a)),i.items.push(...await this.renderPrintCommand(n.body,a)),i.items.push(...await this.renderPrintCommand(n.footer,a)),i}async renderPrintTemplateByData(e,t,n=new V){let r=new I;return r.items.push(...await this.renderPrintCommand(e.header,t)),r.items.push(...await this.renderPrintCommand(e.body,t)),r.items.push(...await this.renderPrintCommand(e.footer,t)),r}async getPrintTemplate(e){let t=await this.httpClient.get(`/xpos-core/${e}.enc`,{responseType:`text`});return c.AES.decrypt(t.data,this.secretKey).toString(c.enc.Utf8)}getCodepageByCountryCode(e){let t={US:P.English,GR:P.Greek,DE:P.WesternEurope,LT:P.BalticRim,PL:P.CentralEurope,RU:P.Cyrillic,TR:P.Turkish,EU:P.MultilingualLatin1WithEuro,PT:P.Portuguese,IS:P.Icelandic,IL:P.Hebrew,CA:P.FrenchCanadian,EG:P.Arabic,NO:P.Nordic,BY:P.Russian,MK:P.ModernGreek,CN:P.SimplifiedChinese,KR:P.Korean,TW:P.TraditionalChinese,FR:P.WesternEuropeanLatin,AE:P.ArabicISO,JP:P.Japanese,CZ:P.CentralEuropeanLatinWindows,BG:P.CyrillicWindows,ES:P.WesternEuropeanLatinWindows,CY:P.GreekWindows,AZ:P.TurkishWindows,PS:P.HebrewWindows,SA:P.ArabicWindows,LV:P.BalticWindows,VN:P.Vietnamese};return e&&t[e.toUpperCase()]||t.CN}async renderPrintCommand(e,t){try{let n=new l(!0),r=JSON.parse(e);console.log(`template`,JSON.stringify(r)),console.log(`templateData`,JSON.stringify(t));let i=await n.transform(r,t,!1);return i=o.flatMap(i,e=>e),i=o.compact(i),i}catch(e){throw console.error(e),e}}},$r=class extends K{constructor(e,t,n,r=`storages`,i=`storage`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},ei=class extends K{constructor(e,t,n,r=`stock_logs`,i=`stock_log`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},ti=class extends K{constructor(e,t,n,r=`appointments`,i=`appointment`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}};function ni(e,t,n){let r=s.create({baseURL:e,timeout:2e4,headers:{"x-device-uid":t,Authorization:`Bearer ${n}`}});return r.interceptors.response.use(function(e){return e.data},function(e){return Promise.reject(e)}),r}const ri=new Map([[`Item`,Rr],[`Section`,Vr],[`SectionItem`,Hr],[`Category`,zr],[`Config`,Br],[`Shift`,Wr],[`Till`,Gr],[`Employee`,Lr],[`PaymentMethod`,Kr],[`Invoice`,Fr],[`Report`,Yr],[`Printer`,En],[`PrintJob`,Xr],[`PrintTemplate`,Qr],[`EmployeeRole`,Ir],[`OrderDisplay`,Ar],[`Storage`,$r],[`Menu`,Zr],[`StockLog`,ei],[`Appointment`,ti]]),Z=`uid, updated_at, created_at, deleted_at, _timestamp, id_in_server, created_at_timestamp`,Q=`${Z}, sequence`,ii=`${Q}, status`,ai=`${Z}, till_type, shift_uid, invoice_uid`,oi=`${Q}, payment_method_code, is_disabled`,si=`${Z}, type, status, table_uid`,ci=`${Q}, name, barcode, codename`,li=`${Z}, status, printer_type, connection_type, protocol, save_only, device_uid_to_print`,ui=`${Z}, name, printer_type`,di=`${Z}, order_number, status`,fi=`${Z}, model`,pi={items:ci,sections:Q,section_items:Q,categories:Q,shifts:ii,tills:ai,employees:`${Z}, role_uid`,payment_methods:oi,invoices:si,configs:Z,reports:Z,printers:Z,print_jobs:li,print_templates:ui,employee_roles:`${Z}, name, is_default`,order_displays:di,storages:fi,menus:Z,stock_logs:`${Z}, entity_type, entity_uid, type`,appointments:`${Z}, status, scheduled_at, employee_uid, customer_id`};var $=function(e){return e.DISCONNECTED=`disconnected`,e.CONNECTED=`connected`,e.ERROR=`error`,e}($||{}),mi=class e{constructor(e,t,n=!1){this.options=e,this.win=t,v(this,`mode`,void 0),v(this,`http`,void 0),v(this,`dataSource`,void 0),v(this,`status`,$.DISCONNECTED),this.mode=e.mode,this.http=ni(e.base_url,e.device_uid,e.token),n||this.initializeDatabase(),Oe.setWindow(t)}static async init(t,n,r=!1){let i=new e(t,n,!0);return r||await i.initializeDatabase(),i}async initializeDatabase(){try{if(!this.options.database||!this.options.database.name)throw Error(`Database name is not defined`);this.dataSource=await new r(this.options.database.name),this.dataSource.version(30).stores(pi),this.status=$.CONNECTED}catch(e){this.status=$.ERROR,console.error(`Database connection error:`,e)}return this.dataSource}async dropDatabase(){await r.delete(this.options.database.name),await this.initializeDatabase()}clearTableData(e){return this.dataSource.table(e).clear()}async getService(e){if(this.status==$.ERROR)throw Error(`Database connection error`);for(;this.status==$.DISCONNECTED;)await new Promise(e=>setTimeout(e,100));try{return new e(this.http,this.dataSource,this.options)}catch(e){throw Error(`Service instantiation error: `+e?.message)}}async getServiceByName(e){if(this.status==$.ERROR)throw Error(`Database connection error`);for(;this.status==$.DISCONNECTED;)await new Promise(e=>setTimeout(e,100));try{let t=ri.get(e);if(!t)throw Error(`No service found for model: ${e}`);return new t(this.http,this.dataSource,this.options)}catch(e){throw Error(`Service instantiation error: `+e?.message)}}};async function hi(e){if(!e)return``;let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,12).toUpperCase()}const gi={v1:{headers:[`Type`,`Name`,`SKU`,`Price`,`Stock`,`Is Internal`,`Min Order`,`Max Order`,`Image URL`,`Thumbnail URL`,`Sequence`]},v2:{headers:[`Type`,`Name`,`SKU`,`Price`,`Stock`,`Is Internal`,`Min Order`,`Max Order`,`Image URL`,`Thumbnail URL`,`Sequence`,`Item UID`]},v3:{headers:[`Type`,`Name`,`SKU`,`Price`,`Stock`,`Is Internal`,`Min Order`,`Max Order`,`Image URL`,`Thumbnail URL`,`Sequence`,`Item UID`,`Print On Receipt`,`Discountable`,`Open Editor Panel`,`Is Delisted`,`Name Translations`]},v4:{headers:[`Type`,`Name`,`SKU`,`Price`,`Stock`,`Is Internal`,`Min Order`,`Max Order`,`Image URL`,`Thumbnail URL`,`Sequence`,`Item UID`,`Print On Receipt`,`Discountable`,`Open Editor Panel`,`Is Delisted`,`Name Translations`,`Prices`]},v5:{headers:[`Type`,`Name`,`SKU`,`Price`,`Stock`,`Is Internal`,`Min Order`,`Max Order`,`Image URL`,`Thumbnail URL`,`Sequence`,`Item UID`,`Print On Receipt`,`Discountable`,`Open Editor Panel`,`Is Delisted`,`Name Translations`,`Prices`,`PLU`,`Code`]}},_i=[`category`,`subcategory`,`product`,`modifier_category`,`modifier`,`combo`,`combo_group`,`combo_item`];function vi(e,t,n=`export.csv`){return bi(wi(e,t,e=>e.code||``,e=>e.plu||``))}async function yi(e,t){let n=new Map,r=new Map;for(let t of e){let e=t.code||(t.name?await hi(`${t.name}|CAT`):``);n.set(t,e),t.uid&&r.set(t.uid,e)}let i=new Map,a=new Map;for(let e of t){let t=e.price??0,n=e.plu||(e.name?await hi(`${e.name}|${t.toFixed(2)}`):``);i.set(e,n),e.uid&&a.set(e.uid,n)}return{blob:bi(wi(e,t,e=>n.get(e)||``,e=>i.get(e)||``)),productPluByUid:a,categoryCodeByUid:r}}function bi(e){let t=Ei(e);return new Blob([``+t],{type:`text/csv;charset=utf-8;`})}function xi(e){if(!(e==null||e===``)){if(typeof e==`number`&&!isNaN(e))return e;if(typeof e==`string`){let t=parseFloat(e);return isNaN(t)?void 0:t}}}function Si(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e);return t.length===0?``:t.map(([e,t])=>`${e}:${t}`).join(`|`)}function Ci(e){if(!e||!e.trim())return{};let t={};for(let n of e.split(`|`)){let e=n.indexOf(`:`);e>0&&(t[n.slice(0,e).trim()]=n.slice(e+1).trim())}return t}function wi(e,t,n,r){let i=[],a=new Map;for(let e of t)a.has(e.category_uid)||a.set(e.category_uid,[]),a.get(e.category_uid).push(e);for(let t of e){let e=n(t);i.push({type:`category`,name:t.name,sku:``,price:void 0,stock:void 0,is_internal:t.is_internal,min_order:void 0,max_order:void 0,image_url:t.image_url||``,image_thumbnail_url:t.image_thumbnail_url||``,sequence:t.sequence,is_delisted:t.is_delisted,name_translations:Si(t.name_translations),code:e});let o=a.get(t.uid)||[];if(t.has_subcategory&&t.subcategories&&t.subcategories.length>0){let e=new Map;for(let n of t.subcategories)e.set(n.uid,n);let n=new Map,a=[];for(let t of o)t.subcategory_uid&&e.has(t.subcategory_uid)?(n.has(t.subcategory_uid)||n.set(t.subcategory_uid,[]),n.get(t.subcategory_uid).push(t)):a.push(t);for(let e of a)Ti(i,e,r);for(let e of t.subcategories){i.push({type:`subcategory`,name:e.name,sku:``,sequence:e.sequence,name_translations:Si(e.name_translations)});let t=n.get(e.uid)||[];for(let e of t)Ti(i,e,r)}}else for(let e of o)Ti(i,e,r)}return i}function Ti(e,t,n){let r=t.type===N.Combo,i=n(t);if(e.push({type:r?`combo`:`product`,name:t.name,sku:t.sku||``,price:t.price,stock:xi(t.stock),is_internal:t.is_internal,min_order:void 0,max_order:void 0,image_url:t.image_url||``,image_thumbnail_url:t.image_thumbnail_url||``,sequence:t.sequence,print_on_receipt:t.print_on_receipt,discountable:t.discountable,open_editor_panel:t.open_editor_panel,is_delisted:t.is_delisted,name_translations:Si(t.name_translations),item_uid:t.uid,prices:t.prices?.length?t.prices:void 0,plu:i}),r&&t.combo_groups&&t.combo_groups.length>0){for(let n of t.combo_groups)if(e.push({type:`combo_group`,name:n.name,sku:``,price:void 0,stock:void 0,is_internal:void 0,min_order:n.min_order,max_order:n.max_order,image_url:``,image_thumbnail_url:``,sequence:n.sequence}),n.combo_items&&n.combo_items.length>0)for(let t of n.combo_items)e.push({type:`combo_item`,name:t.combo_item?.name||``,sku:``,price:t.price,stock:void 0,is_internal:void 0,min_order:void 0,max_order:void 0,image_url:``,image_thumbnail_url:``,sequence:t.sequence,item_uid:t.item_uid})}if(!r&&t.modifier_categories&&t.modifier_categories.length>0){for(let n of t.modifier_categories)if(e.push({type:`modifier_category`,name:n.name,sku:``,price:void 0,stock:void 0,is_internal:void 0,min_order:n.min_order,max_order:n.max_order,image_url:``,image_thumbnail_url:``,sequence:n.sequence}),t.modifiers&&t.modifiers.length>0){let r=t.modifiers.filter(e=>e.category_uid===n.uid);for(let t of r)e.push({type:`modifier`,name:t.name,sku:t.sku||``,price:t.price,stock:xi(t.stock),is_internal:t.is_internal,min_order:void 0,max_order:void 0,image_url:t.image_url||``,image_thumbnail_url:t.image_thumbnail_url||``,sequence:t.sequence,print_on_receipt:t.print_on_receipt,name_translations:Si(t.name_translations),prices:t.prices?.length?t.prices:void 0})}}}function Ei(e){let t=[gi.v5.headers.join(`,`)];for(let n of e)try{let e=n.prices?.length?`"${JSON.stringify(n.prices).replace(/"/g,`""`)}"`:``,r=[n.type,`"${n.name.replace(/"/g,`""`)}"`,n.sku||``,n.price===void 0?``:n.price.toString(),n.stock===void 0?``:n.stock.toString(),n.is_internal===void 0?``:n.is_internal.toString(),n.min_order===void 0?``:n.min_order.toString(),n.max_order===void 0?``:n.max_order.toString(),n.image_url||``,n.image_thumbnail_url||``,n.sequence===void 0?``:n.sequence.toString(),n.item_uid||``,n.print_on_receipt===void 0?``:n.print_on_receipt.toString(),n.discountable===void 0?``:n.discountable.toString(),n.open_editor_panel===void 0?``:n.open_editor_panel.toString(),n.is_delisted===void 0?``:n.is_delisted.toString(),n.name_translations?`"${n.name_translations.replace(/"/g,`""`)}"`:``,e,n.plu?`"${n.plu.replace(/"/g,`""`)}"`:``,n.code?`"${n.code.replace(/"/g,`""`)}"`:``];t.push(r.join(`,`))}catch(e){throw Error(`Export failed on "${n.name}" (type: ${n.type}): ${e.message}`)}return t.join(`
|
|
3
|
+
`)}async function Di(e){return Ni(ji(await e.text()))}function Oi(e){let t=Mi(e).map(e=>e.trim());return t.includes(`PLU`)||t.includes(`Code`)?`v5`:t.includes(`Prices`)?`v4`:t.includes(`Print On Receipt`)||t.includes(`Name Translations`)?`v3`:t.includes(`Item UID`)?`v2`:`v1`}function ki(e,t,n){let r=e?.trim().toLowerCase();if(r){if(r===`true`)return!0;if(r===`false`)return!1;throw Error(`Invalid ${t} "${e}" at line ${n}. Must be: true or false`)}}function Ai(e,t){if(!e)return[];try{let t=JSON.parse(e);if(!Array.isArray(t))throw Error(`not an array`);return t.map(e=>{let t=new Te;return t.lookup_keys=e.lookup_keys||[],t.amount=e.amount||0,t.name=e.name||``,t.name_translations=e.name_translations||{},t.product_uid=e.product_uid||``,t})}catch{throw Error(`Invalid Prices JSON at line ${t}`)}}function ji(e){let t=e.replace(/^\uFEFF/,``).replace(/\r\n/g,`
|
|
4
4
|
`).replace(/\r/g,`
|
|
5
5
|
`).trim().split(`
|
|
6
|
-
`);if(t.length===0)throw Error(`CSV file is empty`);let n=t[0].trim(),r=Oi(n),i=gi[r],a=i.headers.length,o=i.headers.join(`,`);if(n!==o)throw Error(`Invalid CSV header. Expected: ${o}\nReceived: ${n}`);let s=[];for(let e=1;e<t.length;e++){let n=t[e].trim();if(!n)continue;let i=Mi(n);if(i.length!==a)throw Error(`Invalid CSV row at line ${e+1}: expected ${a} columns`);let[o,c,l,u,d,f,p,m,h,g,_]=i,v=r===`v1`?``:i[11];if(!o||o!==`combo_item`&&!c.trim())throw Error(`Missing required fields at line ${e+1}`);if(!_i.includes(o))throw Error(`Invalid type "${o}" at line ${e+1}. Must be: ${_i.join(`, `)}`);let y;if(u&&u.trim()&&(y=parseFloat(u),isNaN(y)))throw Error(`Invalid price "${u}" at line ${e+1}`);let b;if(d&&d.trim()&&(b=parseFloat(d),isNaN(b)))throw Error(`Invalid stock "${d}" at line ${e+1}`);let x=ki(f,`is_internal`,e+1),S;if(p&&p.trim()&&(S=parseInt(p,10),isNaN(S)))throw Error(`Invalid min_order "${p}" at line ${e+1}`);let C;if(m&&m.trim()&&(C=parseInt(m,10),isNaN(C)))throw Error(`Invalid max_order "${m}" at line ${e+1}`);let ee;if(_&&_.trim()&&(ee=parseInt(_,10),isNaN(ee)))throw Error(`Invalid sequence "${_}" at line ${e+1}`);let te,ne,re,ie,w=``,T,ae=``,E=``;(r===`v3`||r===`v4`||r===`v5`)&&(te=ki(i[12],`print_on_receipt`,e+1),ne=ki(i[13],`discountable`,e+1),re=ki(i[14],`open_editor_panel`,e+1),ie=ki(i[15],`is_delisted`,e+1),w=i[16]?.trim()||``),(r===`v4`||r===`v5`)&&i[17]?.trim()&&(T=Ai(i[17],e+1)),r===`v5`&&(ae=i[18]?.trim()||``,E=i[19]?.trim()||``),s.push({type:o,name:c.trim(),sku:l?.trim()||``,price:y,stock:b,is_internal:x,min_order:S,max_order:C,image_url:h?.trim()||``,image_thumbnail_url:g?.trim()||``,sequence:ee,item_uid:v?.trim()||``,print_on_receipt:te,discountable:ne,open_editor_panel:re,is_delisted:ie,name_translations:w,prices:T,plu:ae,code:E})}return s}function Mi(e){let t=[],n=``,r=!1;for(let i=0;i<e.length;i++){let a=e[i];a===`"`?r&&e[i+1]===`"`?(n+=`"`,i++):r=!r:a===`,`&&!r?(t.push(n),n=``):n+=a}return t.push(n),t}function Ni(e){let n=[],r=[],i=[],a=null,o=null,s=null,c=null,l=null,u=0,d=new Map;for(let n of e)(n.type===`product`||n.type===`combo`)&&n.item_uid&&d.set(n.item_uid,E.Item+t());for(let t of e)if(t.type===`category`)a=new be,a.name=t.name,a.is_internal=t.is_internal===void 0?!1:t.is_internal,a.sequence=t.sequence===void 0?u++:t.sequence,a.image_url=t.image_url||``,a.image_thumbnail_url=t.image_thumbnail_url||``,a.visibility=[],a.is_delisted=t.is_delisted===void 0?!1:t.is_delisted,t.name_translations&&(a.name_translations=Ci(t.name_translations)),t.code&&(a.code=t.code),n.push(a),s=null,c=null,l=null,o=null;else if(t.type===`subcategory`){if(!a)throw Error(`Subcategory "${t.name}" found without a category`);o=new xe,o.name=t.name,o.sequence=t.sequence||0,o.category_uid=a.uid,t.name_translations&&(o.name_translations=Ci(t.name_translations)),a.has_subcategory=!0,a.subcategories.push(o),s=null,c=null,l=null}else if(t.type===`product`||t.type===`combo`){if(!a)throw Error(`${t.type===`combo`?`Combo`:`Product`} "${t.name}" found without a category`);if(s=new Ce,s.uid=t.item_uid&&d.get(t.item_uid)||s.uid,s.name=t.name,s.sku=t.sku||``,s.price=t.price||0,s.stock=t.stock===void 0?1e3:t.stock,s.is_internal=t.is_internal===void 0?!1:t.is_internal,s.sequence=t.sequence||0,s.image_url=t.image_url||``,s.image_thumbnail_url=t.image_thumbnail_url||``,s.category_uid=a.uid,s.type=t.type===`combo`?P.Combo:P.ByQuantity,s.modifier_categories=[],s.modifiers=[],s.combo_groups=[],t.print_on_receipt!==void 0&&(s.print_on_receipt=t.print_on_receipt),t.discountable!==void 0&&(s.discountable=t.discountable),t.open_editor_panel!==void 0&&(s.open_editor_panel=t.open_editor_panel),t.is_delisted!==void 0&&(s.is_delisted=t.is_delisted),t.name_translations&&(s.name_translations=Ci(t.name_translations)),t.prices?.length){for(let e of t.prices)e.product_uid=s.uid;s.prices=t.prices}t.plu&&(s.plu=t.plu),o&&(s.subcategory_uid=o.uid),r.push(s),c=null,l=null}else if(t.type===`combo_group`){if(!s||s.type!==P.Combo)throw Error(`Combo group "${t.name}" found without a combo product`);l=new Ee,l.name=t.name,l.min_order=t.min_order===void 0?1:t.min_order,l.max_order=t.max_order===void 0?1:t.max_order,l.sequence=t.sequence===void 0?s.combo_groups.length:t.sequence,s.combo_groups.push(l)}else if(t.type===`combo_item`){if(!l)throw Error(`Combo item "${t.name}" found without a combo group`);let e=d.get(t.item_uid||``);if(t.item_uid&&!e)i.push({combo:s?.name||``,group:l.name,item:t.name,uid:t.item_uid});else{let n=new Te;n.item_uid=e||t.item_uid||``,n.price=t.price||0,n.sequence=t.sequence||0,n.combo_item=new Ce,n.combo_item.name=t.name,l.combo_items.push(n)}}else if(t.type===`modifier_category`){if(!s)throw Error(`Modifier category "${t.name}" found without a product`);c=new ye,c.name=t.name,c.min_order=t.min_order===void 0?0:t.min_order,c.max_order=t.max_order===void 0?0:t.max_order,c.sequence=t.sequence===void 0?s.modifier_categories.length:t.sequence,c.visibility=[],s.modifier_categories.push(c)}else if(t.type===`modifier`){if(!s)throw Error(`Modifier "${t.name}" found without a product`);let e=new Se;if(e.name=t.name,e.sku=t.sku||``,e.price=t.price||0,e.stock=t.stock===void 0?0:t.stock,e.is_internal=t.is_internal===void 0?!1:t.is_internal,e.sequence=t.sequence||0,e.image_url=t.image_url||``,e.image_thumbnail_url=t.image_thumbnail_url||``,e.type=P.Modifier,e.category_uid=c?c.uid:s.category_uid,t.print_on_receipt!==void 0&&(e.print_on_receipt=t.print_on_receipt),t.name_translations&&(e.name_translations=Ci(t.name_translations)),t.prices?.length){for(let n of t.prices)n.product_uid=e.uid;e.prices=t.prices}s.modifiers.push(e)}return{categories:n,products:r,discardedComboItems:i}}let Pi=function(e){return e.None=``,e.Always=`always`,e}({}),Fi=function(e){return e.Image=`image`,e.Video=`video`,e.Unsupported=`unsupported`,e}({}),Ii=function(e){return e.CdsFullScreenImage=`cds_full_screen_image`,e.CdsHalfScreenImage=`cds_half_screen_image`,e}({});var Li=class{constructor(){v(this,`name`,void 0),v(this,`address`,void 0),v(this,`postcode`,void 0),v(this,`tel`,void 0),v(this,`tax_number`,void 0),v(this,`user_id`,void 0),v(this,`uid`,void 0),v(this,`api_key`,void 0),v(this,`ip_address`,void 0),v(this,`meta`,void 0)}},Ri=class extends T{constructor(...e){super(...e),v(this,`uid`,E.Storage+t()),v(this,`model`,void 0),v(this,`data`,void 0)}},zi=class extends T{constructor(...e){super(...e),v(this,`uid`,E.Menu+t()),v(this,`icon`,``),v(this,`meta`,{}),v(this,`category_uids`,[]),v(this,`online_order_expiry_in_minutes`,0),v(this,`online_order_session_expiry_in_minutes`,0)}};let Bi=function(e){return e.In=`IN`,e.Out=`OUT`,e.Adjust=`ADJUST`,e.Production=`PRODUCTION`,e}({}),Vi=function(e){return e.Invoice=`invoice`,e.Purchase=`purchase`,e.Production=`production`,e.Stocktake=`stocktake`,e}({}),Hi=function(e){return e.Item=`item`,e.Material=`material`,e}({});var Ui=class extends w{constructor(){super(),v(this,`entity_type`,Hi.Item),v(this,`entity_uid`,``),v(this,`type`,Bi.Adjust),v(this,`qty`,0),v(this,`qty_before`,0),v(this,`qty_after`,0),v(this,`ref_type`,void 0),v(this,`ref_uid`,void 0),v(this,`reason`,void 0),v(this,`created_by`,void 0),v(this,`uid`,E.StockLog+t())}};let Wi=function(e){return e.Pending=`pending`,e.Confirmed=`confirmed`,e.CheckedIn=`checked_in`,e.InService=`in_service`,e.Completed=`completed`,e.Cancelled=`cancelled`,e.NoShow=`no_show`,e}({}),Gi=function(e){return e.Pos=`pos`,e.Online=`online`,e.Phone=`phone`,e}({});var Ki=class{constructor(){v(this,`uid`,E.AppointmentServiceLine+t()),v(this,`name`,``),v(this,`duration_in_minutes`,0),v(this,`price`,0),v(this,`quantity`,1),v(this,`is_custom`,!1)}},qi=class extends w{constructor(){super(),v(this,`uid`,E.Appointment+t()),v(this,`appointment_no`,``),v(this,`status`,Wi.Confirmed),v(this,`source`,Gi.Pos),v(this,`customer_id`,0),v(this,`scheduled_at`,new Date),v(this,`duration_in_minutes`,60),v(this,`services`,[]),v(this,`meta`,{})}};const Ji=[`#each`,`#if`,`#elseif`,`#else`,`#let`,`#merge`,`#concat`,`#include`,`#?`,`#flatten`];function Yi(e){let t=[],n=(e,n,r,i)=>t.push({type:e,path:n,message:r,context:i}),r;try{r=JSON.parse(e)}catch(t){let n=t.message.match(/position (\d+)/)?.[1];return{valid:!1,errors:[{type:`JSON_PARSE`,path:null,message:t.message,context:n?e.slice(Math.max(0,n-20),+n+20):void 0}]}}let i=JSON.stringify(r),a=i.match(/"[^"]*"/g)||[],o=0,s=0;return a.forEach(e=>{o+=(e.match(/\{\{/g)||[]).length,s+=(e.match(/\}\}/g)||[]).length}),o!==s&&n(`BRACKET_MISMATCH`,null,`{{ : ${o}, }} : ${s}`),(i.match(/\{\{([^}]+)\}\}/g)||[]).forEach(e=>{let t=e.slice(2,-2).trim();if(t.startsWith(`#`)){let r=t.split(/\s/)[0];Ji.includes(r)||n(`UNKNOWN_DIRECTIVE`,null,r,e);return}try{Function(`with(this){return(${t})}`)}catch(t){n(`INVALID_EXPRESSION`,null,t.message,e)}}),(function e(t,r){if(!(!t||typeof t!=`object`)){if(Array.isArray(t)){let i=t[0]&&Object.keys(t[0])[0];i?.includes(`#if`)&&!i.includes(`#elseif`)&&Xi(t,r,n),t.forEach((t,n)=>e(t,`${r}[${n}]`));return}for(let i in t){let a=t[i];i.includes(`#each`)&&typeof a!=`object`&&n(`INVALID_EACH`,r,`value must be object`,i),i.includes(`#let`)&&(!Array.isArray(a)||a.length!==2)&&n(`INVALID_LET`,r,`must be [definitions, template]`,i),(i.includes(`#merge`)||i.includes(`#concat`))&&!Array.isArray(a)&&n(`INVALID_STRUCTURE`,r,`value must be array`,i),e(a,r?`${r}.${i}`:i)}}})(r,``),{valid:!t.length,errors:t}}function Xi(e,t,n){let r=e=>Object.keys(e)[0]||``;r(e[0]).match(/#if\s/)||n(`INVALID_CONDITIONAL`,t,`must start with #if`,r(e[0]));for(let i=1;i<e.length-1;i++)r(e[i]).includes(`#elseif`)||n(`INVALID_CONDITIONAL`,`${t}[${i}]`,`middle must be #elseif`,r(e[i]));e.length>1&&!r(e.at(-1)).includes(`#else`)&&n(`INVALID_CONDITIONAL`,`${t}[${e.length-1}]`,`last must be #else/#elseif`,r(e.at(-1)))}export{y as Address,kt as AlipayMethod,T as AppBaseModel,xt as AppConfig,w as AppCoreModel,fn as AppCoreService,ae as AppExtraModel,pn as AppLocalService,Jr as AppMiscService,K as AppRemoteService,_n as AppReport,Yr as AppReportService,ee as Applying,qi as Appointment,ti as AppointmentService,Ki as AppointmentServiceLine,Gi as AppointmentSource,Wi as AppointmentStatus,Ii as AssetTags,Fi as AssetType,cn as Between,St as Cache,G as CalcFlow,W as CalcType,Dt as CardPaymentCode,nn as CashDrawerConfig,be as Category,Tn as CategorySalesSummary,zr as CategoryService,ve as CategoryType,ht as Charge,Xt as ChargeConfig,F as Codepages,Ee as ComboGroup,Te as ComboGroupItem,Pi as Condition,Mt as Config,Br as ConfigService,ye as CoreCategory,Se as CoreItem,te as Coupon,re as CouponItemized,ne as CouponUsage,Ct as CrmConfig,Zt as CurrencyConfig,x as Customer,Et as CustomerDisplaySystemConfig,Ft as DeployChannel,Ve as Device,Ue as DeviceType,ft as DiscountType,bn as DrawerSummary,De as ElectronSocket,bt as Employee,me as EmployeeRole,Ir as EmployeeRoleService,Lr as EmployeeService,O as ErrorMsgs,ze as EscPosCompatibility,Me as EscPosPrinter,rn as FileUploadRequest,tn as GTOConfig,Rt as GeneralConfig,sn as In,on as Include,$t as InventoryConfig,yt as Invoice,ut as InvoiceAction,mt as InvoiceActivity,Mr as InvoiceBaseService,pt as InvoiceCharge,_t as InvoiceCoreLine,gt as InvoiceDiscount,vt as InvoiceLine,Pr as InvoiceOperationService,Fr as InvoiceService,U as InvoiceStatus,st as InvoiceType,Ce as Item,Cn as ItemSalesSummary,Rr as ItemService,Ut as KdsConfig,At as KioskSystemConfig,Ht as KitchenConfig,Wt as LabelConfig,Nr as LineOperationService,Tt as LoyaltyProgram,Sn as LoyaltyProgramSummary,jt as MarketingConfig,zi as Menu,Zr as MenuService,Li as Merchant,le as MessageType,E as ModelPrefix,oe as ModelType,wn as ModifierSalesSummary,He as Node,We as NodePrinter,ln as Not,ot as Note,at as NoteEntity,it as NoteGroup,rt as NoteGroupEntity,Pt as OnlineOrderConfig,Gt as OrderConfig,kr as OrderDisplay,Ar as OrderDisplayService,X as OrderDisplayStatus,Kt as OrderDisplaySystemConfig,ct as OrderFlow,en as PaxConfig,Qe as Payment,qt as PaymentConfig,$e as PaymentMethod,et as PaymentMethodHistory,Kr as PaymentMethodService,qr as PaymentService,nt as PaymentStatus,xn as PaymentSummary,Nt as PaynowMethod,we as Price,Ne as PrintAlign,Ie as PrintBarcode,L as PrintCommand,Re as PrintImage,V as PrintJob,Xr as PrintJobService,Je as PrintJobStatus,Le as PrintQrcode,Fe as PrintSize,Pe as PrintStyle,B as PrintTemplate,qe as PrintTemplateCore,Qr as PrintTemplateService,I as PrintType,Xe as Printer,Ke as PrinterConnections,Ge as PrinterProtocols,En as PrinterService,Ye as PrinterStatus,z as PrinterType,N as ProductBase,Lt as ProductConfig,Ur as ProductService,P as ProductType,ue as PushData,un as Raw,Vt as Receipt,H as RenderPrintTemplateOptions,gn as Report,hn as ReportCategory,Bt as ReportConfig,vn as ReportData,mn as ReportType,Qt as RoundingConfig,yn as SalesSummary,pe as Section,fe as SectionItem,Hr as SectionItemService,M as SectionItemStatus,Vr as SectionService,mi as ServiceFactory,se as ServiceMode,ce as ServiceOptions,de as Shift,Wr as ShiftService,k as ShiftStatus,tt as StandardPaymentMethod,he as StockChange,Ui as StockLog,Hi as StockLogEntityType,Vi as StockLogRefType,ei as StockLogService,Bi as StockLogType,Ri as Storage,$r as StorageService,xe as Subcategory,_e as System,wt as SystemConfig,D as SystemError,Yt as TaxConfig,lt as TaxMethod,Ze as TemplateData,j as Till,zt as TillConfig,Gr as TillService,A as TillType,dt as UomType,b as User,Jt as UserConfig,ge as Visibility,Ot as WechatPayMethod,vi as createCSVExport,yi as createCSVExportWithHash,pi as dbSchemas,dn as filterByParams,It as getCategoryButtonShape,R as humanizedData,Di as importFromCSV,Be as normalizedDate,ie as transformer,Yi as validateSTTemplate};
|
|
6
|
+
`);if(t.length===0)throw Error(`CSV file is empty`);let n=t[0].trim(),r=Oi(n),i=gi[r],a=i.headers.length,o=i.headers.join(`,`);if(n!==o)throw Error(`Invalid CSV header. Expected: ${o}\nReceived: ${n}`);let s=[];for(let e=1;e<t.length;e++){let n=t[e].trim();if(!n)continue;let i=Mi(n);if(i.length!==a)throw Error(`Invalid CSV row at line ${e+1}: expected ${a} columns`);let[o,c,l,u,d,f,p,m,h,g,_]=i,v=r===`v1`?``:i[11];if(!o||o!==`combo_item`&&!c.trim())throw Error(`Missing required fields at line ${e+1}`);if(!_i.includes(o))throw Error(`Invalid type "${o}" at line ${e+1}. Must be: ${_i.join(`, `)}`);let y;if(u&&u.trim()&&(y=parseFloat(u),isNaN(y)))throw Error(`Invalid price "${u}" at line ${e+1}`);let b;if(d&&d.trim()&&(b=parseFloat(d),isNaN(b)))throw Error(`Invalid stock "${d}" at line ${e+1}`);let x=ki(f,`is_internal`,e+1),S;if(p&&p.trim()&&(S=parseInt(p,10),isNaN(S)))throw Error(`Invalid min_order "${p}" at line ${e+1}`);let C;if(m&&m.trim()&&(C=parseInt(m,10),isNaN(C)))throw Error(`Invalid max_order "${m}" at line ${e+1}`);let ee;if(_&&_.trim()&&(ee=parseInt(_,10),isNaN(ee)))throw Error(`Invalid sequence "${_}" at line ${e+1}`);let te,ne,re,ie,w=``,T,ae=``,E=``;(r===`v3`||r===`v4`||r===`v5`)&&(te=ki(i[12],`print_on_receipt`,e+1),ne=ki(i[13],`discountable`,e+1),re=ki(i[14],`open_editor_panel`,e+1),ie=ki(i[15],`is_delisted`,e+1),w=i[16]?.trim()||``),(r===`v4`||r===`v5`)&&i[17]?.trim()&&(T=Ai(i[17],e+1)),r===`v5`&&(ae=i[18]?.trim()||``,E=i[19]?.trim()||``),s.push({type:o,name:c.trim(),sku:l?.trim()||``,price:y,stock:b,is_internal:x,min_order:S,max_order:C,image_url:h?.trim()||``,image_thumbnail_url:g?.trim()||``,sequence:ee,item_uid:v?.trim()||``,print_on_receipt:te,discountable:ne,open_editor_panel:re,is_delisted:ie,name_translations:w,prices:T,plu:ae,code:E})}return s}function Mi(e){let t=[],n=``,r=!1;for(let i=0;i<e.length;i++){let a=e[i];a===`"`?r&&e[i+1]===`"`?(n+=`"`,i++):r=!r:a===`,`&&!r?(t.push(n),n=``):n+=a}return t.push(n),t}function Ni(e){let n=[],r=[],i=[],a=null,o=null,s=null,c=null,l=null,u=0,d=new Map;for(let n of e)(n.type===`product`||n.type===`combo`)&&n.item_uid&&d.set(n.item_uid,E.Item+t());for(let t of e)if(t.type===`category`)a=new xe,a.name=t.name,a.is_internal=t.is_internal===void 0?!1:t.is_internal,a.sequence=t.sequence===void 0?u++:t.sequence,a.image_url=t.image_url||``,a.image_thumbnail_url=t.image_thumbnail_url||``,a.visibility=[],a.is_delisted=t.is_delisted===void 0?!1:t.is_delisted,t.name_translations&&(a.name_translations=Ci(t.name_translations)),t.code&&(a.code=t.code),n.push(a),s=null,c=null,l=null,o=null;else if(t.type===`subcategory`){if(!a)throw Error(`Subcategory "${t.name}" found without a category`);o=new Se,o.name=t.name,o.sequence=t.sequence||0,o.category_uid=a.uid,t.name_translations&&(o.name_translations=Ci(t.name_translations)),a.has_subcategory=!0,a.subcategories.push(o),s=null,c=null,l=null}else if(t.type===`product`||t.type===`combo`){if(!a)throw Error(`${t.type===`combo`?`Combo`:`Product`} "${t.name}" found without a category`);if(s=new we,s.uid=t.item_uid&&d.get(t.item_uid)||s.uid,s.name=t.name,s.sku=t.sku||``,s.price=t.price||0,s.stock=t.stock===void 0?1e3:t.stock,s.is_internal=t.is_internal===void 0?!1:t.is_internal,s.sequence=t.sequence||0,s.image_url=t.image_url||``,s.image_thumbnail_url=t.image_thumbnail_url||``,s.category_uid=a.uid,s.type=t.type===`combo`?N.Combo:N.ByQuantity,s.modifier_categories=[],s.modifiers=[],s.combo_groups=[],t.print_on_receipt!==void 0&&(s.print_on_receipt=t.print_on_receipt),t.discountable!==void 0&&(s.discountable=t.discountable),t.open_editor_panel!==void 0&&(s.open_editor_panel=t.open_editor_panel),t.is_delisted!==void 0&&(s.is_delisted=t.is_delisted),t.name_translations&&(s.name_translations=Ci(t.name_translations)),t.prices?.length){for(let e of t.prices)e.product_uid=s.uid;s.prices=t.prices}t.plu&&(s.plu=t.plu),o&&(s.subcategory_uid=o.uid),r.push(s),c=null,l=null}else if(t.type===`combo_group`){if(!s||s.type!==N.Combo)throw Error(`Combo group "${t.name}" found without a combo product`);l=new De,l.name=t.name,l.min_order=t.min_order===void 0?1:t.min_order,l.max_order=t.max_order===void 0?1:t.max_order,l.sequence=t.sequence===void 0?s.combo_groups.length:t.sequence,s.combo_groups.push(l)}else if(t.type===`combo_item`){if(!l)throw Error(`Combo item "${t.name}" found without a combo group`);let e=d.get(t.item_uid||``);if(t.item_uid&&!e)i.push({combo:s?.name||``,group:l.name,item:t.name,uid:t.item_uid});else{let n=new Ee;n.item_uid=e||t.item_uid||``,n.price=t.price||0,n.sequence=t.sequence||0,n.combo_item=new we,n.combo_item.name=t.name,l.combo_items.push(n)}}else if(t.type===`modifier_category`){if(!s)throw Error(`Modifier category "${t.name}" found without a product`);c=new be,c.name=t.name,c.min_order=t.min_order===void 0?0:t.min_order,c.max_order=t.max_order===void 0?0:t.max_order,c.sequence=t.sequence===void 0?s.modifier_categories.length:t.sequence,c.visibility=[],s.modifier_categories.push(c)}else if(t.type===`modifier`){if(!s)throw Error(`Modifier "${t.name}" found without a product`);let e=new Ce;if(e.name=t.name,e.sku=t.sku||``,e.price=t.price||0,e.stock=t.stock===void 0?0:t.stock,e.is_internal=t.is_internal===void 0?!1:t.is_internal,e.sequence=t.sequence||0,e.image_url=t.image_url||``,e.image_thumbnail_url=t.image_thumbnail_url||``,e.type=N.Modifier,e.category_uid=c?c.uid:s.category_uid,t.print_on_receipt!==void 0&&(e.print_on_receipt=t.print_on_receipt),t.name_translations&&(e.name_translations=Ci(t.name_translations)),t.prices?.length){for(let n of t.prices)n.product_uid=e.uid;e.prices=t.prices}s.modifiers.push(e)}return{categories:n,products:r,discardedComboItems:i}}let Pi=function(e){return e.None=``,e.Always=`always`,e}({}),Fi=function(e){return e.Image=`image`,e.Video=`video`,e.Unsupported=`unsupported`,e}({}),Ii=function(e){return e.CdsFullScreenImage=`cds_full_screen_image`,e.CdsHalfScreenImage=`cds_half_screen_image`,e}({});var Li=class{constructor(){v(this,`name`,void 0),v(this,`address`,void 0),v(this,`postcode`,void 0),v(this,`tel`,void 0),v(this,`tax_number`,void 0),v(this,`user_id`,void 0),v(this,`uid`,void 0),v(this,`api_key`,void 0),v(this,`ip_address`,void 0),v(this,`meta`,void 0)}},Ri=class extends T{constructor(...e){super(...e),v(this,`uid`,E.Storage+t()),v(this,`model`,void 0),v(this,`data`,void 0)}},zi=class extends T{constructor(...e){super(...e),v(this,`uid`,E.Menu+t()),v(this,`icon`,``),v(this,`meta`,{}),v(this,`category_uids`,[]),v(this,`online_order_expiry_in_minutes`,0),v(this,`online_order_session_expiry_in_minutes`,0)}};let Bi=function(e){return e.In=`IN`,e.Out=`OUT`,e.Adjust=`ADJUST`,e.Production=`PRODUCTION`,e}({}),Vi=function(e){return e.Invoice=`invoice`,e.Purchase=`purchase`,e.Production=`production`,e.Stocktake=`stocktake`,e}({}),Hi=function(e){return e.Item=`item`,e.Material=`material`,e}({});var Ui=class extends w{constructor(){super(),v(this,`entity_type`,Hi.Item),v(this,`entity_uid`,``),v(this,`type`,Bi.Adjust),v(this,`qty`,0),v(this,`qty_before`,0),v(this,`qty_after`,0),v(this,`ref_type`,void 0),v(this,`ref_uid`,void 0),v(this,`reason`,void 0),v(this,`created_by`,void 0),v(this,`uid`,E.StockLog+t())}};let Wi=function(e){return e.Pending=`pending`,e.Confirmed=`confirmed`,e.CheckedIn=`checked_in`,e.InService=`in_service`,e.Completed=`completed`,e.Cancelled=`cancelled`,e.NoShow=`no_show`,e}({}),Gi=function(e){return e.Pos=`pos`,e.Online=`online`,e.Phone=`phone`,e}({});var Ki=class{constructor(){v(this,`uid`,E.AppointmentServiceLine+t()),v(this,`name`,``),v(this,`duration_in_minutes`,0),v(this,`price`,0),v(this,`quantity`,1),v(this,`is_custom`,!1)}},qi=class extends w{constructor(){super(),v(this,`uid`,E.Appointment+t()),v(this,`appointment_no`,``),v(this,`status`,Wi.Confirmed),v(this,`source`,Gi.Pos),v(this,`customer_id`,0),v(this,`scheduled_at`,new Date),v(this,`duration_in_minutes`,60),v(this,`services`,[]),v(this,`meta`,{})}};const Ji=[`#each`,`#if`,`#elseif`,`#else`,`#let`,`#merge`,`#concat`,`#include`,`#?`,`#flatten`];function Yi(e){let t=[],n=(e,n,r,i)=>t.push({type:e,path:n,message:r,context:i}),r;try{r=JSON.parse(e)}catch(t){let n=t.message.match(/position (\d+)/)?.[1];return{valid:!1,errors:[{type:`JSON_PARSE`,path:null,message:t.message,context:n?e.slice(Math.max(0,n-20),+n+20):void 0}]}}let i=JSON.stringify(r),a=i.match(/"[^"]*"/g)||[],o=0,s=0;return a.forEach(e=>{o+=(e.match(/\{\{/g)||[]).length,s+=(e.match(/\}\}/g)||[]).length}),o!==s&&n(`BRACKET_MISMATCH`,null,`{{ : ${o}, }} : ${s}`),(i.match(/\{\{([^}]+)\}\}/g)||[]).forEach(e=>{let t=e.slice(2,-2).trim();if(t.startsWith(`#`)){let r=t.split(/\s/)[0];Ji.includes(r)||n(`UNKNOWN_DIRECTIVE`,null,r,e);return}try{Function(`with(this){return(${t})}`)}catch(t){n(`INVALID_EXPRESSION`,null,t.message,e)}}),(function e(t,r){if(!(!t||typeof t!=`object`)){if(Array.isArray(t)){let i=t[0]&&Object.keys(t[0])[0];i?.includes(`#if`)&&!i.includes(`#elseif`)&&Xi(t,r,n),t.forEach((t,n)=>e(t,`${r}[${n}]`));return}for(let i in t){let a=t[i];i.includes(`#each`)&&typeof a!=`object`&&n(`INVALID_EACH`,r,`value must be object`,i),i.includes(`#let`)&&(!Array.isArray(a)||a.length!==2)&&n(`INVALID_LET`,r,`must be [definitions, template]`,i),(i.includes(`#merge`)||i.includes(`#concat`))&&!Array.isArray(a)&&n(`INVALID_STRUCTURE`,r,`value must be array`,i),e(a,r?`${r}.${i}`:i)}}})(r,``),{valid:!t.length,errors:t}}function Xi(e,t,n){let r=e=>Object.keys(e)[0]||``;r(e[0]).match(/#if\s/)||n(`INVALID_CONDITIONAL`,t,`must start with #if`,r(e[0]));for(let i=1;i<e.length-1;i++)r(e[i]).includes(`#elseif`)||n(`INVALID_CONDITIONAL`,`${t}[${i}]`,`middle must be #elseif`,r(e[i]));e.length>1&&!r(e.at(-1)).includes(`#else`)&&n(`INVALID_CONDITIONAL`,`${t}[${e.length-1}]`,`last must be #else/#elseif`,r(e.at(-1)))}export{y as Address,kt as AlipayMethod,T as AppBaseModel,xt as AppConfig,w as AppCoreModel,fn as AppCoreService,ae as AppExtraModel,pn as AppLocalService,Jr as AppMiscService,K as AppRemoteService,_n as AppReport,Yr as AppReportService,ee as Applying,qi as Appointment,ti as AppointmentService,Ki as AppointmentServiceLine,Gi as AppointmentSource,Wi as AppointmentStatus,Ii as AssetTags,Fi as AssetType,cn as Between,St as Cache,G as CalcFlow,W as CalcType,Dt as CardPaymentCode,nn as CashDrawerConfig,xe as Category,Tn as CategorySalesSummary,zr as CategoryService,ye as CategoryType,ht as Charge,Xt as ChargeConfig,P as Codepages,De as ComboGroup,Ee as ComboGroupItem,Pi as Condition,Mt as Config,Br as ConfigService,be as CoreCategory,Ce as CoreItem,te as Coupon,re as CouponItemized,ne as CouponUsage,Ct as CrmConfig,Zt as CurrencyConfig,x as Customer,Et as CustomerDisplaySystemConfig,Ft as DeployChannel,He as Device,We as DeviceType,ft as DiscountType,bn as DrawerSummary,Oe as ElectronSocket,bt as Employee,me as EmployeeRole,Ir as EmployeeRoleService,Lr as EmployeeService,O as ErrorMsgs,Be as EscPosCompatibility,Ne as EscPosPrinter,rn as FileUploadRequest,tn as GTOConfig,Rt as GeneralConfig,sn as In,on as Include,$t as InventoryConfig,yt as Invoice,ut as InvoiceAction,mt as InvoiceActivity,Mr as InvoiceBaseService,pt as InvoiceCharge,_t as InvoiceCoreLine,gt as InvoiceDiscount,vt as InvoiceLine,Pr as InvoiceOperationService,Fr as InvoiceService,U as InvoiceStatus,H as InvoiceType,we as Item,Cn as ItemSalesSummary,Rr as ItemService,Ut as KdsConfig,At as KioskSystemConfig,Ht as KitchenConfig,Wt as LabelConfig,Nr as LineOperationService,Tt as LoyaltyProgram,Sn as LoyaltyProgramSummary,jt as MarketingConfig,zi as Menu,Zr as MenuService,Li as Merchant,le as MessageType,E as ModelPrefix,oe as ModelType,wn as ModifierSalesSummary,Ue as Node,Ge as NodePrinter,ln as Not,st as Note,ot as NoteEntity,at as NoteGroup,it as NoteGroupEntity,Pt as OnlineOrderConfig,Gt as OrderConfig,kr as OrderDisplay,Ar as OrderDisplayService,X as OrderDisplayStatus,Kt as OrderDisplaySystemConfig,ct as OrderFlow,en as PaxConfig,$e as Payment,qt as PaymentConfig,et as PaymentMethod,tt as PaymentMethodHistory,Kr as PaymentMethodService,qr as PaymentService,rt as PaymentStatus,xn as PaymentSummary,Nt as PaynowMethod,Te as Price,Pe as PrintAlign,Le as PrintBarcode,I as PrintCommand,ze as PrintImage,B as PrintJob,Xr as PrintJobService,Ye as PrintJobStatus,Re as PrintQrcode,Ie as PrintSize,Fe as PrintStyle,z as PrintTemplate,Je as PrintTemplateCore,Qr as PrintTemplateService,F as PrintType,Ze as Printer,qe as PrinterConnections,Ke as PrinterProtocols,En as PrinterService,Xe as PrinterStatus,R as PrinterType,ge as ProductBase,Lt as ProductConfig,Ur as ProductService,N as ProductType,ue as PushData,un as Raw,Vt as Receipt,V as RenderPrintTemplateOptions,gn as Report,hn as ReportCategory,Bt as ReportConfig,vn as ReportData,mn as ReportType,Qt as RoundingConfig,yn as SalesSummary,pe as Section,fe as SectionItem,Hr as SectionItemService,M as SectionItemStatus,Vr as SectionService,mi as ServiceFactory,se as ServiceMode,ce as ServiceOptions,de as Shift,Wr as ShiftService,k as ShiftStatus,nt as StandardPaymentMethod,he as StockChange,Ui as StockLog,Hi as StockLogEntityType,Vi as StockLogRefType,ei as StockLogService,Bi as StockLogType,Ri as Storage,$r as StorageService,Se as Subcategory,ve as System,wt as SystemConfig,D as SystemError,Yt as TaxConfig,lt as TaxMethod,Qe as TemplateData,j as Till,zt as TillConfig,Gr as TillService,A as TillType,dt as UomType,b as User,Jt as UserConfig,_e as Visibility,Ot as WechatPayMethod,vi as createCSVExport,yi as createCSVExportWithHash,pi as dbSchemas,dn as filterByParams,It as getCategoryButtonShape,L as humanizedData,Di as importFromCSV,Ve as normalizedDate,ie as transformer,Yi as validateSTTemplate};
|
|
7
7
|
//# sourceMappingURL=index.js.map
|