@posx/core 5.5.722 → 5.5.724

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 CHANGED
@@ -1604,6 +1604,8 @@ interface IPayment extends IAppCoreModel {
1604
1604
  payment_method: IPaymentMethod;
1605
1605
  /** Payment Method History when payment method is changed */
1606
1606
  payment_method_history?: IPaymentMethodHistory;
1607
+ /** UID of the till record this payment is counted in; empty when the payment has no till */
1608
+ till_uid?: string;
1607
1609
  }
1608
1610
  declare class Payment extends AppCoreModel implements IPayment {
1609
1611
  invoice_uid: string;
@@ -1614,6 +1616,7 @@ declare class Payment extends AppCoreModel implements IPayment {
1614
1616
  payment_method_name: string;
1615
1617
  payment_method: IPaymentMethod;
1616
1618
  payment_method_history: IPaymentMethodHistory;
1619
+ till_uid?: string;
1617
1620
  uid: string;
1618
1621
  updated_at: Date;
1619
1622
  constructor();
@@ -1983,6 +1986,199 @@ declare class EmployeeRole extends AppBaseModel implements IEmployeeRole {
1983
1986
  constructor();
1984
1987
  }
1985
1988
  //#endregion
1989
+ //#region src/types/permission.type.d.ts
1990
+ declare enum RouteNames {
1991
+ POS = "route_pos",
1992
+ CRM = "route_crm",
1993
+ MANAGEMENT = "route_management",
1994
+ SETTINGS = "route_settings",
1995
+ REPORTING = "route_reporting",
1996
+ ANALYTICS = "route_analytics",
1997
+ BOOKING = "route_booking",
1998
+ }
1999
+ declare enum DirectiveNames {
2000
+ FUNCTION_SWITCH_TABLE = "function_switch_table",
2001
+ FUNCTION_LAST_BILL = "function_last_bill",
2002
+ FUNCTION_PRINT_LAST_KITCHEN_SLIP = "function_print_last_kitchen_slip",
2003
+ FUNCTION_PRINT_LAST_ORDER_DOCKET = "function_print_last_order_docket",
2004
+ FUNCTION_PRINT_FULL_ORDER_DOCKET = "function_print_full_order_docket",
2005
+ FUNCTION_NOTE = "function_note",
2006
+ FUNCTION_DELETE_BILL = "function_delete_bill",
2007
+ FUNCTION_PERCENT_DISCOUNT = "function_percent_discount",
2008
+ FUNCTION_FLAT_DISCOUNT = "function_flat_discount",
2009
+ FUNCTION_QR_CODE = "function_qr_code",
2010
+ FUNCTION_PAY_IN = "function_pay_in",
2011
+ FUNCTION_PAY_OUT = "function_pay_out",
2012
+ FUNCTION_OPEN_DRAWER = "function_open_drawer",
2013
+ FUNCTION_VOID = "function_void",
2014
+ FUNCTION_VOID_AND_DUPLICATE = "function_void_and_duplicate",
2015
+ FUNCTION_RECEIPT = "function_receipt",
2016
+ FUNCTION_REPRINT = "function_reprint",
2017
+ FUNCTION_ADD_CUSTOMER = "function_add_customer",
2018
+ FUNCTION_CHANGE_PAYMENT = "function_change_payment",
2019
+ FUNCTION_CHECK = "function_check",
2020
+ FUNCTION_PAY_AT_COUNTER = "function_pay_at_counter",
2021
+ FUNCTION_MERGE_TABLE = "function_merge_table",
2022
+ FUNCTION_ADD_SALESPERSON = "function_add_salesperson",
2023
+ ITEM_EDITOR_FLAT_DISCOUNT = "item_editor_flat_discount",
2024
+ ITEM_EDITOR_PERCENT_DISCOUNT = "item_editor_percent_discount",
2025
+ ITEM_EDITOR_DELETE = "item_editor_delete",
2026
+ ITEM_EDITOR_NOTE = "item_editor_note",
2027
+ ITEM_EDITOR_DUPLICATE = "item_editor_duplicate",
2028
+ ITEM_EDITOR_TAKEAWAY = "item_editor_takeaway",
2029
+ ITEM_EDITOR_TRANSFER = "item_editor_transfer",
2030
+ ITEM_EDITOR_SALES_PERSON = "item_editor_sales_person",
2031
+ ITEM_EDITOR_CHANGE_PRICE = "item_editor_change_price",
2032
+ ITEM_EDITOR_CHANGE_OPEN_PRICE = "item_editor_change_open_price",
2033
+ TABLE_EDITOR = "table_editor",
2034
+ FUNCTION_STOCK_ADJUST = "function_stock_adjust",
2035
+ FUNCTION_STOCK_HISTORY = "function_stock_history",
2036
+ FUNCTION_CRM_ADD_CUSTOMER = "function_crm_add_customer",
2037
+ FUNCTION_CRM_EDIT_CUSTOMER = "function_crm_edit_customer",
2038
+ FUNCTION_CRM_DELETE_CUSTOMER = "function_crm_delete_customer",
2039
+ }
2040
+ declare enum PageNames {
2041
+ MANAGEMENT_REPORT_PAGE = "management_report_page",
2042
+ MANAGEMENT_INVENTORY_PAGE = "management_inventory_page",
2043
+ MANAGEMENT_INVOICES_PAGE = "management_invoices_page",
2044
+ MANAGEMENT_PRODUCT_PAGE = "management_product_page",
2045
+ MANAGEMENT_EMPLOYEE_PAGE = "management_employee_page",
2046
+ MANAGEMENT_SETUP_PAGE = "management_setup_page",
2047
+ }
2048
+ declare const SYSTEM_ROLES: string[];
2049
+ declare const routeValues: string[];
2050
+ declare const functionValues: string[];
2051
+ declare const itemEditorValues: string[];
2052
+ declare const pageValues: string[];
2053
+ //#endregion
2054
+ //#region src/types/permission.labels.d.ts
2055
+ declare const PERMISSION_LABELS: {
2056
+ en: {
2057
+ routes: {
2058
+ route_pos: string;
2059
+ route_crm: string;
2060
+ route_management: string;
2061
+ route_settings: string;
2062
+ route_reporting: string;
2063
+ route_analytics: string;
2064
+ route_booking: string;
2065
+ };
2066
+ functions: {
2067
+ function_switch_table: string;
2068
+ function_last_bill: string;
2069
+ function_print_last_kitchen_slip: string;
2070
+ function_print_last_order_docket: string;
2071
+ function_print_full_order_docket: string;
2072
+ function_note: string;
2073
+ function_delete_bill: string;
2074
+ function_percent_discount: string;
2075
+ function_flat_discount: string;
2076
+ function_qr_code: string;
2077
+ function_pay_in: string;
2078
+ function_pay_out: string;
2079
+ function_open_drawer: string;
2080
+ function_void: string;
2081
+ function_void_and_duplicate: string;
2082
+ function_receipt: string;
2083
+ function_reprint: string;
2084
+ function_add_customer: string;
2085
+ function_change_payment: string;
2086
+ function_check: string;
2087
+ function_pay_at_counter: string;
2088
+ function_merge_table: string;
2089
+ function_add_salesperson: string;
2090
+ function_stock_adjust: string;
2091
+ function_stock_history: string;
2092
+ function_crm_add_customer: string;
2093
+ function_crm_edit_customer: string;
2094
+ function_crm_delete_customer: string;
2095
+ };
2096
+ itemEditor: {
2097
+ table_editor: string;
2098
+ item_editor_flat_discount: string;
2099
+ item_editor_percent_discount: string;
2100
+ item_editor_delete: string;
2101
+ item_editor_note: string;
2102
+ item_editor_duplicate: string;
2103
+ item_editor_takeaway: string;
2104
+ item_editor_transfer: string;
2105
+ item_editor_sales_person: string;
2106
+ item_editor_change_price: string;
2107
+ item_editor_change_open_price: string;
2108
+ };
2109
+ pages: {
2110
+ management_report_page: string;
2111
+ management_inventory_page: string;
2112
+ management_invoices_page: string;
2113
+ management_product_page: string;
2114
+ management_employee_page: string;
2115
+ management_setup_page: string;
2116
+ };
2117
+ };
2118
+ zh: {
2119
+ routes: {
2120
+ route_pos: string;
2121
+ route_crm: string;
2122
+ route_management: string;
2123
+ route_settings: string;
2124
+ route_reporting: string;
2125
+ route_analytics: string;
2126
+ route_booking: string;
2127
+ };
2128
+ functions: {
2129
+ function_switch_table: string;
2130
+ function_last_bill: string;
2131
+ function_print_last_kitchen_slip: string;
2132
+ function_print_last_order_docket: string;
2133
+ function_print_full_order_docket: string;
2134
+ function_note: string;
2135
+ function_delete_bill: string;
2136
+ function_percent_discount: string;
2137
+ function_flat_discount: string;
2138
+ function_qr_code: string;
2139
+ function_pay_in: string;
2140
+ function_pay_out: string;
2141
+ function_open_drawer: string;
2142
+ function_void: string;
2143
+ function_void_and_duplicate: string;
2144
+ function_receipt: string;
2145
+ function_reprint: string;
2146
+ function_add_customer: string;
2147
+ function_change_payment: string;
2148
+ function_check: string;
2149
+ function_pay_at_counter: string;
2150
+ function_merge_table: string;
2151
+ function_add_salesperson: string;
2152
+ function_stock_adjust: string;
2153
+ function_stock_history: string;
2154
+ function_crm_add_customer: string;
2155
+ function_crm_edit_customer: string;
2156
+ function_crm_delete_customer: string;
2157
+ };
2158
+ itemEditor: {
2159
+ table_editor: string;
2160
+ item_editor_flat_discount: string;
2161
+ item_editor_percent_discount: string;
2162
+ item_editor_delete: string;
2163
+ item_editor_note: string;
2164
+ item_editor_duplicate: string;
2165
+ item_editor_takeaway: string;
2166
+ item_editor_transfer: string;
2167
+ item_editor_sales_person: string;
2168
+ item_editor_change_price: string;
2169
+ item_editor_change_open_price: string;
2170
+ };
2171
+ pages: {
2172
+ management_report_page: string;
2173
+ management_inventory_page: string;
2174
+ management_invoices_page: string;
2175
+ management_product_page: string;
2176
+ management_employee_page: string;
2177
+ management_setup_page: string;
2178
+ };
2179
+ };
2180
+ };
2181
+ //#endregion
1986
2182
  //#region src/types/product.type.d.ts
1987
2183
  type TStockChangeItem = {
1988
2184
  item_uid: string;
@@ -3560,6 +3756,7 @@ interface ICustomerDisplaySystemConfig {
3560
3756
  screen_height?: number;
3561
3757
  order_display_duration?: number;
3562
3758
  language?: string;
3759
+ enable_payment_bill?: boolean;
3563
3760
  }
3564
3761
  declare class CustomerDisplaySystemConfig implements ICustomerDisplaySystemConfig {
3565
3762
  enabled: boolean;
@@ -3572,6 +3769,7 @@ declare class CustomerDisplaySystemConfig implements ICustomerDisplaySystemConfi
3572
3769
  screen_height: number;
3573
3770
  order_display_duration: number;
3574
3771
  language: string;
3772
+ enable_payment_bill: boolean;
3575
3773
  constructor();
3576
3774
  }
3577
3775
  interface IKioskSystemConfig {
@@ -3861,6 +4059,8 @@ interface IProductConfig {
3861
4059
  hide_barcoded_items?: boolean;
3862
4060
  /** Recognize EAN-13 in-store scale labels (20 + 5-digit PLU + 5-digit weight g / qty) by PLU instead of barcode */
3863
4061
  enable_weight_scale_barcode?: boolean;
4062
+ /** Enter by_weight item weight in kg on POS instead of grams */
4063
+ weight_input_in_kg?: boolean;
3864
4064
  /** Codename badge background color (hex, e.g. #FF2F00) */
3865
4065
  codename_badge_color?: string;
3866
4066
  }
@@ -3873,6 +4073,7 @@ declare class ProductConfig implements IProductConfig {
3873
4073
  modifier_single_select: boolean;
3874
4074
  hide_barcoded_items: boolean;
3875
4075
  enable_weight_scale_barcode: boolean;
4076
+ weight_input_in_kg: boolean;
3876
4077
  codename_badge_color: string;
3877
4078
  constructor();
3878
4079
  }
@@ -5936,7 +6137,7 @@ interface IPrinterService extends IAppRemoteService<IPrinter> {
5936
6137
  /**
5937
6138
  * Opens the cash drawer.
5938
6139
  */
5939
- openCashDrawer(): Promise<void>;
6140
+ openCashDrawer(kickCode?: string): Promise<void>;
5940
6141
  /** Retrieves the default kitchen display printer */
5941
6142
  getDefaultKitchenDisplayPrinter(): Promise<IPrinter>;
5942
6143
  }
@@ -5964,7 +6165,7 @@ declare class PrinterService extends AppRemoteService<IPrinter> implements IPrin
5964
6165
  getDefaultKitchenDisplayPrinter(): Promise<IPrinter>;
5965
6166
  getPrintersByUids(uids: string[]): Promise<IPrinter[]>;
5966
6167
  searchPrinters(refresh?: boolean, port?: number): Promise<string[]>;
5967
- openCashDrawer(): Promise<void>;
6168
+ openCashDrawer(kickCode?: string): Promise<void>;
5968
6169
  }
5969
6170
  //#endregion
5970
6171
  //#region src/types/ods.type.d.ts
@@ -6146,7 +6347,7 @@ declare class InvoiceBaseService extends AppRemoteService<IInvoice> implements I
6146
6347
  * @returns void
6147
6348
  */
6148
6349
  calculateRewardPoint(invoice: IInvoice, aboveInvoiceAmount: number, includeServiceCharge: boolean, includeTax: boolean): void;
6149
- /** Reverse-calculates flat discount needed to reach target grand_total */
6350
+ /** Reverse-calculates flat AfterSubtotal discount needed to reach target grand_total */
6150
6351
  calculateDiscountFromTargetTotal(invoice: IInvoice, targetGrandTotal: number, appConfig: IAppConfig): number;
6151
6352
  private resetInvoiceCalculations;
6152
6353
  private resetLineCalculations;
@@ -6719,7 +6920,7 @@ declare function humanizedData(date: Date, format?: string): string;
6719
6920
  declare function normalizedDate(date: Date): string;
6720
6921
  //#endregion
6721
6922
  //#region src/types/csv.type.d.ts
6722
- /** CSV v11 format: 30 columns, adds sold-out reset/exempt/pax flags after Config (v6 reserved for #122 Icon) */
6923
+ /** CSV v12 format: 33 columns, adds Add Credit/Add Point/Minus Point after the v11 flags (v6 reserved for #122 Icon) */
6723
6924
  interface IExportRow {
6724
6925
  type: 'category' | 'subcategory' | 'product' | 'modifier_category' | 'modifier' | 'combo' | 'combo_group' | 'combo_item';
6725
6926
  name: string;
@@ -6751,6 +6952,9 @@ interface IExportRow {
6751
6952
  is_pax_linked?: number;
6752
6953
  is_point_reward_exempt?: boolean;
6753
6954
  is_credit_reward_exempt?: boolean;
6955
+ add_credit?: number;
6956
+ add_point?: number;
6957
+ minus_point?: number;
6754
6958
  }
6755
6959
  //#endregion
6756
6960
  //#region src/utils/csv.utils.d.ts
@@ -6863,5 +7067,5 @@ declare function validateSTTemplate(jsonStr: string): ValidationResult;
6863
7067
  /** Pure deep-clone of an item with fresh uids, cleared plu, and regenerated modifier ids. Shared by ItemService and admin-portal. */
6864
7068
  declare function cloneItemData(item: IItem): IItem;
6865
7069
  //#endregion
6866
- 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, DatabaseStats, DayOfWeek, DeployChannel, Device, DeviceEtc, DeviceType, DiagnosticsService, DirectPayInvoiceOptions, DiscountType, DrawerSummary, ElectronSocket, Employee, EmployeeRole, EmployeeRoleService, EmployeeService, ErrorMsgs, EscPosCompatibility, EscPosPrinter, EventPrintConfig, 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, IEventPrintConfig, 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, INonCashTillSummary, 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, ITillEntry, ITillService, IUser, IUserConfig, IVisibility, In, Include, InventoryConfig, Invoice, InvoiceAction, InvoiceActivity, InvoiceBaseService, InvoiceCharge, InvoiceCoreLine, InvoiceDeviceType, 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, NonCashTillSummary, 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, PriceType, 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, TableStats, TaxConfig, TaxMethod, TemplateData, Till, TillConfig, TillService, TillType, UomType, UpdateGeneralConfigOptions, UpdateInvoiceOptions, User, UserConfig, type ValidationError, type ValidationResult, Visibility, VoidInvoiceOptions, WechatPayMethod, WeeklyHours, cloneItemData, createCSVExport, createCSVExportWithHash, dbSchemas, filterByParams, getCategoryButtonShape, humanizedData, importFromCSV, mergeImportedItem, normalizedDate, transformer, validateSTTemplate };
7070
+ 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, DatabaseStats, DayOfWeek, DeployChannel, Device, DeviceEtc, DeviceType, DiagnosticsService, DirectPayInvoiceOptions, DirectiveNames, DiscountType, DrawerSummary, ElectronSocket, Employee, EmployeeRole, EmployeeRoleService, EmployeeService, ErrorMsgs, EscPosCompatibility, EscPosPrinter, EventPrintConfig, 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, IEventPrintConfig, 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, INonCashTillSummary, 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, ITillEntry, ITillService, IUser, IUserConfig, IVisibility, In, Include, InventoryConfig, Invoice, InvoiceAction, InvoiceActivity, InvoiceBaseService, InvoiceCharge, InvoiceCoreLine, InvoiceDeviceType, 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, NonCashTillSummary, Not, Note, NoteEntity, NoteGroup, NoteGroupEntity, OnlineOrderConfig, OpenHours, OrderConfig, OrderDisplay, OrderDisplayService, OrderDisplayStatus, OrderDisplaySystemConfig, OrderFlow, PERMISSION_LABELS, PageNames, PaxConfig, PayInvoiceOptions, Payment, PaymentConfig, PaymentMethod, PaymentMethodHistory, PaymentMethodService, PaymentService, PaymentStatus, PaymentSummary, PaynowMethod, Price, PriceType, 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, RouteNames, SYSTEM_ROLES, 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, TableStats, TaxConfig, TaxMethod, TemplateData, Till, TillConfig, TillService, TillType, UomType, UpdateGeneralConfigOptions, UpdateInvoiceOptions, User, UserConfig, type ValidationError, type ValidationResult, Visibility, VoidInvoiceOptions, WechatPayMethod, WeeklyHours, cloneItemData, createCSVExport, createCSVExportWithHash, dbSchemas, filterByParams, functionValues, getCategoryButtonShape, humanizedData, importFromCSV, itemEditorValues, mergeImportedItem, normalizedDate, pageValues, routeValues, transformer, validateSTTemplate };
6867
7071
  //# 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||{}),w=class{constructor(){v(this,`applying_type`,S.Inclusive),v(this,`applying_items`,[])}},T=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)}},ee=class{constructor(e){v(this,`invoice_uid`,``),e&&(this.invoice_uid=e.invoice_uid)}},te=class{constructor(e){v(this,`guid`,``),v(this,`coupon`,new T),v(this,`is_multi_stores`,!1),v(this,`usage`,new ee),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 T(e.coupon),this.is_multi_stores=e.is_multi_stores,this.usage=new ee(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 ne={from(t){return e(t).format(`YYYY-MM-DD HH:mm:ss`)},to(e){return e}};var E=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)}},D=class extends E{constructor(){super(),v(this,`name`,void 0),v(this,`name_translations`,{})}},re=class extends D{constructor(...e){super(...e),v(this,`description`,void 0),v(this,`description_translations`,{})}};let O=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}({}),ie=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}({}),ae=function(e){return e.LOCAL=`local`,e.CLOUD=`cloud`,e}({});var oe=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 se=function(e){return e.Data=`DataMessage`,e.Event=`EventMessage`,e}({});var ce=class{constructor(){v(this,`model`,``),v(this,`data`,``),v(this,`has_many`,!1),v(this,`type`,se.Data)}},k=class extends Error{constructor(e){super(e),this.name=`system_error`}};let A=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}({}),j=function(e){return e.Open=`opened`,e.Closed=`closed`,e}({});var le=class extends E{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`,j.Open),v(this,`uid`,O.Shift+t())}};let M=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 N=class extends E{constructor(){super(),v(this,`user_uid`,``),v(this,`shift_uid`,``),v(this,`invoice_uid`,``),v(this,`type`,M.CashDeposit),v(this,`amount`,0),v(this,`note`,``),v(this,`uid`,O.Till+t()),v(this,`payment_method_uid`,void 0),v(this,`payment_method_code`,void 0),v(this,`payment_method_name`,void 0),v(this,`payment_method`,void 0)}};let P=function(e){return e.CLOSED=`closed`,e.OPENED=`opened`,e.PAYMENT=`payment`,e}({});var ue=class extends D{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`,O.SectionItem+t()),v(this,`invoice_uid`,``),v(this,`section_uid`,``),v(this,`status`,P.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`,{})}},de=class extends D{constructor(){super(),v(this,`sequence`,0),v(this,`disable_auto_print_receipt`,!1),v(this,`uid`,O.Section+t())}},fe=class extends D{constructor(){super(),v(this,`permissions`,[]),v(this,`is_default`,!1),v(this,`uid`,O.EmployeeRole+t())}},pe=class{constructor(e){v(this,`item_uid`,``),v(this,`quantity`,0),v(this,`modifiers`,[]),this.item_uid=e,this.quantity=0,this.modifiers=[]}},me=class extends re{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)}},he=class{constructor(){v(this,`system`,ge.POS),v(this,`visible`,!1),v(this,`sequence`,0)}};let ge=function(e){return e.POS=`pos`,e.QrCodeOrder=`qr_code_order`,e}({}),_e=function(e){return e.Product=`product`,e.Modifier=`modifier`,e}({});var ve=class extends me{constructor(){super(),v(this,`type`,_e.Modifier),v(this,`visibility`,[]),v(this,`uid`,O.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)}},ye=class extends me{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`,_e.Product),v(this,`is_delisted`,!1),v(this,`subcategories`,[]),v(this,`uid`,O.Category+t()),v(this,`max_order`,0),v(this,`min_order`,0),v(this,`code`,void 0),v(this,`non_searchable`,!1)}},be=class extends me{constructor(){super(),v(this,`category_uid`,``),v(this,`uid`,O.Subcategory+t())}};let F=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 xe=class extends me{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`,F.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,`auto_reset_sold_out`,!1),v(this,`exclude_auto_reset_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,`is_always_auto_applied`,!1),v(this,`has_bcrs_deposit`,!1),v(this,`uid`,O.ItemModifier+t())}},Se=class extends xe{constructor(){super(),v(this,`codename`,``),v(this,`sku`,``),v(this,`recipe`,``),v(this,`barcode`,``),v(this,`type`,F.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`,O.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),v(this,`is_pax_linked`,void 0),v(this,`is_discount_nonstackable`,!1),v(this,`price_as_total_payable`,!1)}};let Ce=function(e){return e.Flat=`flat`,e.Percent=`percent`,e}({});var we=class extends E{constructor(){super(),v(this,`lookup_keys`,[]),v(this,`product_uid`,``),v(this,`uid`,O.Price+t()),v(this,`amount`,0),v(this,`type`,Ce.Flat),v(this,`percent`,1),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`,O.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(I).includes(e.codepage)){let t=parseInt(e.codepage,10);r.raw([31,27,31,255,t,10,0])}else e.codepage&&Object.values(I).includes(e.codepage)?n.codepage(e.codepage):n.codepage(I.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 L.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 L.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 L.Line:r.line(t.item?.text?.repeat(48)??`-`.repeat(48),t.item?.line_width??48);break;case L.NewLine:t.repeat=t.repeat??1;for(let e=0;e<t.repeat;e++)r.newline();break;case L.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 L.QRCode:t.qrcode&&r.qrcode(t.qrcode.data,t.qrcode.model,t.qrcode.size,t.qrcode.errorlevel);break;case L.Barcode:t.barcode&&r.barcode(t.barcode.data,t.barcode.symbology,t.barcode.height);break;case L.Cut:r.cut(t.item?.text??`full`);break;case L.Beeper:r.beeper();break;case L.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 I=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}({}),L=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 R=class{constructor(){v(this,`codepage`,I.WesternEuropeanLatin),v(this,`items`,[])}};function z(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 D{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 D{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}({}),B=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.EventPrinter=`event_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.WINDOWS_DRIVER_BUILT_IN=`WINDOWS_DRIVER_BUILT_IN`,e}({});var qe=class{constructor(){v(this,`header`,``),v(this,`body`,``),v(this,`footer`,``),v(this,`commands`,``),v(this,`type`,B.ReceiptPrinter)}},V=class extends D{constructor(){super(),v(this,`header`,``),v(this,`body`,``),v(this,`footer`,``),v(this,`commands`,``),v(this,`printer_type`,B.ReceiptPrinter),v(this,`codepage`,void 0),v(this,`uid`,O.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 H=class extends D{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`,B.ReceiptPrinter),v(this,`protocol`,Ge.ESCPOS),v(this,`connection_type`,Ke.ETHERNET),v(this,`data`,new R),v(this,`status`,Je.Queued),v(this,`retries`,0),v(this,`commands`,``),v(this,`uid`,O.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 D{constructor(){super(),v(this,`device_uid`,``),v(this,`terminal_device_uids`,[]),v(this,`type`,B.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`,O.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`,``),v(this,`disable_cancel_print`,!1)}},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=z(this.printed_at)}},U=class{constructor(){v(this,`printer_name`,``),v(this,`kitchen_itemized_print`,!1),v(this,`is_cancel`,!1)}},Qe=class extends E{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`,O.Payment+t()),v(this,`updated_at`,new Date)}},$e=class extends D{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,`col`,void 0),v(this,`row`,void 0),v(this,`uid`,O.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 D{constructor(){super()}},it=class extends rt{constructor(){super()}},at=class extends D{constructor(){super(),v(this,`note_group_uid`,``),v(this,`related_model`,ie.Invoice),v(this,`usage`,0)}},ot=class extends at{constructor(){super()}};let W=function(e){return e.DineIn=`dine_in`,e.TakeOut=`take_out`,e.Delivery=`delivery`,e}({}),st=function(e){return e.Posx=`posx`,e.Kiosk=`kiosk`,e.WyoApp=`wyo_app`,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}({}),G=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}({}),K=function(e){return e.Flat=`flat`,e.Percent=`percent`,e}({}),q=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`,O.InvoiceCharge+t()),v(this,`name`,``),v(this,`percentage`,0),v(this,`amount`,0),v(this,`calc_flow`,q.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`,O.Charge+t()),v(this,`name`,``),v(this,`percent`,0),v(this,`calc_flow`,q.AfterSubtotal),v(this,`trigger_condition`,``)}},gt=class{constructor(){v(this,`calc_type`,K.Flat),v(this,`amount`,0),v(this,`percent`,0),v(this,`percent_amount`,0),v(this,`type`,ft.Custom),v(this,`calc_flow`,q.AfterSubtotal),v(this,`applying_item_uids`,[]),v(this,`name`,``),v(this,`name_translation`,{}),v(this,`voucher_uid`,``),v(this,`coupon_uid`,``),v(this,`uid`,O.InvoiceDiscount+t())}},_t=class{constructor(){v(this,`item_uid`,``),v(this,`item`,new xe),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 E{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`,K.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 Se),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),v(this,`is_pax_linked`,void 0)}},yt=class extends E{constructor(e){super(),v(this,`ref_id`,``),v(this,`call_num`,``),v(this,`table_uid`,``),v(this,`table_name`,``),v(this,`type`,W.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,`bcrs_deposit`,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`,G.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,`signature`,void 0),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`,O.Invoice+t()),v(this,`meta`,{}),v(this,`price_lookup_key`,``),e&&(this.meta={device_type:e})}},bt=class extends E{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`,O.Employee+t()),v(this,`role_uid`,``),v(this,`language`,`en`),v(this,`can_login`,!0)}},xt=class extends E{constructor(){super(),v(this,`config`,new Nt),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,`table_switch_slip`,!1)}},Et=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)}},Dt=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 Ot=function(e){return e.SmoochPay=`SPCD`,e.YeahPay=`YEAP`,e.Shouqianba=`CRES`,e}({}),kt=function(e){return e.YeahPayWechat=`YPWP`,e.YeahPayWechatOnline=`YPWO`,e.Shouqianba=`WCPH`,e}({}),At=function(e){return e.YeahPayAlipay=`YPAP`,e.YeahPayAlipayOnline=`YPAO`,e.Shouqianba=`ALPH`,e}({});var jt=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,`enable_pay_at_counter`,!1),v(this,`landing_image`,``),v(this,`menu_banner_image`,``),v(this,`home_page_images`,[]),v(this,`paynow_method`,Pt.WyoPaynow),v(this,`card_payment_code`,Ot.SmoochPay),v(this,`wechat_method`,kt.YeahPayWechat),v(this,`alipay_method`,At.YeahPayAlipay),v(this,`takeout_call_num_prefix`,void 0),v(this,`hide_item_price_when_zero_modifier_price`,!1)}},Mt=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})}},Nt=class{constructor(){v(this,`general`,new zt),v(this,`product`,new Rt),v(this,`till`,new Bt),v(this,`report`,new Vt),v(this,`receipt`,new Ht),v(this,`kitchen`,new Ut),v(this,`kds`,new Wt),v(this,`label`,new Gt),v(this,`order`,new Kt),v(this,`ods`,new qt),v(this,`payment`,new Jt),v(this,`user`,new Yt),v(this,`tax`,new Xt),v(this,`rounding`,new $t),v(this,`inventory`,new en),v(this,`pax_config`,new tn),v(this,`gto`,new nn),v(this,`cash_drawer`,new rn),v(this,`marketing`,new Mt),v(this,`charges`,new Zt),v(this,`currency`,new Qt),v(this,`cds`,new Dt),v(this,`kiosk`,new jt),v(this,`online_order`,new Ft),v(this,`loyalty_program`,new Et),v(this,`crm`,new Ct),v(this,`system`,new wt),v(this,`event_print`,new Tt)}};let Pt=function(e){return e.FomoOnlinePaynow=`PNWO`,e.WyoPaynow=`WPPN`,e.YeahPayPaynow=`YPPN`,e}({});var Ft=class{constructor(){v(this,`enable_membership`,!1),v(this,`enable_payment_without_member_login`,!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),v(this,`disable_pay_at_counter_for_take_out`,!1),v(this,`disable_qr_order_receipt`,!1),v(this,`auto_prompt_pax`,!1),v(this,`upsell_item_uids`,[])}};let It=function(e){return e.PROD=`prod`,e.DEV=`dev`,e}({});const Lt=e=>e===`compact`||e===`rectangle`?e:`square`;var Rt=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`),v(this,`show_codename`,!1),v(this,`modifier_single_select`,!1),v(this,`hide_barcoded_items`,!1),v(this,`enable_weight_scale_barcode`,!1),v(this,`codename_badge_color`,`#FF2F00`)}},zt=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`,It.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`}}])}},Bt=class{constructor(){v(this,`control`,!0),v(this,`slip`,!0),v(this,`auto_start_shift`,!1),v(this,`auto_shift_amount`,0)}},Vt=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)}},Ht=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)}},Ut=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`)}},Wt=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),v(this,`show_done_count`,!1),v(this,`show_combo_parent_name`,!1),v(this,`station_mode`,`done`),v(this,`hide_mode`,`done`),v(this,`menu_font_scale`,1),v(this,`text_color_name`,`#FFFFFF`),v(this,`text_color_modifier`,`#FFFFFF`),v(this,`text_color_note`,`#FFFFFF`),v(this,`scroll_mode`,!1),v(this,`new_order_sound_enabled`,!0)}},Gt=class{constructor(){v(this,`print`,!1),v(this,`text_to_raster`,!1)}},Kt=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),v(this,`check_modifier_min_order`,!1),v(this,`auto_prompt_pax`,!1),v(this,`return_to_tables_after_send`,!1),v(this,`disable_line_merge_between_sends`,!1),v(this,`keep_unsent_lines`,!1),v(this,`keep_auto_added_lines_at_end`,!1),v(this,`lock_invoice_after_shift_close`,!1),v(this,`logout_after_end_shift`,!1),v(this,`enable_staff_login_on_launch`,!1),v(this,`change_modifier_stock_on_send`,!1),v(this,`enable_min_order_qty`,!1),v(this,`enable_takeaway_auto_modifier`,!1),v(this,`enable_modifier_total_display`,!0),v(this,`enable_pay_at_counter_badge`,!0),v(this,`sort_remarks_by_recent_use`,!1)}},qt=class{constructor(){v(this,`enabled`,!1),v(this,`language`,`en`)}},Jt=class{constructor(){v(this,`quick_cash_payment`,!1),v(this,`notification`,!0),v(this,`quick`,!1),v(this,`payment_auto_redirect_seconds`,5),v(this,`auto_prompt_commission`,!1)}},Yt=class{constructor(){v(this,`control`,!0)}},Xt=class{constructor(){v(this,`enabled`,!0),v(this,`method`,lt.Inclusive),v(this,`rate`,7),v(this,`name`,`GST`)}},Zt=class{constructor(){v(this,`service_charge`,!1),v(this,`service_charge_rate`,10)}},Qt=class{constructor(){v(this,`currency_symbol`,`$`),v(this,`is_symbol_after_amount`,!1)}},$t=class{constructor(){v(this,`base`,.1),v(this,`up`,!0),v(this,`cashless`,!1),v(this,`prepayment_rounding`,!1)}},en=class{constructor(){v(this,`inventory_control`,!1),v(this,`sold_out_for_today_only`,!1)}},tn=class{constructor(){v(this,`pax`,!0),v(this,`detail`,!1)}},nn=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`)}},rn=class{constructor(){v(this,`kick_code`,`27, 112, 48, 55, 121`),v(this,`connection_mode`,`via_receipt_printer`)}},an=class{constructor(e){v(this,`name`,``),v(this,`base64`,``),v(this,`extension`,`png`),Object.assign(this,e)}};const on=e=>e===``||e===void 0,sn=e=>t=>on(e)||t.includes(e),cn=e=>t=>on(e)||e.includes(t),ln=(e,t)=>n=>n>e&&n<t,un=e=>typeof e==`function`?(t,n)=>!e(t,n):t=>t!=e,dn=e=>e,fn=e=>t=>!t.deleted_at&&Object.keys(e).every(n=>{if(on(e[n])||t[n]===e[n])return!0;if(typeof e[n]==`function`)return e[n](t[n],t)});var pn=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 insertIfNotExists(e){let n={...e};n.created_at||(n.created_at=new Date),n.uid||(n.uid=t()),n.updated_at=new Date;try{return await this.db.table(this.moduleName).add(n),!0}catch(e){if(e.name!==`ConstraintError`)throw e;return!1}}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(fn(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(fn(e)).count(),o=this.db.table(this.moduleName).filter(fn(e));return r!==-1&&o.offset((n-1)*r).limit(r),{list:await o.toArray(),count:a,page:n,pageSize:r}}},mn=class extends pn{async updateOne(e,t){throw Error(`Method not implemented.`)}async deleteOne(e){throw Error(`Method not implemented.`)}},J=class extends pn{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}};function hn(e){let n=o.cloneDeep(e);if(n.uid=O.Item+t(),n.id_in_server=0,n.plu=void 0,!n.modifier_categories?.length)return n;let r=[],i=[];for(let e of n.modifier_categories){let a=n.modifiers?.filter(t=>t.category_uid===e.uid);if(!a?.length)continue;let s={...o.cloneDeep(e),uid:O.ItemModifierCategory+t()};r.push(s),i.push(...a.map(e=>({...o.cloneDeep(e),uid:O.ItemModifier+t(),category_uid:s.uid})))}return n.modifier_categories=r,n.modifiers=i,n}let gn=function(e){return e[e.printable=0]=`printable`,e[e.generative=1]=`generative`,e}({});var _n=class{constructor(){v(this,`uid`,O.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)}},vn=class{constructor(){v(this,`uid`,O.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)}},yn=class extends E{constructor(){super(),v(this,`uid`,O.AppReport+t()),v(this,`reports`,[]),v(this,`version`,1)}},bn=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,`printed_time`,``),v(this,`sales_summary`,new xn),v(this,`drawer_summary`,new Sn),v(this,`non_cash_till_summary`,new Cn),v(this,`payments_summary`,[]),v(this,`loyalty_program_summary`,new Tn),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`,[]),v(this,`first_ref_id`,``),v(this,`last_ref_id`,``)}},xn=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)}},Sn=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),v(this,`entries`,[])}},Cn=class{constructor(){v(this,`pay_in_total`,0),v(this,`pay_in_count`,0),v(this,`pay_out_total`,0),v(this,`pay_out_count`,0),v(this,`pay_in_by_method`,[]),v(this,`pay_out_by_method`,[]),v(this,`entries`,[])}},wn=class{constructor(){v(this,`code`,``),v(this,`name`,``),v(this,`total`,0),v(this,`count`,0)}},Tn=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)}},En=class{constructor(){v(this,`item`,{}),v(this,`quantity`,0),v(this,`total_amount`,0),v(this,`modifiers`,[])}},Dn=class{constructor(){v(this,`item`,{}),v(this,`quantity`,0),v(this,`total_amount`,0)}},On=class{constructor(){v(this,`category`,null),v(this,`items`,[]),v(this,`total_quantity`,0),v(this,`total_amount`,0)}},kn=class extends J{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 Kr(e,t,n,`configs`,`config`),this.printJobService=new ni(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(B.ReceiptPrinter)}async getDefaultPrinterByType(e){return this.getDefaultPrinter(e)}async getDefaultKioskPrinter(){return this.getDefaultPrinter(B.KioskPrinter)}async getDefaultCheckPrinter(){return this.getDefaultPrinter(B.CheckPrinter)}async getDefaultKitchenPrinter(){return this.getDefaultPrinter(B.KitchenPrinter)}async getDefaultOrderPrinter(){return this.getDefaultPrinter(B.OrderPrinter)}async getDefaultKitchenDisplayPrinter(){return this.getDefaultPrinter(B.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 R;t.items.push({type:L.OpenCashDrawer});let n=new H(e,t,!1,1);await this.printJobService.addOne(n)}};function Y(e,t=2){let n=10**t;return Math.round(+(e*n).toFixed(6))/n}function An(e){let t=e.name,n=t.lastIndexOf(`.`);return n===-1||n===t.length-1?``:t.slice(n+1)}function jn(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 Mn=(e,t)=>e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/[_\-\.]+/g,` `).toLowerCase().replace(/[\s]+(\w)/g,(e,n)=>t(n)),Nn=e=>e.replace(/^\W+|\W+$/g,``),Pn=e=>typeof e==`string`?Mn(e,e=>e.toUpperCase()):``,Fn=e=>typeof e==`string`?e.charAt(0).toUpperCase()+e.slice(1):``,In=e=>typeof e==`string`?e.replace(/\w\S*/g,e=>Fn(e)):``,Ln=e=>typeof e==`string`?Mn(e,e=>`-`+e):``,Rn=e=>typeof e==`string`?Mn(e,e=>`.`+e):``,zn=e=>Bn(e),Bn=e=>typeof e==`string`?e.toLowerCase():``,Vn=e=>{if(typeof e!=`string`)return``;let t=Mn(e,e=>e.toUpperCase());return t.charAt(0).toUpperCase()+t.slice(1)},Hn=e=>typeof e==`string`?Mn(e,e=>`/`+e):``,Un=e=>typeof e==`string`?e.replace(/((?:\S[^\.\?\!]*)[\.\?\!]*)/g,e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()):``,Wn=e=>typeof e==`string`?Mn(e,e=>`_`+e):``,Gn=e=>typeof e==`string`?e.replace(/[- _]+/g,` `).split(` `).map(e=>Fn(e)).join(` `):``,Kn=e=>qn(e),qn=e=>typeof e==`string`?e.toUpperCase():``,Jn=(e,t)=>typeof e==`string`&&typeof t==`string`?e+t:e,Yn=(e,t)=>{if(typeof e!=`string`)return``;let n=``;for(let e=0;e<t;e++)n+=`&nbsp;`;return n+e+n},Xn=e=>typeof e==`string`?Nn(e):``,Zn=e=>typeof e==`string`?e.split(` `).join(`-`):``,Qn=(e,t=` `)=>typeof e==`string`?(typeof t!=`string`&&(t=` `),e.split(t).join(`+`)):``,$n=(e,t)=>typeof e==`string`&&typeof t==`string`?t+e:e,er=(e,t)=>typeof e==`string`?typeof t==`string`?e.split(t).join(``):e:``,tr=(e,t)=>typeof e==`string`?typeof t==`string`?e.replace(t,``):e:``,nr=(e,t,n)=>typeof e==`string`?typeof t==`string`?(typeof n!=`string`&&(n=``),e.split(t).join(n)):e:``,rr=(e,t,n)=>typeof e==`string`?typeof t==`string`?(typeof n!=`string`&&(n=``),e.replace(t,n)):e:``,ir=e=>typeof e==`string`?e.split(``).reverse().join(``):``,ar=(e,t=`,`)=>typeof e==`string`?(typeof t!=`string`&&(t=`,`),e.split(t)):[],or=(e,t)=>typeof e==`string`?e.length<=t?e:ur(e,t)+`…`:``,sr=e=>typeof e==`string`?e.trim():``,cr=e=>typeof e==`string`?e.replace(/^\s+/,``):``,lr=e=>typeof e==`string`?e.replace(/\s+$/,``):``,ur=(e,t,n=``)=>typeof e==`string`?(typeof n!=`string`&&(n=``),e.length>t?e.slice(0,t-n.length)+n:e):``;var dr={camelcase:Pn,capitalize:Fn,capitalizeAll:In,dashcase:Ln,dotcase:Rn,downcase:zn,lowercase:Bn,pascalcase:Vn,pathcase:Hn,sentence:Un,snakecase:Wn,titleize:Gn,upcase:Kn,uppercase:qn,append:Jn,center:Yn,chop:Xn,hyphenate:Zn,plusify:Qn,prepend:$n,remove:er,removeFirst:tr,replace:nr,replaceFirst:rr,reverse:ir,split:ar,ellipsis:or,trim:sr,trimLeft:cr,trimRight:lr,truncate:ur,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 fr=e=>e&&typeof e==`object`&&typeof e.fn==`function`,X=(e,t,n)=>fr(n)?e?n.fn?n.fn(t):!0:n.inverse?n.inverse(t):!1:e,pr=function(...e){let t=e.pop();return X(e.every(e=>!!e),this,t)},mr=function(...e){let t=e.pop();return X(e.some(e=>!!e),this,t)},hr=function(e,t){return X(!e,this,t)},gr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),X(e===t,this,n)},_r=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),X(e==t,this,n)},vr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),X(e!==t,this,n)},yr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),X(e!=t,this,n)},br=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),X(e>t,this,n)},xr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),X(e>=t,this,n)},Sr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),X(e<t,this,n)},Cr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),X(e<=t,this,n)},wr=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 X(i,this,r)},Tr=function(e,t,n){return typeof n==`number`&&(n=arguments[3]),X(e==null?!1:Array.isArray(e)||typeof e==`string`?e.includes(t):typeof e==`object`?t in e:!1,this,n)},Er=Tr,Dr=function(e,...t){let n=t.pop();return X(t.includes(e),this,n)},Or=(e,t)=>{if(!(!e||!t))return t.split(`.`).reduce((e,t)=>e?.[t],e)},kr=e=>{let t=[];for(let n=0;n<e.length-1;n+=2)typeof e[n]==`string`&&!fr(e[n+1])&&t.push({prop:e[n],value:e[n+1]});return t};var Ar={and:pr,or:mr,not:hr,eq:gr,is:_r,neq:vr,isnt:yr,gt:br,gte:xr,lt:Sr,lte:Cr,compare:wr,contains:Tr,includes:Er,in:Dr,findAnd:function(e,...t){if(!Array.isArray(e))return null;let n=kr(t);return e.find(e=>n.every(t=>Or(e,t.prop)===t.value))||null},findOr:function(e,...t){if(!Array.isArray(e))return null;let n=kr(t);return e.find(e=>n.some(t=>Or(e,t.prop)===t.value))||null},filterAnd:function(e,...t){if(!Array.isArray(e))return[];let n=kr(t);return e.filter(e=>n.every(t=>Or(e,t.prop)===t.value))},filterOr:function(e,...t){if(!Array.isArray(e))return[];let n=kr(t);return e.filter(e=>n.some(t=>Or(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 X(!e&&!t,this,n)},ifEven:function(e,t){return X(e%2==0,this,t)},ifOdd:function(e,t){return X(e%2!=0,this,t)},ifNth:function(e,t,n){return X(typeof e==`number`&&typeof t==`number`&&t%e===0,this,n)}};function jr(e){let t=e?.handlebars||e?.hbs||m(`handlebars`);return Object.keys(dr).forEach(e=>{t.registerHelper(e,dr[e])}),Object.keys(Ar).forEach(e=>{t.registerHelper(e,Ar[e])}),t.helpers}var Mr=jr,Nr=class extends E{constructor(){super(),v(this,`uid`,O.OrderDisplaySystem+t()),v(this,`order_number`,``),v(this,`status`,Pr.Preparing)}};let Pr=function(e){return e.Preparing=`preparing`,e.ReadyForPickup=`ready_for_pickup`,e}({});var Fr=class extends J{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 k(`Display order not found`);if(t.status==`ready_for_pickup`)throw new k(`Order is already ready for pickup`);if(t.status=Pr.ReadyForPickup,t.updated_at=new Date,t.id_in_server==0)throw new k(`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 k(`Display order not found`);if(t.status==`preparing`)throw new k(`Order is already preparing`);if(t.status=Pr.Preparing,t.updated_at=new Date,t.id_in_server==0)throw new k(`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==Pr.ReadyForPickup).reverse().limit(100).toArray();if(e.length===0)throw new k(`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=Pr.Preparing,t.updated_at=new Date,t.id_in_server==0)throw new k(`Order is not synced with server`);return await this.updateOne(t.id_in_server,t),t}};Mr({handlebars:d});const Ir=(e,t)=>e.item?.[t]?e.subtotal:e.subtotal_before_discount?e.quantity*(e.modifiers||[]).filter(e=>e.item?.[t]).reduce((e,t)=>e+t.price*t.quantity,0)*e.subtotal/e.subtotal_before_discount:0,Lr={quantity:1,price:0,remark:``};var Rr=class extends J{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 Zr(e,t,n,`tills`,`till`),this.sectionItemService=new Jr(e,t,n,`section_items`,`section_item`),this.sectionService=new qr(e,t,n,`sections`,`section`),this.configService=new Kr(e,t,n,`configs`,`config`),this.printTemplateService=new ii(e,t,n,`print_templates`,`print_template`),this.printerService=new kn(e,t,n,`printers`,`printer`),this.printJobService=new ni(e,t,n,`print_jobs`,`print_job`),this.itemService=new Wr(e,t,n,`items`,`item`),this.orderDisplayService=new Fr(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,q.AfterSubtotal),e.grand_total<0&&(e.grand_total=0,e.service_chargeable_subtotal=0),this.calculateInvoiceCharges(e,q.AfterSubtotal),e.subtotal>0&&e.discount_amount>0){let t=1-e.discount_amount/e.subtotal;e.service_chargeable_subtotal=Y(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,q.AfterServiceCharge),e.grand_total<0&&(e.grand_total=0),this.calculateInvoiceCharges(e,q.AfterServiceCharge);let i=t.config.tax.enabled?t.config.tax.rate:0;return this.calculateTax(e,i,t.config.tax.method),e.bcrs_deposit=Y(e.lines.reduce((e,t)=>e+(t.item?.has_bcrs_deposit?t.quantity*.1:0),0),2),e.grand_total=Y(e.grand_total+e.bcrs_deposit,2),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,q.AfterGrantTotal),e.grand_total<0&&(e.grand_total=0),this.calculateInvoiceCharges(e,q.AfterGrantTotal),e.grand_total=Y(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+=Y(n.subtotal,2),e.point_subtotal+=n.point_subtotal;e.subtotal=Y(t,2),e.grand_total=Y(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=Y(e.quantity*(e.price+t),2),e.item.discountable&&(e.discount_amount>0||e.discount_percent>0)&&(e.discount_calc_type==K.Flat||(e.discount_amount=Y(e.subtotal*e.discount_percent,2)),e.subtotal-=e.discount_amount),e.subtotal=Y(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=Y(Y(e.lines.filter(e=>!e.is_take_out).reduce((e,t)=>e+t.subtotal-Ir(t,`is_service_charge_exempt`),0)),2)}calculateDiscount(e,t){if(!e?.lines?.length)return;let n=0;if(e.discountable_subtotal=Y(e.lines.filter(e=>e.item.discountable&&!(e.item.is_discount_nonstackable&&e.discount_amount>0)).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==K.Flat?n+=r.amount:(r.percent_amount=Y((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){let e=n.price+(n.modifiers??[]).reduce((e,t)=>e+t.price*t.quantity,0);r.applying_item_uids.includes(n.item_uid)&&e>t&&(t=e,i=!0)}if(!i){e.discounts=e.discounts.filter(e=>e.uid!=r.uid);continue}r.calc_type==K.Flat?(r.amount=Y(r.amount>t?t:r.amount),n+=r.amount):(r.percent_amount=Y(t*r.percent),n+=r.percent_amount)}e.discount_amount+=Y(n),e.grand_total=Y(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=Y(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,Y(s/100)}calculateDeliveryCharge(e){e.delivery_charge>0&&e.type===W.Delivery&&(e.grand_total+=e.delivery_charge,e.grand_total=Y(e.grand_total,2))}calculateServiceCharge(e,t){let n=0;e.service_charge=0,!(e.lines==null||e.lines.length<1)&&(e.type==W.Delivery||e.type==W.TakeOut||(t>0&&(n=e.service_chargeable_subtotal*(t/100)),e.service_charge=Y(n,2),e.grand_total+=e.service_charge,e.grand_total=Y(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=Y(i*r*t/(100+t)+e.service_charge*t/(100+t),2):(e.tax=Y(i*r*t/100+e.service_charge*t/100,2),e.grand_total=Y(e.grand_total+e.tax,2))}calculateCreditDeduction(e){e.minus_credit||(e.minus_credit=0),!(e.minus_credit<=0)&&(e.minus_credit=Y(e.minus_credit),e.minus_credit>e.grand_total&&(e.minus_credit=Y(e.grand_total)),e.grand_total=Y(e.grand_total-e.minus_credit))}calculateTip(e){e.tip>0&&(e.grand_total=Y(e.grand_total+e.tip,2))}calculateTaxSubtotalRatio(e){if(!e.lines)return 1;let t=e.lines.reduce((e,t)=>e+Ir(t,`is_tax_exempt`),0);return!t||e.grand_total===0||e.subtotal===0?1:1-t/e.subtotal}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=Y(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=Y((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:K.Flat,calc_flow:q.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:K.Flat,calc_flow:q.AfterServiceCharge,amount:a}],this.calculate(s,n),s.grand_total>t)throw Error(`Target grand total ${t} is unreachable`);return Y(a,2)}resetInvoiceCalculations(e){e.subtotal=0,e.point_subtotal=0,e.service_chargeable_subtotal=0,e.service_charge=0,e.tax=0,e.bcrs_deposit=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=Y(Math.max(0,e.tender_amount-Math.max(0,t))),t=Y(t-e.tender_amount)):e.payment_method.allow_custom_amount?(t=Y(t-Math.min(e.tender_amount,Math.max(0,t))),e.change_amount=0):(e.change_amount=0,t=Y(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 q.AfterSubtotal:t=e.subtotal;break;case q.AfterServiceCharge:t=e.subtotal+e.service_charge;break;case q.AfterGrantTotal:t=e.grand_total;break;default:t=e.subtotal}n.percentage>0&&(n.amount=Y(t*(n.percentage/100),2)),e.grand_total+=n.amount,e.grand_total=Y(e.grand_total,2)}}},zr=class extends Rr{addItemToLine(e,n,r,i,a,o,s,c,l){let u={...Lr,...o};e.lines??(e.lines=[]);let d=this.findOrCreateLine(e,i,u.quantity,u.price,a,u.remark,s,c,l);return i.type==F.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=O.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=O.InvoiceLine+t(),e.lines.push(r);for(let i of this.getAttachedLines(e,n.uid)){let n=o.cloneDeep(i);n.uid=O.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==K.Percent&&n>100)throw new k(`Discount percent can not be more than 100%`);if(t==K.Flat&&n>e.subtotal)throw new k(`Discount amount can not be more than price`);return e.discount_calc_type=t,t==K.Flat?e.discount_amount=n:e.discount_percent=n,e}minusLineQuantity(e,t,n,r=!1){if(n<=0)throw new k(`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 k(`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,r,i){if(!e||e.length<=0)return e;n=n??0;let a=e.findIndex(e=>e.item_uid===t.item_uid&&e.price===t.price);if(a<0)return e;e[a].quantity+=n;let[s]=e[a].quantity<=0?e.splice(a,1):[];return s?.sent>0&&r&&i&&(r.deleted_modifiers??(r.deleted_modifiers=[])).push({...o.cloneDeep(i),modifiers:[s]}),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,c=!1){let l=this.addItemToLine(e,t,n,r,o,s,c,i,a);return l.is_combo_item=!0,l.combo_line_uid=i,l.combo_group_uid=a,l}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 k(`Line is not a combo`);let r=o.cloneDeep(n);return r.uid=O.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=O.InvoiceLine+t(),i.combo_line_uid=r.uid,i.is_duplicate=!0,e.lines.push(i)}),e}},Br=class extends zr{async addInvoice(e){let t=await this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/add_invoice`,e);if(t.error==A.outdatedInvoice)throw await this.saveOne(t.data),new k(t.error);if(t.error)throw new k(t.error);return t.data}async createInvoice(e,t,n,r=!1){if(e.status=G.Open,e.ref_id||(e.ref_id=await this.getRefId()),!e.call_num){let t=e.ref_id.slice(-3);e.call_num=t===`000`?`777`:t}e.table_name=t.name,e.table_uid=t.uid,t.invoice_uid=e.uid,t.status=P.OPENED,this.sectionItemService.syncInvoiceData(t,e),this.addEmployeeToInvoice(e,n),e.created_at=new Date,e.created_at_timestamp=e.created_at.getTime();let i=(await this.configService.getDefaultOne()).config;e.humanized_created_at=z(e.created_at,i?.order?.datetime_format),t.invoice_created_at=new Date;let a=await this.createKitchenPrintJobs(e),o=await this.createLabelPrintJobs(e),s=await this.createOrderPrintJobs(e),c=this.sortPrintJobsByPrinterSequence([...a,...o,...s]);r&&c.forEach(e=>e.save_only=!0),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=a.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.snapshotSendState(e),g=i?.order?.change_modifier_stock_on_send,_=await this.getItemStockChangeList(e,g);await this.preprocessInvoice(e,g);let v={invoice:e,section_item:t};c.length>0&&(v.print_jobs=c),_.length>0&&(v.items=await this.itemService.getItemsWithStockChanges(_));try{let e=await this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${this.methodName}`,v);if(e.error==A.outdatedInvoice)throw await this.saveOne(e.data),v.invoice=e.data,new k(e.error);if(e.error==A.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),v.section_item=e.data,new k(e.error);return v}catch(t){throw e.kitchen_print_job_uids.length=l,e.label_print_job_uids.length=u,e.order_print_job_uids.length=d,h(),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.snapshotSendState(e),g=(await this.configService.getDefaultOne()).config?.order?.change_modifier_stock_on_send,_=await this.getItemStockChangeList(e,g);await this.preprocessInvoice(e,g);let v={invoice:e,section_item:t};c.length>0&&(v.print_jobs=c),_.length>0&&(v.items=await this.itemService.getItemsWithStockChanges(_));try{let e=await this.http.patch(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/update_invoice`,v);if(e.error==A.outdatedInvoice)throw await this.saveOne(e.data),new k(`${e.error}, system has updated the data, please try again`);if(e.error==A.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),v.section_item=e.data,new k(`${e.error}, system has updated the data, please try again`);return v}catch(t){throw e.kitchen_print_job_uids.length=l,e.label_print_job_uids.length=u,e.order_print_job_uids.length=d,h(),t}}async cancelInvoice(e,t,n){if(e.id_in_server==0&&e.lines.length<=0)throw new k(`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=G.Void,t.invoice_uid=``,t.status=P.CLOSED,this.sectionItemService.reset(t),this.addEmployeeToInvoice(e,n);let r=await this.createReceiptPrintJob(e,B.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==A.outdatedInvoice)throw await this.saveOne(a.data),i.invoice=a.data,new k(a.error);if(a.error==A.outdatedSectionItem)throw await this.sectionItemService.saveOne(a.data),i.section_item=a.data,new k(a.error);return i}async checkInvoice(e,t,n,r){t.status=P.PAYMENT,this.addEmployeeToInvoice(e,n);let i=await this.createReceiptPrintJob(e,B.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.snapshotSendState(e),_=(await this.configService.getDefaultOne()).config?.order?.change_modifier_stock_on_send,v=await this.getItemStockChangeList(e,_);await this.preprocessInvoice(e,_);let y={invoice:e,section_item:t};l.length>0&&(y.print_jobs=l),v.length>0&&(y.items=await this.itemService.getItemsWithStockChanges(v));try{let e=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/check_invoice`,y);if(e.error==A.outdatedInvoice)throw await this.saveOne(e.data),y.invoice=e.data,new k(e.error);if(e.error==A.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),y.section_item=e.data,new k(e.error);return y}catch(t){throw e.kitchen_print_job_uids.length=u,e.label_print_job_uids.length=d,e.order_print_job_uids.length=f,g(),t}}async switchInvoice(e,t,n,r){if(t.uid==n.uid)throw new k(`source and target table can not be the same`);if(t.status!=P.CLOSED)throw new k(`target table is occupied`);if(e.lines==null||!e.id_in_server&&e.lines.length<=0)throw new k(`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=P.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==A.outdatedInvoice)throw await this.saveOne(a.data),i.invoice=a.data,new k(a.error);if(a.error==A.outdatedSourceSectionItem)throw await this.sectionItemService.saveOne(a.data),i.source_section_item=a.data,new k(a.error);if(a.error==A.outdatedTargetSectionItem)throw await this.sectionItemService.saveOne(a.data),i.target_section_item=a.data,new k(a.error);return i}async payInvoice(e,t,n,r,i){e.status=G.Paid,t.invoice_uid=``,t.status=P.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=z(e.paid_at,o),e.payment_has_cash=e.payments?.some(e=>e.payment_method?.is_cash===!0);let s=this.snapshotSendState(e),c=a?.order?.change_modifier_stock_on_send,l=this.mergeStockChangeLists(await this.getItemStockChangeList(e,c),c?[]:await this.getModifierStockChangeList(e)),u=await this.sectionService.getOne(t.section_uid),d=await this.createLabelPrintJobs(e),f=await this.createReceiptPrintJob(e,B.ReceiptPrinter,u?.disable_auto_print_receipt||!1,0,i),p=await this.createKitchenPrintJobs(e),m=await this.createCancelKitchenPrintJobs(e,e.deleted_lines),h=await this.createVoidSlipPrintJobs(e,e.deleted_lines,t),g=await this.createOrderPrintJobs(e),_=[...d,...p,...m,...h,...g];f&&_.push(f);let v=this.sortPrintJobsByPrinterSequence(_);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 y=e.kitchen_print_job_uids.length,b=e.label_print_job_uids.length,x=e.order_print_job_uids.length,S=p.map(e=>e.uid),C=d.map(e=>e.uid),w=g.map(e=>e.uid);S.length>0&&e.kitchen_print_job_uids.push(S),C.length>0&&e.label_print_job_uids.push(C),w.length>0&&e.order_print_job_uids.push(w),await this.preprocessInvoice(e,c);let T={invoice:e,section_item:t,till:n};v.length>0&&(T.print_jobs=v),l.length>0&&(T.items=await this.itemService.getItemsWithStockChanges(l));try{let t=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/pay_invoice`,T);if(t.error==A.outdatedInvoice)throw await this.saveOne(t.data),T.invoice=t.data,new k(`${t.error}, system has updated the data and please try again`);if(t.error==A.outdatedSectionItem)throw await this.sectionItemService.saveOne(t.data),T.section_item=t.data,new k(`${t.error}, system has updated the data and please try again`);if(e.call_num&&a?.ods?.enabled){let t=new Nr;t.order_number=e.call_num,await this.orderDisplayService.addOne(t)}return T}catch(t){throw e.kitchen_print_job_uids.length=y,e.label_print_job_uids.length=b,e.order_print_job_uids.length=x,s(),t}}async directPayInvoice(e,t,n,r,i,a=!1,o=!1){e.status=G.Paid,n!=null&&this.addEmployeeToInvoice(e,n),e.paid_at=new Date;let s=(await this.configService.getDefaultOne()).config,c=s?.order?.datetime_format;if(e.humanized_paid_at=z(e.paid_at,c),e.created_at=new Date,e.created_at_timestamp=e.created_at.getTime(),e.humanized_created_at=z(e.created_at,c),e.ref_id||(e.ref_id=await this.getRefId()),!e.call_num){let t=e.ref_id.slice(-3);e.call_num=t===`000`?`777`:t}e.payment_has_cash=e.payments?.some(e=>e.payment_method?.is_cash===!0);let l=this.snapshotSendState(e),u=s?.order?.change_modifier_stock_on_send,d=this.mergeStockChangeLists(await this.getItemStockChangeList(e,u),u?[]:await this.getModifierStockChangeList(e)),f=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,p=(f?.section_uid?await this.sectionService.getOne(f.section_uid):null)?.disable_auto_print_receipt||!1,m=null,h=null;if(r&&r.type==B.KioskPrinter){let t=!!s?.kiosk?.disable_receipt_printer_receipt||p;m=await this.createReceiptPrintJob(e,B.ReceiptPrinter,t),h=await this.createReceiptPrintJob(e,B.KioskPrinter,!1,0,r,i)}else m=await this.createReceiptPrintJob(e,B.ReceiptPrinter,p||o,0,r);let g=await this.createLabelPrintJobs(e),_=await this.createKitchenPrintJobs(e,a),v=await this.createOrderPrintJobs(e),y=[...g,..._,...v];m&&y.push(m),h&&y.push(h);let b=this.sortPrintJobsByPrinterSequence(y),x=_.map(e=>e.uid),S=g.map(e=>e.uid),C=v.map(e=>e.uid);x.length>0&&(e.kitchen_print_job_uids=[x]),S.length>0&&(e.label_print_job_uids=[S]),C.length>0&&(e.order_print_job_uids=[C]),await this.preprocessInvoice(e,u);let w={invoice:e,till:t};b.length>0&&(w.print_jobs=b),d.length>0&&(w.items=await this.itemService.getItemsWithStockChanges(d));try{let t=await this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/direct_pay_invoice`,w);if(t.error==A.outdatedInvoice)throw await this.saveOne(t.data),w.invoice=t.data,new k(t.error);if(e.call_num&&s?.ods?.enabled){let t=new Nr;t.order_number=e.call_num,await this.orderDisplayService.addOne(t)}return w}catch(e){throw l(),e}}async voidInvoice(e,t,n,r){n&&(e.etc.void_reason=n);let i=e.status,a=this.snapshotSendState(e);e.status=G.Void,e.voided_at=new Date;let o=(await this.configService.getDefaultOne()).config?.order?.datetime_format;e.humanized_voided_at=z(e.voided_at,o),t&&(t.deleted_at=new Date),this.addEmployeeToInvoice(e,r);let s=(await this.configService.getDefaultOne()).config,c=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,l=await this.createReceiptPrintJob(e,B.ReceiptPrinter,!0),u=[],d=[],f=[...e.lines,...(e.deleted_lines||[]).filter(e=>(e.sent||0)-(e.stock_reverted||0)>0)];s.kitchen.print_cancel_whole_invoice&&(u=await this.createCancelKitchenPrintJobs(e,f)||[]),s.receipt.print_cancel_whole_invoice&&(d=await this.createVoidSlipPrintJobs(e,f,c)||[]);let p=[...u,...d];l&&p.push(l);let m={invoice:e,till:t};p.length>0&&(m.print_jobs=p);let h=await this.tillService.db.table(`tills`).where({invoice_uid:e.uid}).toArray(),g=h.filter(e=>e.type===M.CashInvoice&&!e.deleted_at).reduce((e,t)=>e+t.amount,0);if(g>0){let t=new N;t.type=M.CashInvoice,t.amount=-g,t.invoice_uid=e.uid,t.shift_uid=h[0]?.shift_uid,t.user_uid=r?.uid||h[0]?.user_uid,m.till=t}c&&c.status!=P.CLOSED&&c.invoice_uid===e.uid&&(c.invoice_uid=``,c.status=P.CLOSED,m.section_item=c);let _=await this.getItemStockChangeList(e,s?.order?.change_modifier_stock_on_send,!0),v=i==G.Paid&&!s?.order?.change_modifier_stock_on_send?this.mergeStockChangeLists(_,await this.getModifierStockChangeList(e,!0)):_;v.length>0&&(m.items=await this.itemService.getItemsWithStockChanges(v));try{let e=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/void_invoice`,m);if(e.error==A.outdatedInvoice)throw await this.saveOne(e.data),m.invoice=e.data,new k(e.error);return m}catch(t){throw e.status=i,a(),t}}async duplicateInvoice(e,n){if(e.status!=G.Paid)throw new k(`invalid invoice status`);let r=o.cloneDeep(e);if(r.etc.is_duplicate=!0,r.etc.duplicated_from_uid=r.uid,r.uid=O.Invoice+t(),r.status=G.Open,r.ref_id=await this.getRefId(),this.addEmployeeToInvoice(r,n),r.lines)for(let e of r.lines)e.uid=O.InvoiceLine+t();if(r.payments)for(let e of r.payments)e.uid=O.Payment+t();return r}async reprintReceipt(e,n=!1,r){if(!e?.receipt_print_job_uid)throw new k(`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 k(`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 k(`Receipt printer not found`);return i=this.printJobService.replacePrinter(i,a),i.uid=O.PrintJob+t(),i.save_only=n,i.status=Je.Queued,i.print_times=1,i.printed=0,i.retries=0,i.created_at=new Date,i.updated_at=i.created_at,i.created_at_timestamp=i.created_at.getTime(),await this.printJobService.addOne(i),i}async printLastKitchenSlips(e){let n=await this.getOne(e);if(!n)throw new k(`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 k(`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 k(`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=O.PrintJob+t(),r.save_only=!1,r.status=Je.Queued,r.print_times=1,r.printed=0,r.retries=0,r.created_at=new Date,r.updated_at=r.created_at,r.created_at_timestamp=r.created_at.getTime(),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 k(`Invoice not found`);let r=n.order_print_job_uids?.[n.order_print_job_uids.length-1]||[];if(r.length===0)throw new k(`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 k(`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=O.PrintJob+t(),r.save_only=!1,r.status=Je.Queued,r.print_times=1,r.printed=0,r.retries=0,r.created_at=new Date,r.updated_at=r.created_at,r.created_at_timestamp=r.created_at.getTime(),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=q.AfterSubtotal,i=`custom`,a={}){if(e.discounts||(e.discounts=[]),t==K.Percent&&n>100)throw new k(`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==K.Flat?o.amount=n:o.percent=n,e.discounts.push(o),e}addCouponToInvoice(e,t,n=q.AfterSubtotal){e.discounts||(e.discounts=[]);let r=new gt;if(r.calc_type=t.coupon.discount_calc_type==1?K.Flat:K.Percent,r.calc_flow=n,r.name=t.coupon.name,r.calc_type==K.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 k(`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 k(`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 k(`Source invoice has no nothing to merge`);if(t.lines.some(e=>e.quantity!=e.sent))throw new k(`Please send first before merging`);if(!await this.getOne(e.uid))throw new k(`Target invoice not found`);if(!await this.getOne(t.uid))throw new k(`Source invoice not found`);if(e?.id_in_server==0)throw new k(`Target invoice is not synced to server`);if(t?.id_in_server==0)throw new k(`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!=G.Paid)throw new k(`invalid invoice status`);if(!t||t.length<1)throw new k(`invalid options`);for(let n of t){let t=e.payments.find(e=>e.uid==n.source_payment.uid);if(!t)throw new k(`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==B.ReceiptPrinter||t==B.CheckPrinter){let n=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,r=t==B.ReceiptPrinter?n?.receipt_printer_uid:n?.check_printer_uid;r&&(o=await this.printerService.getOne(r)),o||(o=t==B.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 k(`Print template not found`);t==B.ReceiptPrinter&&!s.config?.receipt?.enabled&&(n=!0);let l=await this.printTemplateService.renderPrintTemplate(e,s.config,c,{...new U,printer_name:o.name}),u=new H(o,l,n,r);return t!=B.ReceiptPrinter&&(u.printer_type=t),o.connection_type!=Ke.ETHERNET&&(u.connection_type=o.connection_type),t==B.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,B.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 H(t,await this.printTemplateService.renderPrintTemplate(l,n,a,{...new U,printer_name:t.name}),!1,t.print_times);r.push(i)}else{l.lines=c;let e=new H(t,await this.printTemplateService.renderPrintTemplate(l,n,a,{...new U,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,B.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 H(i,await this.printTemplateService.renderPrintTemplate(u,t,s,{...new U,printer_name:i.name}),!1,i.print_times);n.push(d)}return n}async createFullOrderDocketPrintJob(e){let t=(await this.configService.getDefaultOne()).config;if(!t.receipt.print_docket)return[];let n=(e.lines||[]).filter(e=>e.sent>0).map(e=>({...o.cloneDeep(e),quantity:e.sent}));if(n.length===0)return[];let r=[],i=new Set;for(let e of n)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=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,c=await this.printerService.getPrintersByUids(a);for(let i of c){if(s?.order_printer_uids?.length>0&&!s.order_printer_uids.includes(i.uid))continue;let a=await this.printTemplateService.getOneByParams({uid:i.print_template_uid});if(!a)continue;let c=n.filter(e=>e.item?.order_printers_uids?.includes(i.uid));if(c.length===0)continue;let l=this.getSortedLines(c.map(e=>o.cloneDeep(e)),i);this.sortLineModifiers(l);let u=o.cloneDeep(e);u.lines=l;let d=new H(i,await this.printTemplateService.renderPrintTemplate(u,t,a,{...new U,printer_name:i.name}),!1,i.print_times);r.push(d)}return r}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(i.disable_cancel_print||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 H(i,await this.printTemplateService.renderPrintTemplate(u,r,a,{...new U,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,B.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 H(e,new R,!1,e.print_times);c.commands=o,n.push(c)}return n}filterLinesAndPrintersToPrint(e,t){let n;switch(t){case B.KitchenPrinter:n=`kitchen_printers_uids`;break;case B.OrderPrinter:n=`order_printers_uids`;break;case B.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==B.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){if(t.disable_cancel_print)continue;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 H(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 H(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))}snapshotSendState(e){let t=(e.lines??[]).map(e=>({l:e,sent:e.sent,mods:e.modifiers?.map(e=>({m:e,sent:e.sent}))})),n=[...e.deleted_lines??[],...(e.deleted_modifiers??[]).flatMap(e=>e.modifiers??[])].map(e=>({x:e,stock_reverted:e.stock_reverted}));return()=>{t.forEach(({l:e,sent:t,mods:n})=>{e.sent=t,n?.forEach(({m:e,sent:t})=>e.sent=t)}),n.forEach(({x:e,stock_reverted:t})=>e.stock_reverted=t)}}async preprocessInvoice(e,t){if(e.lines){for(let n of e.lines)if(n.sent=n.quantity,t)for(let e of n.modifiers||[])e.sent=e.quantity}return e}rebaseUnsentLines(e,t){if(t?.uid!==e.uid||!t?.lines?.length)return!1;let n=!1;for(let r of t.lines){let t=r.quantity-(r.sent||0);if(t<=0)continue;let i=e.lines?.find(e=>e.uid===r.uid);i?(i.sent??0)>=i.quantity&&(i.quantity+=t,n=!0):r.sent||(r.selected=!1,(e.lines??(e.lines=[])).push(r),n=!0)}return n}addInvoiceCharge(e,t,n,r,i=q.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}async getItemStockChangeList(e,t,n=!1){let r=new Map,i=t?await this.buildModifierIndex():null,a=(e,t)=>{if(i)for(let n of e.modifiers||[]){let a=t(n),o=i.uidToSku.get(n.item_uid);if(a)for(let{itemUid:t,modUid:s}of o?i.skuToCopies.get(o)||[]:[{itemUid:e.item_uid,modUid:n.item_uid}]){let e=r.get(t)||new pe(t),n=e.modifiers.find(e=>e.item_uid===s);n?n.quantity+=a:e.modifiers.push({item_uid:s,quantity:a}),r.set(t,e)}}};for(let t of e.lines||[]){a(t,e=>(t.sent||0)*(e.sent||0)-(n?0:t.quantity*e.quantity));let e=n?-(t.sent||0):t.quantity-(t.sent||0);if(e===0)continue;let i=r.get(t.item_uid)||new pe(t.item_uid);i.quantity-=e,r.set(t.item_uid,i)}for(let t of e.deleted_lines||[]){let e=(t.sent||0)-(t.stock_reverted||0);if(e<=0)continue;a(t,t=>e*(t.sent||0));let n=r.get(t.item_uid)||new pe(t.item_uid);n.quantity+=e,r.set(t.item_uid,n),t.stock_reverted=t.sent}for(let t of e.deleted_modifiers||[])a(t,e=>{let n=(t.sent||0)*((e.sent||0)-(e.stock_reverted||0));return e.stock_reverted=e.sent,n});return Array.from(r.values())}async buildModifierIndex(){let e=new Map,t=new Map;for(let n of await this.itemService.getAll())for(let r of n.modifiers||[]){if(!r.sku)continue;e.set(r.uid,r.sku);let i=t.get(r.sku)||[];i.push({itemUid:n.uid,modUid:r.uid}),t.set(r.sku,i)}return{uidToSku:e,skuToCopies:t}}async getModifierStockChangeList(e,t=!1){if(!e.lines||e.lines.length===0)return[];let{uidToSku:n,skuToCopies:r}=await this.buildModifierIndex(),i=new Map;for(let a of e.lines)if(!(!a.modifiers||a.modifiers.length===0))for(let e of a.modifiers){let o=t?a.quantity*e.quantity:-(a.quantity*e.quantity),s=n.get(e.item_uid),c=s?r.get(s)||[]:[{itemUid:a.item_uid,modUid:e.item_uid}];for(let{itemUid:e,modUid:t}of c){let n=i.get(e)||new pe(e),r=n.modifiers.find(e=>e.item_uid===t);r||(r={item_uid:t,quantity:0},n.modifiers.push(r)),r.quantity+=o,i.set(e,n)}}return Array.from(i.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 pe(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}},Vr=class extends Br{},Hr=class extends J{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}},Ur=class extends J{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 k(`Password is incorrect`)}else throw new k(`User not found`)}catch(e){throw e instanceof k?e:new k(`Unexpected error, login failed`)}}async createEmployee(e){try{if(await this.getOne(e.uid))throw new k(`User already exists`);return e.password&&(e.password=await p.hash(e.password,12)),this.addOne(e)}catch(e){throw e instanceof k?e:new k(`Unexpected error, creating employee failed`)}}async changePassword(e){try{return await p.hash(e,12)}catch{throw new k(`Unexpected error, changing password failed`)}}},Wr=class extends J{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=O.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 k(`Item does not have any modifier categories`);let n=e.modifier_categories.findIndex(e=>e.uid===t.uid);if(n===-1)throw new k(`Modifier category not found`);return e.modifier_categories[n]=t,e}async removeModifierCategory(e,t){if(!e.modifier_categories)throw e.modifier_categories=[],new k(`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=O.ItemModifier+t(),e.modifiers.push(n),e}async updateModifier(e,t){if(!e.modifiers)throw e.modifiers=[],new k(`Item does not have any modifiers`);let n=e.modifiers.findIndex(e=>e.uid===t.uid);if(n===-1)throw new k(`Modifier not found`);return e.modifiers[n]=t,e}async removeModifier(e,t){if(!e.modifiers)throw e.modifiers=[],new k(`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 k(`Item does not have any modifier categories`);if(!e.modifier_categories.find(e=>e.uid===n))throw new k(`Modifier category not found`);let r=e.modifiers.find(e=>e.uid===t);if(!r)throw new k(`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 an({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 k(`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 k(`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 k(`Item not found`);let r=Number(n.stock);return n.stock=(isNaN(r)?0:r)+t,this.updateOne(n.id_in_server,n)}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}async buildModifierIndex(){let e=new Map,t=new Map;for(let n of await this.getAll())for(let r of n.modifiers||[]){if(!r.sku)continue;e.set(r.uid,r.sku);let i=t.get(r.sku)||[];i.push({itemUid:n.uid,modUid:r.uid}),t.set(r.sku,i)}return{uidToSku:e,skuToCopies:t}}async changeModifiersStockBySku(e,t){if(!e)return[];let{skuToCopies:n}=await this.buildModifierIndex(),r=n.get(e);if(!r?.length)return[];let i=new Map;for(let{itemUid:e,modUid:n}of r){let r=i.get(e);if(!r){let t=await this.getOne(e);if(!t)continue;r=t,i.set(e,r)}let a=r.modifiers?.find(e=>e.uid===n);a&&(a.stock=(Number(a.stock)||0)+t)}return Array.from(i.values())}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){return hn(e)}async cloneModifiers(e,n){let r=o.cloneDeep(e);r.uid=O.ItemModifierCategory+t();let i=[];for(let e of n){let n=o.cloneDeep(e);n.uid=O.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 k(`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!==F.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}},Gr=class extends J{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 k(`Category does not have any subcategories`);let n=e.subcategories.findIndex(e=>e.uid===t.uid);if(n===-1)throw new k(`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 k(`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}},Kr=class extends J{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 zt,product:()=>new Rt,till:()=>new Bt,report:()=>new Vt,receipt:()=>new Ht,kitchen:()=>new Ut,kds:()=>new Wt,label:()=>new Gt,order:()=>new Kt,payment:()=>new Jt,user:()=>new Yt,tax:()=>new Xt,rounding:()=>new $t,charges:()=>new Zt,currency:()=>new Qt,inventory:()=>new en,pax_config:()=>new tn,gto:()=>new nn,cash_drawer:()=>new rn,marketing:()=>new Mt})}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=An(e);return await this.http.post(`api/v5/merchants/`+this.options.merchant_uid+`/upload-image`,new an({base64:await jn(e),name:t,extension:n})),{file_url:`${this.options.base_url}images/${t}.${n}`,thumbnail_url:`${this.options.base_url}images/${t}.thumbnail.${n}`}}},qr=class extends J{constructor(e,t,n,r=`sections`,i=`section`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Jr=class extends J{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||``}}},Yr=class extends J{constructor(e,t,n,r=`products`,i=`product`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Xr=class extends J{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 Zr(e,t,n)}async cashIn(e,t,n){let r=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status===j.Open).first();if(!r)throw new k(`No opening shift found`);let i=new N;return i.amount=e,i.type=M.CashIn,i.user_uid=r.user_uid,i.shift_uid=r.uid,i.note=t,n&&(i.payment_method_uid=n.uid,i.payment_method_code=n.payment_method_code,i.payment_method_name=n.name,i.payment_method=n),this.tillService.addOne(i)}async cashOut(e,t,n){let r=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status===j.Open).first();if(!r)throw new k(`No opening shift found`);let i=new N;return i.amount=e,i.type=M.CashOut,i.user_uid=r.user_uid,i.shift_uid=r.uid,i.note=t,n&&(i.payment_method_uid=n.uid,i.payment_method_code=n.payment_method_code,i.payment_method_name=n.name,i.payment_method=n),this.tillService.addOne(i)}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==j.Open).first();if(!n)throw new k(`No opening shift found`);return n.declared_amount=e,n.ended_at=new Date,n.user_uid=t,n.status=j.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==j.Open).first();if(r)throw new k(`shift is already opened shift at ${r.started_at}`);let i=new le;if(i.started_at=new Date,i.user_uid=t,i.status=j.Open,await this.addOne(i),await this.insertIfNotExists(i),e>0){let r=new N;r.amount=e,r.type=M.OpenDeposit,r.user_uid=t,r.amount=e,r.shift_uid=i.uid,r.note=n,await this.tillService.addOne(r),await this.tillService.insertIfNotExists(r)}return console.log(`open shift end`),i}},Zr=class extends J{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 N;return a.shift_uid=t,a.user_uid=n,a.note=r,a.invoice_uid=i,a.amount=Y(e.filter(e=>e.payment_method.is_cash).map(e=>e.tender_amount-e.change_amount).reduce((e,t)=>e+t,0)),a.type=M.CashInvoice,a}async autoQuery(e,t){return await this.http.get(`sapi/v5/merchants/${this.options.merchant_uid}/${this.moduleName}`,{params:e.build(),...t})}},Qr=class extends J{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`,{headers:{"Cache-Control":`no-cache, no-store`}}),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}},$r=class extends J{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=Y(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}},ei=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 k(`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 k(`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}},ti=class extends J{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 Vr(e,t,n,`invoices`,`invoice`),this.tillService=new Zr(e,t,n,`tills`,`till`),this.paymentService=new $r(e,t,n,`payments`,`payment`),this.printerService=new kn(e,t,n,`printers`,`printer`),this.printTemplateService=new ii(e,t,n,`print_templates`,`print_template`),this.printJobService=new ni(e,t,n,`print_jobs`,`print_job`),this.configService=new Kr(e,t,n,`configs`,`config`)}async syncStandardReports(){let e=await this.getDefaultOne();e||(e=new yn);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 k(`No default receipt printer found`);let n=await this.printTemplateService.getOneByParams({report_code_name:e.report_code_name});if(!n)throw new k(`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 H(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 bn;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 i=new Date(e.start_datetime).getTime(),a=new Date(e.end_datetime).getTime(),o=36e5,s=new f().addParam(`created_at`,`GreaterThanOrEqualTo`,new Date(i-o).toISOString()).addParam(`created_at`,`LessThanOrEqualTo`,new Date(a+o).toISOString()),c=e.shift_uid||e.report_code_name==`till_report`?((await this.tillService.autoQuery(s,{timeout:6e5})).results||[]).filter(t=>t.deleted_at==null&&(e.shift_uid?t.shift_uid==e.shift_uid:new Date(t.created_at).getTime()>=i&&new Date(t.created_at).getTime()<=a)):[],l=e=>e.payment_method?e.payment_method.is_cash:!0,u=e=>Y(e.reduce((e,t)=>e+t.amount,0)),d=e=>{let t=new Map;for(let n of e){let e=t.get(n.payment_method_code)??Object.assign(new wn,{code:n.payment_method_code,name:n.payment_method_name});e.total=Y(e.total+n.amount),e.count++,t.set(n.payment_method_code,e)}return[...t.values()]},p=c.filter(e=>e.type==M.CashIn&&l(e)),m=c.filter(e=>e.type==M.CashOut&&l(e)),h=c.filter(e=>e.type==M.CashIn&&!l(e)),g=c.filter(e=>e.type==M.CashOut&&!l(e)),_=(e,t)=>e.map(e=>({type:e.type,label:t,created_at:new Date(e.created_at).toISOString(),time:z(new Date(e.created_at),`MM/DD HH:mm`),amount:e.type==M.CashOut?-e.amount:e.amount,note:e.note||``,payment_method_code:e.payment_method_code,payment_method_name:e.payment_method_name,invoice_uid:e.invoice_uid||``,ref_id:``})),v=(e,t)=>e.created_at.localeCompare(t.created_at),y=r.drawer_summary;y.open_amount=u(c.filter(e=>e.type==M.OpenDeposit)),y.pay_in_total=u(p),y.pay_in_count=p.length,y.pay_out_total=u(m),y.pay_out_count=m.length,y.cash_invoice_total=u(c.filter(e=>e.type==M.CashInvoice)),y.cash_invoice_count=c.filter(e=>e.type==M.CashInvoice).length,y.drawer_amount=Y(y.open_amount+y.pay_in_total+y.cash_invoice_total-y.pay_out_total),y.difference=e.shift_uid?Y(y.drawer_amount-y.declared_amount):0,y.entries=[..._(c.filter(e=>e.type==M.OpenDeposit),`OPEN`),..._(p,`CASH IN`),..._(c.filter(e=>e.type==M.CashInvoice),`CASH SALE`),..._(m,`CASH OUT`)].sort(v);let b=r.non_cash_till_summary;b.pay_in_total=u(h),b.pay_in_count=h.length,b.pay_out_total=u(g),b.pay_out_count=g.length,b.pay_in_by_method=d(h),b.pay_out_by_method=d(g),b.entries=[..._(h,`PAY IN`),..._(g,`PAY OUT`)].sort(v),r.start_datetime=new Date(e.start_datetime).toISOString(),r.end_datetime=new Date(e.end_datetime).toISOString(),r.humanized_start_datetime=z(new Date(e.start_datetime),t),r.humanized_end_datetime=z(new Date(e.end_datetime),t),r.humanized_printed_datetime=z(new Date,t),r.printed_time=z(new Date,`MM/DD HH:mm`);let x=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),S=(await this.invoiceService.autoQuery(x,{timeout:6e5})).results||[],C=new Map(S.map(e=>[e.uid,e.ref_id]));for(let e of r.drawer_summary.entries)e.type==M.CashInvoice&&(e.ref_id=C.get(e.invoice_uid)||``);return this.processReportInvoicesData(r,S,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===K.Percent?`${Y(i*100)}% Discount`:`${n}${Y(r)} Discount`),f=(e,t,n,r,i,a)=>{let o=u(t,n,n===K.Percent?i:r),s=e.get(o);s?(s.count++,s.total=Y(s.total+a)):e.set(o,{name:t,alias:d(t,n,r,i),calc_type:n,amount:r,percent:i,count:1,total:Y(a)})};t.forEach(t=>{if(t.status==G.Paid){t.ref_id&&((!e.first_ref_id||t.ref_id<e.first_ref_id)&&(e.first_ref_id=t.ref_id),t.ref_id>e.last_ref_id&&(e.last_ref_id=t.ref_id)),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||W.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=Y(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=Y(n.total_amount+e.price*e.quantity)):(n=new Dn,n.item=e.item,n.quantity=e.quantity,n.total_amount=Y(e.price*e.quantity),i.set(t,n))})):(a=new En,a.item=t.item,a.quantity=t.quantity,a.total_amount=Y(t.subtotal),a.modifiers=[],t.modifiers&&t.modifiers.length>0&&t.modifiers.forEach(e=>{let t={item:e.item,quantity:e.quantity,total_amount:Y(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=Y(r.total_amount+e.price*e.quantity)):(r=new Dn,r.item=e.item,r.quantity=e.quantity,r.total_amount=Y(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=Y(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:Y(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===K.Percent?e.percent_amount:e.amount;f(t?c:s,e.name||``,e.calc_type,e.amount,e.percent,n)})}t.status==G.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==G.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 On,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=Y(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=Y(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=Y(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:Y(e.total)})),e.sales_summary.paid_invoice_total=Y(e.sales_summary.paid_invoice_total),e.sales_summary.sales_total=Y(e.sales_summary.sales_total),e.sales_summary.rounding_total=Y(e.sales_summary.rounding_total),e.sales_summary.tax_total=Y(e.sales_summary.tax_total),e.sales_summary.service_charge_total=Y(e.sales_summary.service_charge_total),e.sales_summary.discount_total=Y(e.sales_summary.discount_total),e.sales_summary.foc_sales_total=Y(e.sales_summary.foc_sales_total),e.sales_summary.foc_rounding_total=Y(e.sales_summary.foc_rounding_total),e.sales_summary.foc_tax_total=Y(e.sales_summary.foc_tax_total),e.sales_summary.foc_service_charge_total=Y(e.sales_summary.foc_service_charge_total),e.sales_summary.void_invoice_total=Y(e.sales_summary.void_invoice_total),e.sales_summary.pax_sales_total=Y(e.sales_summary.pax_sales_total),e.loyalty_program_summary.add_credit_total=Y(e.loyalty_program_summary.add_credit_total),e.loyalty_program_summary.topup_paid_total=Y(e.loyalty_program_summary.topup_paid_total),e.loyalty_program_summary.rewarded_credit_total=Y(e.loyalty_program_summary.rewarded_credit_total),e.loyalty_program_summary.minus_credit_total=Y(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}},ni=class extends J{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}},ri=class extends J{constructor(e,t,n,r=`menus`,i=`menu`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},ii=class extends J{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:B.ReceiptPrinter})){let e=new V;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=B.ReceiptPrinter,await this.addOne(e),console.log(`Default Receipt Template added`)}if(!await this.getOneByParams({printer_type:B.CheckPrinter})){let e=new V;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=B.CheckPrinter,await this.addOne(e),console.log(`Default Check Template added`)}if(!await this.getOneByParams({printer_type:B.OrderPrinter})){let e=new V;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=B.OrderPrinter,await this.addOne(e),console.log(`Default Order Template added`)}if(!await this.getOneByParams({printer_type:B.KitchenPrinter})){let e=new V;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=B.KitchenPrinter,await this.addOne(e),console.log(`Default Kitchen Template added`)}if(!await this.getOneByParams({printer_type:B.KioskPrinter})){let e=new V;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=B.KioskPrinter,await this.addOne(e),console.log(`Default Kiosk Template added`)}if(!await this.getOneByParams({printer_type:B.KitchenDisplayPrinter})){let e=new V;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=B.KitchenDisplayPrinter,await this.addOne(e),console.log(`Default Kitchen Display Template added`)}if(!await this.getOneByParams({printer_type:B.LabelPrinter})){let e=new V;e.commands=await this.getPrintTemplate(`tspl_cmds`),e.name=`Default Label Template`,e.printer_type=B.LabelPrinter,await this.addOne(e)}if(!await this.getOneByParams({printer_type:B.QrCodePrinter})){let e=new V;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=B.QrCodePrinter,await this.addOne(e)}if(!await this.getOneByParams({printer_type:B.EventPrinter})){let e=new V;e.name=`Default Event Template`,e.header=await this.getPrintTemplate(`eht`),e.body=await this.getPrintTemplate(`ebt`),e.footer=await this.getPrintTemplate(`eft`),e.printer_type=B.EventPrinter,await this.addOne(e)}if(!await this.getOneByParams({report_code_name:`sales_summary_report`})){let e=new V;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 V;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 V;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 V;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`)}if(!await this.getOneByParams({report_code_name:`till_report`})){let e=new V;e.name=`Till Report`,e.body=await this.getPrintTemplate(`trbt`),e.header=await this.getPrintTemplate(`trht`),e.footer=await this.getPrintTemplate(`trft`),e.report_code_name=`till_report`,await this.addOne(e),console.log(`Till Report Template added`)}}async renderPrintTemplate(e,t,n,r=new U){let i=new R;n.printer_type==B.KitchenPrinter||n.printer_type==B.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=z(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 U){let i=new R,a=new Ze;return a.report_data=e,a.config=t,a.normalized_printed_at=z(a.printed_at,t?.order?.datetime_format),i.codepage=n.codepage||I.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 U){let r=new R;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:I.English,GR:I.Greek,DE:I.WesternEurope,LT:I.BalticRim,PL:I.CentralEurope,RU:I.Cyrillic,TR:I.Turkish,EU:I.MultilingualLatin1WithEuro,PT:I.Portuguese,IS:I.Icelandic,IL:I.Hebrew,CA:I.FrenchCanadian,EG:I.Arabic,NO:I.Nordic,BY:I.Russian,MK:I.ModernGreek,CN:I.SimplifiedChinese,KR:I.Korean,TW:I.TraditionalChinese,FR:I.WesternEuropeanLatin,AE:I.ArabicISO,JP:I.Japanese,CZ:I.CentralEuropeanLatinWindows,BG:I.CyrillicWindows,ES:I.WesternEuropeanLatinWindows,CY:I.GreekWindows,AZ:I.TurkishWindows,PS:I.HebrewWindows,SA:I.ArabicWindows,LV:I.BalticWindows,VN:I.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}}},ai=class extends J{constructor(e,t,n,r=`storages`,i=`storage`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},oi=class extends J{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}},si=class extends J{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 ci(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}var li=class{constructor(e){this.db=e}flatten(e){let t={};for(let[n,r]of Object.entries(e))(typeof r!=`object`||!r||r instanceof Date)&&(t[n]=r);return t}async getTableStats(){let e=[];for(let t of this.db.tables){let n=await t.count().catch(()=>-1),r=await t.orderBy(`created_at`).reverse().limit(5).toArray().catch(()=>[]);e.push({name:t.name,count:n,latestRecords:r.map(e=>this.flatten(e))})}return{tables:e.sort((e,t)=>t.count-e.count),totalCount:e.reduce((e,t)=>e+t.count,0)}}};const ui=new Map([[`Item`,Wr],[`Section`,qr],[`SectionItem`,Jr],[`Category`,Gr],[`Config`,Kr],[`Shift`,Xr],[`Till`,Zr],[`Employee`,Ur],[`PaymentMethod`,Qr],[`Invoice`,Vr],[`Report`,ti],[`Printer`,kn],[`PrintJob`,ni],[`PrintTemplate`,ii],[`EmployeeRole`,Hr],[`OrderDisplay`,Fr],[`Storage`,ai],[`Menu`,ri],[`StockLog`,oi],[`Appointment`,si]]),Z=`uid, updated_at, created_at, deleted_at, _timestamp, id_in_server, created_at_timestamp`,di=`${Z}, sequence`,fi=`${di}, status`,pi=`${Z}, till_type, shift_uid, invoice_uid`,mi=`${di}, payment_method_code, is_disabled`,hi=`${Z}, type, status, table_uid`,gi=`${di}, name, barcode, codename`,_i=`${Z}, status, printer_type, connection_type, protocol, save_only, device_uid_to_print`,vi=`${Z}, name, printer_type`,yi=`${Z}, order_number, status`,bi=`${Z}, model`,xi={items:gi,sections:di,section_items:di,categories:di,shifts:fi,tills:pi,employees:`${Z}, role_uid`,payment_methods:mi,invoices:hi,configs:Z,reports:Z,printers:Z,print_jobs:_i,print_templates:vi,employee_roles:`${Z}, name, is_default`,order_displays:yi,storages:bi,menus:Z,stock_logs:`${Z}, entity_type, entity_uid, type`,appointments:`${Z}, status, scheduled_at, employee_uid, customer_id`};var Q=function(e){return e.DISCONNECTED=`disconnected`,e.CONNECTED=`connected`,e.ERROR=`error`,e}(Q||{}),Si=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`,Q.DISCONNECTED),this.mode=e.mode,this.http=ci(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(xi),this.status=Q.CONNECTED}catch(e){this.status=Q.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==Q.ERROR)throw Error(`Database connection error`);for(;this.status==Q.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==Q.ERROR)throw Error(`Database connection error`);for(;this.status==Q.DISCONNECTED;)await new Promise(e=>setTimeout(e,100));try{let t=ui.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)}}updateToken(e){this.http.defaults.headers.Authorization=`Bearer ${e}`}get httpClient(){return this.http}async dispose(){await this.dataSource?.close(),this.status=Q.ERROR}getDiagnosticsService(){if(this.status!=Q.CONNECTED)throw Error(`Database connection error`);return new li(this.dataSource)}};async function Ci(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 wi={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`]},v7:{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`,`Barcode`]},v8:{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`,`Barcode`,`Original Price`]},v9:{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`,`Barcode`,`Original Price`,`Codename`]},v10:{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`,`Barcode`,`Original Price`,`Codename`,`Config`]},v11:{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.Barcode.Original Price.Codename.Config.Exclude Auto Reset Sold Out.Is Service Charge Exempt.Is Tax Exempt.Is Pax Linked.Is Point Reward Exempt.Is Credit Reward Exempt`.split(`.`)}},Ti=[`category`,`subcategory`,`product`,`modifier_category`,`modifier`,`combo`,`combo_group`,`combo_item`];function Ei(e,t,n=`export.csv`){return Oi(Mi(e,t,e=>e.code||``,e=>e.plu||``))}async function Di(e,t){let n=new Map,r=new Map;for(let t of e){let e=t.code||(t.name?await Ci(`${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 Ci(`${e.name}|${t.toFixed(2)}`):``);i.set(e,n),e.uid&&a.set(e.uid,n)}return{blob:Oi(Mi(e,t,e=>n.get(e)||``,e=>i.get(e)||``)),productPluByUid:a,categoryCodeByUid:r}}function Oi(e){let t=Pi(e);return new Blob([``+t],{type:`text/csv;charset=utf-8;`})}function ki(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 Ai(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e);return t.length===0?``:t.map(([e,t])=>`${e}:${t}`).join(`|`)}function ji(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 Mi(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:Ai(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)Ni(i,e,r);for(let e of t.subcategories){i.push({type:`subcategory`,name:e.name,sku:``,sequence:e.sequence,name_translations:Ai(e.name_translations)});let t=n.get(e.uid)||[];for(let e of t)Ni(i,e,r)}}else for(let e of o)Ni(i,e,r)}return i}function Ni(e,t,n){let r=t.type===F.Combo,i=n(t);if(e.push({type:r?`combo`:`product`,name:t.name,sku:t.sku||``,price:t.price,stock:ki(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:Ai(t.name_translations),item_uid:t.uid,prices:t.prices?.length?t.prices:void 0,plu:i,barcode:t.barcode||``,original_price:t.original_price||void 0,codename:t.codename||``,config:t.config,exclude_auto_reset_sold_out:t.exclude_auto_reset_sold_out,is_service_charge_exempt:t.is_service_charge_exempt,is_tax_exempt:t.is_tax_exempt,is_pax_linked:Number(t.is_pax_linked)||void 0,is_point_reward_exempt:t.is_point_reward_exempt,is_credit_reward_exempt:t.is_credit_reward_exempt}),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:ki(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:Ai(t.name_translations),prices:t.prices?.length?t.prices:void 0,original_price:t.original_price||void 0,config:t.config,exclude_auto_reset_sold_out:t.exclude_auto_reset_sold_out})}}}function Pi(e){let t=[wi.v11.headers.join(`,`)];for(let n of e)try{let e=n.prices?.length?`"${JSON.stringify(n.prices).replace(/"/g,`""`)}"`:``,r=n.config&&Object.keys(n.config).length?`"${JSON.stringify(n.config).replace(/"/g,`""`)}"`:``,i=[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,`""`)}"`:``,n.barcode?`"${n.barcode.replace(/"/g,`""`)}"`:``,n.original_price===void 0?``:n.original_price.toString(),n.codename?`"${n.codename.replace(/"/g,`""`)}"`:``,r,n.exclude_auto_reset_sold_out??``,n.is_service_charge_exempt??``,n.is_tax_exempt??``,n.is_pax_linked??``,n.is_point_reward_exempt??``,n.is_credit_reward_exempt??``];t.push(i.join(`,`))}catch(e){throw Error(`Export failed on "${n.name}" (type: ${n.type}): ${e.message}`)}return t.join(`
3
- `)}async function Fi(e){return Vi(zi(await e.text()))}function Ii(e){let t=Bi(e).map(e=>e.trim());return t.includes(`Exclude Auto Reset Sold Out`)?`v11`:t.includes(`Config`)?`v10`:t.includes(`Codename`)?`v9`:t.includes(`Original Price`)?`v8`:t.includes(`Barcode`)?`v7`: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 $(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 Li(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 we;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 Ri(e,t){try{let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`not an object`);return t}catch{throw Error(`Invalid Config JSON at line ${t}`)}}function zi(e){let t=e.replace(/^\uFEFF/,``).replace(/\r\n/g,`
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||{}),w=class{constructor(){v(this,`applying_type`,S.Inclusive),v(this,`applying_items`,[])}},T=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)}},ee=class{constructor(e){v(this,`invoice_uid`,``),e&&(this.invoice_uid=e.invoice_uid)}},te=class{constructor(e){v(this,`guid`,``),v(this,`coupon`,new T),v(this,`is_multi_stores`,!1),v(this,`usage`,new ee),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 T(e.coupon),this.is_multi_stores=e.is_multi_stores,this.usage=new ee(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 ne={from(t){return e(t).format(`YYYY-MM-DD HH:mm:ss`)},to(e){return e}};var E=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)}},D=class extends E{constructor(){super(),v(this,`name`,void 0),v(this,`name_translations`,{})}},re=class extends D{constructor(...e){super(...e),v(this,`description`,void 0),v(this,`description_translations`,{})}};let O=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}({}),ie=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}({}),ae=function(e){return e.LOCAL=`local`,e.CLOUD=`cloud`,e}({});var oe=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 se=function(e){return e.Data=`DataMessage`,e.Event=`EventMessage`,e}({});var ce=class{constructor(){v(this,`model`,``),v(this,`data`,``),v(this,`has_many`,!1),v(this,`type`,se.Data)}},k=class extends Error{constructor(e){super(e),this.name=`system_error`}};let A=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}({}),j=function(e){return e.Open=`opened`,e.Closed=`closed`,e}({});var le=class extends E{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`,j.Open),v(this,`uid`,O.Shift+t())}};let M=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 N=class extends E{constructor(){super(),v(this,`user_uid`,``),v(this,`shift_uid`,``),v(this,`invoice_uid`,``),v(this,`type`,M.CashDeposit),v(this,`amount`,0),v(this,`note`,``),v(this,`uid`,O.Till+t()),v(this,`payment_method_uid`,void 0),v(this,`payment_method_code`,void 0),v(this,`payment_method_name`,void 0),v(this,`payment_method`,void 0)}};let P=function(e){return e.CLOSED=`closed`,e.OPENED=`opened`,e.PAYMENT=`payment`,e}({});var ue=class extends D{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`,O.SectionItem+t()),v(this,`invoice_uid`,``),v(this,`section_uid`,``),v(this,`status`,P.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`,{})}},de=class extends D{constructor(){super(),v(this,`sequence`,0),v(this,`disable_auto_print_receipt`,!1),v(this,`uid`,O.Section+t())}},fe=class extends D{constructor(){super(),v(this,`permissions`,[]),v(this,`is_default`,!1),v(this,`uid`,O.EmployeeRole+t())}};let pe=function(e){return e.POS=`route_pos`,e.CRM=`route_crm`,e.MANAGEMENT=`route_management`,e.SETTINGS=`route_settings`,e.REPORTING=`route_reporting`,e.ANALYTICS=`route_analytics`,e.BOOKING=`route_booking`,e}({}),me=function(e){return e.FUNCTION_SWITCH_TABLE=`function_switch_table`,e.FUNCTION_LAST_BILL=`function_last_bill`,e.FUNCTION_PRINT_LAST_KITCHEN_SLIP=`function_print_last_kitchen_slip`,e.FUNCTION_PRINT_LAST_ORDER_DOCKET=`function_print_last_order_docket`,e.FUNCTION_PRINT_FULL_ORDER_DOCKET=`function_print_full_order_docket`,e.FUNCTION_NOTE=`function_note`,e.FUNCTION_DELETE_BILL=`function_delete_bill`,e.FUNCTION_PERCENT_DISCOUNT=`function_percent_discount`,e.FUNCTION_FLAT_DISCOUNT=`function_flat_discount`,e.FUNCTION_QR_CODE=`function_qr_code`,e.FUNCTION_PAY_IN=`function_pay_in`,e.FUNCTION_PAY_OUT=`function_pay_out`,e.FUNCTION_OPEN_DRAWER=`function_open_drawer`,e.FUNCTION_VOID=`function_void`,e.FUNCTION_VOID_AND_DUPLICATE=`function_void_and_duplicate`,e.FUNCTION_RECEIPT=`function_receipt`,e.FUNCTION_REPRINT=`function_reprint`,e.FUNCTION_ADD_CUSTOMER=`function_add_customer`,e.FUNCTION_CHANGE_PAYMENT=`function_change_payment`,e.FUNCTION_CHECK=`function_check`,e.FUNCTION_PAY_AT_COUNTER=`function_pay_at_counter`,e.FUNCTION_MERGE_TABLE=`function_merge_table`,e.FUNCTION_ADD_SALESPERSON=`function_add_salesperson`,e.ITEM_EDITOR_FLAT_DISCOUNT=`item_editor_flat_discount`,e.ITEM_EDITOR_PERCENT_DISCOUNT=`item_editor_percent_discount`,e.ITEM_EDITOR_DELETE=`item_editor_delete`,e.ITEM_EDITOR_NOTE=`item_editor_note`,e.ITEM_EDITOR_DUPLICATE=`item_editor_duplicate`,e.ITEM_EDITOR_TAKEAWAY=`item_editor_takeaway`,e.ITEM_EDITOR_TRANSFER=`item_editor_transfer`,e.ITEM_EDITOR_SALES_PERSON=`item_editor_sales_person`,e.ITEM_EDITOR_CHANGE_PRICE=`item_editor_change_price`,e.ITEM_EDITOR_CHANGE_OPEN_PRICE=`item_editor_change_open_price`,e.TABLE_EDITOR=`table_editor`,e.FUNCTION_STOCK_ADJUST=`function_stock_adjust`,e.FUNCTION_STOCK_HISTORY=`function_stock_history`,e.FUNCTION_CRM_ADD_CUSTOMER=`function_crm_add_customer`,e.FUNCTION_CRM_EDIT_CUSTOMER=`function_crm_edit_customer`,e.FUNCTION_CRM_DELETE_CUSTOMER=`function_crm_delete_customer`,e}({}),he=function(e){return e.MANAGEMENT_REPORT_PAGE=`management_report_page`,e.MANAGEMENT_INVENTORY_PAGE=`management_inventory_page`,e.MANAGEMENT_INVOICES_PAGE=`management_invoices_page`,e.MANAGEMENT_PRODUCT_PAGE=`management_product_page`,e.MANAGEMENT_EMPLOYEE_PAGE=`management_employee_page`,e.MANAGEMENT_SETUP_PAGE=`management_setup_page`,e}({});const ge=[`Cashier`,`Manager`,`Admin`],_e=Object.values(pe),ve=Object.values(me).filter(e=>e.startsWith(`function_`)),ye=[me.TABLE_EDITOR,...Object.values(me).filter(e=>e.startsWith(`item_editor_`))],be=Object.values(he),xe={en:{routes:{route_pos:`POS`,route_crm:`CRM`,route_management:`Management`,route_settings:`Settings`,route_reporting:`Reporting`,route_analytics:`Analytics`,route_booking:`Booking`},functions:{function_switch_table:`Switch Table`,function_last_bill:`Last Bill`,function_print_last_kitchen_slip:`Print Last Kitchen Slip`,function_print_last_order_docket:`Print Last Order Docket`,function_print_full_order_docket:`Print Complete Order List`,function_note:`Note`,function_delete_bill:`Delete Bill`,function_percent_discount:`Percent Discount`,function_flat_discount:`Flat Discount`,function_qr_code:`QR Code`,function_pay_in:`Pay In`,function_pay_out:`Pay Out`,function_open_drawer:`Open Drawer`,function_void:`Void`,function_void_and_duplicate:`Void and Duplicate`,function_receipt:`Receipt`,function_reprint:`Reprint`,function_add_customer:`Add Customer`,function_change_payment:`Change Payment`,function_check:`Check`,function_pay_at_counter:`Pay at Counter`,function_merge_table:`Merge Table`,function_add_salesperson:`Add Salesperson`,function_stock_adjust:`Stock Adjust`,function_stock_history:`Stock History`,function_crm_add_customer:`CRM Add Customer`,function_crm_edit_customer:`CRM Edit Customer`,function_crm_delete_customer:`CRM Delete Customer`},itemEditor:{table_editor:`Table Editor`,item_editor_flat_discount:`Flat Discount`,item_editor_percent_discount:`Percent Discount`,item_editor_delete:`Delete`,item_editor_note:`Note`,item_editor_duplicate:`Duplicate`,item_editor_takeaway:`Takeaway`,item_editor_transfer:`Transfer`,item_editor_sales_person:`Sales Person`,item_editor_change_price:`Change Price`,item_editor_change_open_price:`Change Open Price`},pages:{management_report_page:`Report Page`,management_inventory_page:`Inventory Page`,management_invoices_page:`Invoices Page`,management_product_page:`Product Page`,management_employee_page:`Employee Page`,management_setup_page:`Setup Page`}},zh:{routes:{route_pos:`收银台`,route_crm:`会员管理`,route_management:`后台管理`,route_settings:`系统设置`,route_reporting:`报表`,route_analytics:`数据分析`,route_booking:`预约`},functions:{function_switch_table:`切换桌台`,function_last_bill:`上一单`,function_print_last_kitchen_slip:`打印上一张厨房单`,function_print_last_order_docket:`打印上一张客检单`,function_print_full_order_docket:`打印完整客检单`,function_note:`备注`,function_delete_bill:`删除订单`,function_percent_discount:`百分比折扣`,function_flat_discount:`直减折扣`,function_qr_code:`二维码`,function_pay_in:`入金`,function_pay_out:`出金`,function_open_drawer:`开钱箱`,function_void:`作废`,function_void_and_duplicate:`作废并复制`,function_receipt:`收据`,function_reprint:`重打`,function_add_customer:`添加客户`,function_change_payment:`修改支付`,function_check:`买单`,function_pay_at_counter:`柜台付款`,function_merge_table:`合并桌台`,function_add_salesperson:`添加销售员`,function_stock_adjust:`库存调整`,function_stock_history:`库存历史`,function_crm_add_customer:`CRM 添加客户`,function_crm_edit_customer:`CRM 编辑客户`,function_crm_delete_customer:`CRM 删除客户`},itemEditor:{table_editor:`编辑桌台`,item_editor_flat_discount:`直减折扣`,item_editor_percent_discount:`百分比折扣`,item_editor_delete:`删除`,item_editor_note:`备注`,item_editor_duplicate:`复制`,item_editor_takeaway:`外带`,item_editor_transfer:`转移`,item_editor_sales_person:`销售员`,item_editor_change_price:`改价`,item_editor_change_open_price:`改开放价`},pages:{management_report_page:`报表页面`,management_inventory_page:`库存页面`,management_invoices_page:`订单页面`,management_product_page:`商品页面`,management_employee_page:`员工页面`,management_setup_page:`设置页面`}}};var F=class{constructor(e){v(this,`item_uid`,``),v(this,`quantity`,0),v(this,`modifiers`,[]),this.item_uid=e,this.quantity=0,this.modifiers=[]}},Se=class extends re{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)}},Ce=class{constructor(){v(this,`system`,we.POS),v(this,`visible`,!1),v(this,`sequence`,0)}};let we=function(e){return e.POS=`pos`,e.QrCodeOrder=`qr_code_order`,e}({}),Te=function(e){return e.Product=`product`,e.Modifier=`modifier`,e}({});var Ee=class extends Se{constructor(){super(),v(this,`type`,Te.Modifier),v(this,`visibility`,[]),v(this,`uid`,O.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)}},De=class extends Se{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`,Te.Product),v(this,`is_delisted`,!1),v(this,`subcategories`,[]),v(this,`uid`,O.Category+t()),v(this,`max_order`,0),v(this,`min_order`,0),v(this,`code`,void 0),v(this,`non_searchable`,!1)}},Oe=class extends Se{constructor(){super(),v(this,`category_uid`,``),v(this,`uid`,O.Subcategory+t())}};let I=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 ke=class extends Se{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`,I.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,`auto_reset_sold_out`,!1),v(this,`exclude_auto_reset_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,`is_always_auto_applied`,!1),v(this,`has_bcrs_deposit`,!1),v(this,`uid`,O.ItemModifier+t())}},Ae=class extends ke{constructor(){super(),v(this,`codename`,``),v(this,`sku`,``),v(this,`recipe`,``),v(this,`barcode`,``),v(this,`type`,I.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`,O.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),v(this,`is_pax_linked`,void 0),v(this,`is_discount_nonstackable`,!1),v(this,`price_as_total_payable`,!1)}};let je=function(e){return e.Flat=`flat`,e.Percent=`percent`,e}({});var Me=class extends E{constructor(){super(),v(this,`lookup_keys`,[]),v(this,`product_uid`,``),v(this,`uid`,O.Price+t()),v(this,`amount`,0),v(this,`type`,je.Flat),v(this,`percent`,1),v(this,`name`,``),v(this,`name_translations`,{})}},Ne=class{constructor(){v(this,`item_uid`,``),v(this,`combo_item`,void 0),v(this,`price`,0),v(this,`sequence`,0),v(this,`meta`,{})}},Pe=class{constructor(){v(this,`uid`,O.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`,{})}},Fe=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(Fe,`State`,{CLOSED:0,OPENING:1,OPENED:2,CLOSING:3}),v(Fe,`electronSocket`,null);function Ie(e){return e===`69`}const Le={Ẳ: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 Re(e,t=63){let n=[];for(let r of e)if(Le[r]!==void 0)n.push(Le[r]);else{let e=r.charCodeAt(0);e<=127?n.push(e):n.push(t)}return Uint8Array.from(n)}function ze(){return typeof Socket>`u`?new Fe:new Socket}var Be=class{constructor(){v(this,`socket`,void 0),this.socket=ze(),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(L).includes(e.codepage)){let t=parseInt(e.codepage,10);r.raw([31,27,31,255,t,10,0])}else e.codepage&&Object.values(L).includes(e.codepage)?n.codepage(e.codepage):n.codepage(L.SimplifiedChinese);for(let t of e.items){if(!t)throw Error(`Item is undefined or null`);switch(t.style){case He.Bold:r.bold(!0);break;case He.Italic:r.italic(!0);break;case He.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 R.Text:if(t.item?.text){if(t.item.size===Ue.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(Ie(e.codepage)){let e=Re(t.item.text);r.raw(Array.from(e))}else r.text(t.item.text,t.item.line_width??48);t.item.size===Ue.Custom&&r.raw([29,33,0])}break;case R.Table:if(t.table){if(t.table.size===Ue.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(Ie(e.codepage)){let e=Re(t);r.raw(Array.from(e))}else r.text(t);r.newline()}),t.table.size===Ue.Custom&&r.raw([29,33,0])}break;case R.Line:r.line(t.item?.text?.repeat(48)??`-`.repeat(48),t.item?.line_width??48);break;case R.NewLine:t.repeat=t.repeat??1;for(let e=0;e<t.repeat;e++)r.newline();break;case R.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 R.QRCode:t.qrcode&&r.qrcode(t.qrcode.data,t.qrcode.model,t.qrcode.size,t.qrcode.errorlevel);break;case R.Barcode:t.barcode&&r.barcode(t.barcode.data,t.barcode.symbology,t.barcode.height);break;case R.Cut:r.cut(t.item?.text??`full`);break;case R.Beeper:r.beeper();break;case R.OpenCashDrawer:{let e=(t.item?.text??``).split(`,`).filter(e=>e.trim()).map(Number),n=e.length>=5&&e.every(e=>Number.isInteger(e)&&e>=0&&e<=255);r.raw(n?e:[27,112,48,55,121]);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 L=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}({}),Ve=function(e){return e.Left=`left`,e.Center=`center`,e.Right=`right`,e}({}),He=function(e){return e.Normal=`normal`,e.Bold=`bold`,e.Italic=`italic`,e.Underline=`underline`,e}({}),Ue=function(e){return e.Custom=`custom`,e.Normal=`normal`,e.Small=`small`,e}({}),R=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 We=class{constructor(){v(this,`data`,``),v(this,`symbology`,`ean13`),v(this,`height`,0)}},Ge=class{constructor(){v(this,`data`,``),v(this,`model`,2),v(this,`size`,6),v(this,`errorlevel`,`m`)}},Ke=class{constructor(){v(this,`base64_data`,``),v(this,`width`,0),v(this,`height`,0),v(this,`algorithm`,`threshold`),v(this,`threshold`,128)}};let qe=function(e){return e[e.SunmiPrinter=0]=`SunmiPrinter`,e}({});var z=class{constructor(){v(this,`codepage`,L.WesternEuropeanLatin),v(this,`items`,[])}};function B(t,n){return e(t).format(n||`YYYY-MMM-DD HH:mm:ss`)}function Je(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 Ye=class extends D{constructor(){super(),v(this,`machine_name`,``),v(this,`connection_id`,``),v(this,`type`,Ze.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:``})}},Xe=class extends D{constructor(){super(),v(this,`type`,Ze.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 Ze=function(e){return e.Client=`client`,e.Node=`node`,e}({}),V=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.EventPrinter=`event_printer`,e}({});var Qe=class{constructor(){v(this,`printer_name`,``),v(this,`status`,``),v(this,`port_name`,``),v(this,`error`,``)}};let $e=function(e){return e.ESCPOS=`ESC/POS`,e.TSPL=`TSPL`,e}({}),et=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.WINDOWS_DRIVER_BUILT_IN=`WINDOWS_DRIVER_BUILT_IN`,e}({});var tt=class{constructor(){v(this,`header`,``),v(this,`body`,``),v(this,`footer`,``),v(this,`commands`,``),v(this,`type`,V.ReceiptPrinter)}},H=class extends D{constructor(){super(),v(this,`header`,``),v(this,`body`,``),v(this,`footer`,``),v(this,`commands`,``),v(this,`printer_type`,V.ReceiptPrinter),v(this,`codepage`,void 0),v(this,`uid`,O.PrintTemplate+t()),v(this,`report_code_name`,``)}};let nt=function(e){return e.Queued=`queued`,e.Printed=`printed`,e.Failed=`failed`,e.Expired=`expired`,e}({});var U=class extends D{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`,V.ReceiptPrinter),v(this,`protocol`,$e.ESCPOS),v(this,`connection_type`,et.ETHERNET),v(this,`data`,new z),v(this,`status`,nt.Queued),v(this,`retries`,0),v(this,`commands`,``),v(this,`uid`,O.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 rt=function(e){return e.Online=`online`,e.Offline=`offline`,e}({});var it=class extends D{constructor(){super(),v(this,`device_uid`,``),v(this,`terminal_device_uids`,[]),v(this,`type`,V.ReceiptPrinter),v(this,`is_not_default`,!1),v(this,`driver_printer_name`,``),v(this,`fallback_printer_uid`,0),v(this,`protocol`,$e.ESCPOS),v(this,`connection_type`,et.ETHERNET),v(this,`print_template_uid`,``),v(this,`uid`,O.Printer+t()),v(this,`ip_address`,``),v(this,`status`,rt.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`,``),v(this,`disable_cancel_print`,!1)}},at=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=B(this.printed_at)}},W=class{constructor(){v(this,`printer_name`,``),v(this,`kitchen_itemized_print`,!1),v(this,`is_cancel`,!1)}},ot=class extends E{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 st),v(this,`payment_method_history`,void 0),v(this,`till_uid`,void 0),v(this,`uid`,O.Payment+t()),v(this,`updated_at`,new Date)}},st=class extends D{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,`col`,void 0),v(this,`row`,void 0),v(this,`uid`,O.PaymentMethod+t())}},ct=class extends st{constructor(){super(),v(this,`changed_at`,new Date),v(this,`changed_by`,``)}},lt=class{toPaymentMethod(){let e=new st;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 ut=function(e){return e.STARTED=`payment_started`,e.COMPLETED=`payment_completed`,e.FAILED=`payment_failed`,e.CANCELLED=`payment_cancelled`,e}({});var dt=class extends D{constructor(){super()}},ft=class extends dt{constructor(){super()}},pt=class extends D{constructor(){super(),v(this,`note_group_uid`,``),v(this,`related_model`,ie.Invoice),v(this,`usage`,0)}},mt=class extends pt{constructor(){super()}};let ht=function(e){return e.DineIn=`dine_in`,e.TakeOut=`take_out`,e.Delivery=`delivery`,e}({}),gt=function(e){return e.Posx=`posx`,e.Kiosk=`kiosk`,e.WyoApp=`wyo_app`,e}({}),_t=function(e){return e.PayToOrder=`pay_to_order`,e.OrderFirstAndPayLater=`order_first_and_pay_later`,e.OnSelection=`on_selection`,e}({}),vt=function(e){return e.Inclusive=`inclusive`,e.Exclusive=`exclusive`,e}({}),G=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}({}),yt=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}({}),bt=function(e){return e.quantity=`quantity`,e.weight=`weight`,e}({}),K=function(e){return e.Flat=`flat`,e.Percent=`percent`,e}({}),q=function(e){return e.AfterSubtotal=`after_subtotal`,e.AfterServiceCharge=`after_service_charge`,e.AfterGrantTotal=`after_grant_total`,e}({}),xt=function(e){return e.Custom=`custom`,e.Voucher=`voucher`,e.Coupon=`coupon`,e}({});var St=class{constructor(){v(this,`uid`,O.InvoiceCharge+t()),v(this,`name`,``),v(this,`percentage`,0),v(this,`amount`,0),v(this,`calc_flow`,q.AfterSubtotal)}},Ct=class{constructor(){v(this,`action`,yt.Create),v(this,`action_by`,``),v(this,`device_uid`,``),v(this,`action_at`,new Date)}},wt=class{constructor(){v(this,`uid`,O.Charge+t()),v(this,`name`,``),v(this,`percent`,0),v(this,`calc_flow`,q.AfterSubtotal),v(this,`trigger_condition`,``)}},Tt=class{constructor(){v(this,`calc_type`,K.Flat),v(this,`amount`,0),v(this,`percent`,0),v(this,`percent_amount`,0),v(this,`type`,xt.Custom),v(this,`calc_flow`,q.AfterSubtotal),v(this,`applying_item_uids`,[]),v(this,`name`,``),v(this,`name_translation`,{}),v(this,`voucher_uid`,``),v(this,`coupon_uid`,``),v(this,`uid`,O.InvoiceDiscount+t())}},Et=class{constructor(){v(this,`item_uid`,``),v(this,`item`,new ke),v(this,`price`,0),v(this,`unit_of_measure`,bt.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)}},Dt=class extends E{constructor(){super(),v(this,`item_uid`,``),v(this,`price`,0),v(this,`unit_of_measure`,bt.quantity),v(this,`quantity`,0),v(this,`remark`,``),v(this,`invoice_uid`,``),v(this,`discount_calc_type`,K.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 Ae),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),v(this,`is_pax_linked`,void 0)}},Ot=class extends E{constructor(e){super(),v(this,`ref_id`,``),v(this,`call_num`,``),v(this,`table_uid`,``),v(this,`table_name`,``),v(this,`type`,ht.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,`bcrs_deposit`,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`,G.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,`signature`,void 0),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`,O.Invoice+t()),v(this,`meta`,{}),v(this,`price_lookup_key`,``),e&&(this.meta={device_type:e})}},kt=class extends E{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`,O.Employee+t()),v(this,`role_uid`,``),v(this,`language`,`en`),v(this,`can_login`,!0)}},At=class extends E{constructor(){super(),v(this,`config`,new Ht),v(this,`cache`,new jt),v(this,`storage`,{pricing_lookup_keys:[],pay_in_reasons:[],pay_out_reasons:[]})}},jt=class{constructor(){v(this,`printers`,[])}},Mt=class{constructor(){}},Nt=class{constructor(){v(this,`enable_appointment_module`,!1)}},Pt=class{constructor(){v(this,`table_switch_slip`,!1)}},Ft=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)}},It=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`),v(this,`enable_payment_bill`,!0)}};let Lt=function(e){return e.SmoochPay=`SPCD`,e.YeahPay=`YEAP`,e.Shouqianba=`CRES`,e}({}),Rt=function(e){return e.YeahPayWechat=`YPWP`,e.YeahPayWechatOnline=`YPWO`,e.Shouqianba=`WCPH`,e}({}),zt=function(e){return e.YeahPayAlipay=`YPAP`,e.YeahPayAlipayOnline=`YPAO`,e.Shouqianba=`ALPH`,e}({});var Bt=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,`enable_pay_at_counter`,!1),v(this,`landing_image`,``),v(this,`menu_banner_image`,``),v(this,`home_page_images`,[]),v(this,`paynow_method`,Ut.WyoPaynow),v(this,`card_payment_code`,Lt.SmoochPay),v(this,`wechat_method`,Rt.YeahPayWechat),v(this,`alipay_method`,zt.YeahPayAlipay),v(this,`takeout_call_num_prefix`,void 0),v(this,`hide_item_price_when_zero_modifier_price`,!1)}},Vt=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})}},Ht=class{constructor(){v(this,`general`,new Jt),v(this,`product`,new qt),v(this,`till`,new Yt),v(this,`report`,new Xt),v(this,`receipt`,new Zt),v(this,`kitchen`,new Qt),v(this,`kds`,new $t),v(this,`label`,new en),v(this,`order`,new tn),v(this,`ods`,new nn),v(this,`payment`,new rn),v(this,`user`,new an),v(this,`tax`,new on),v(this,`rounding`,new ln),v(this,`inventory`,new un),v(this,`pax_config`,new dn),v(this,`gto`,new fn),v(this,`cash_drawer`,new pn),v(this,`marketing`,new Vt),v(this,`charges`,new sn),v(this,`currency`,new cn),v(this,`cds`,new It),v(this,`kiosk`,new Bt),v(this,`online_order`,new Wt),v(this,`loyalty_program`,new Ft),v(this,`crm`,new Mt),v(this,`system`,new Nt),v(this,`event_print`,new Pt)}};let Ut=function(e){return e.FomoOnlinePaynow=`PNWO`,e.WyoPaynow=`WPPN`,e.YeahPayPaynow=`YPPN`,e}({});var Wt=class{constructor(){v(this,`enable_membership`,!1),v(this,`enable_payment_without_member_login`,!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:_t.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),v(this,`disable_pay_at_counter_for_take_out`,!1),v(this,`disable_qr_order_receipt`,!1),v(this,`auto_prompt_pax`,!1),v(this,`upsell_item_uids`,[])}};let Gt=function(e){return e.PROD=`prod`,e.DEV=`dev`,e}({});const Kt=e=>e===`compact`||e===`rectangle`?e:`square`;var qt=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`),v(this,`show_codename`,!1),v(this,`modifier_single_select`,!1),v(this,`hide_barcoded_items`,!1),v(this,`enable_weight_scale_barcode`,!1),v(this,`weight_input_in_kg`,!1),v(this,`codename_badge_color`,`#FF2F00`)}},Jt=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`,Gt.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`}}])}},Yt=class{constructor(){v(this,`control`,!0),v(this,`slip`,!0),v(this,`auto_start_shift`,!1),v(this,`auto_shift_amount`,0)}},Xt=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)}},Zt=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)}},Qt=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`)}},$t=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`,`#29A8A6`),v(this,`color_warning`,`#FFAE58`),v(this,`color_overdue`,`#FF6A6A`),v(this,`color_completed`,`#538235`),v(this,`enable_kds_status_on_pos`,!1),v(this,`show_done_count`,!1),v(this,`show_combo_parent_name`,!1),v(this,`station_mode`,`done`),v(this,`hide_mode`,`done`),v(this,`menu_font_scale`,1),v(this,`text_color_name`,`#FFFFFF`),v(this,`text_color_modifier`,`#FFFFFF`),v(this,`text_color_note`,`#FFFFFF`),v(this,`scroll_mode`,!1),v(this,`new_order_sound_enabled`,!0)}},en=class{constructor(){v(this,`print`,!1),v(this,`text_to_raster`,!1)}},tn=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),v(this,`check_modifier_min_order`,!1),v(this,`auto_prompt_pax`,!1),v(this,`return_to_tables_after_send`,!1),v(this,`disable_line_merge_between_sends`,!1),v(this,`keep_unsent_lines`,!1),v(this,`keep_auto_added_lines_at_end`,!1),v(this,`lock_invoice_after_shift_close`,!1),v(this,`logout_after_end_shift`,!1),v(this,`enable_staff_login_on_launch`,!1),v(this,`change_modifier_stock_on_send`,!1),v(this,`enable_min_order_qty`,!1),v(this,`enable_takeaway_auto_modifier`,!1),v(this,`enable_modifier_total_display`,!0),v(this,`enable_pay_at_counter_badge`,!0),v(this,`sort_remarks_by_recent_use`,!1)}},nn=class{constructor(){v(this,`enabled`,!1),v(this,`language`,`en`)}},rn=class{constructor(){v(this,`quick_cash_payment`,!1),v(this,`notification`,!0),v(this,`quick`,!1),v(this,`payment_auto_redirect_seconds`,5),v(this,`auto_prompt_commission`,!1)}},an=class{constructor(){v(this,`control`,!0)}},on=class{constructor(){v(this,`enabled`,!0),v(this,`method`,vt.Inclusive),v(this,`rate`,7),v(this,`name`,`GST`)}},sn=class{constructor(){v(this,`service_charge`,!1),v(this,`service_charge_rate`,10)}},cn=class{constructor(){v(this,`currency_symbol`,`$`),v(this,`is_symbol_after_amount`,!1)}},ln=class{constructor(){v(this,`base`,.1),v(this,`up`,!0),v(this,`cashless`,!1),v(this,`prepayment_rounding`,!1)}},un=class{constructor(){v(this,`inventory_control`,!1),v(this,`sold_out_for_today_only`,!1)}},dn=class{constructor(){v(this,`pax`,!0),v(this,`detail`,!1)}},fn=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`)}},pn=class{constructor(){v(this,`kick_code`,`27, 112, 48, 55, 121`),v(this,`connection_mode`,`via_receipt_printer`)}},mn=class{constructor(e){v(this,`name`,``),v(this,`base64`,``),v(this,`extension`,`png`),Object.assign(this,e)}};const hn=e=>e===``||e===void 0,gn=e=>t=>hn(e)||t.includes(e),_n=e=>t=>hn(e)||e.includes(t),vn=(e,t)=>n=>n>e&&n<t,yn=e=>typeof e==`function`?(t,n)=>!e(t,n):t=>t!=e,bn=e=>e,xn=e=>t=>!t.deleted_at&&Object.keys(e).every(n=>{if(hn(e[n])||t[n]===e[n])return!0;if(typeof e[n]==`function`)return e[n](t[n],t)});var Sn=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 insertIfNotExists(e){let n={...e};n.created_at||(n.created_at=new Date),n.uid||(n.uid=t()),n.updated_at=new Date;try{return await this.db.table(this.moduleName).add(n),!0}catch(e){if(e.name!==`ConstraintError`)throw e;return!1}}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(xn(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(xn(e)).count(),o=this.db.table(this.moduleName).filter(xn(e));return r!==-1&&o.offset((n-1)*r).limit(r),{list:await o.toArray(),count:a,page:n,pageSize:r}}},Cn=class extends Sn{async updateOne(e,t){throw Error(`Method not implemented.`)}async deleteOne(e){throw Error(`Method not implemented.`)}},J=class extends Sn{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}};function wn(e){let n=o.cloneDeep(e);if(n.uid=O.Item+t(),n.id_in_server=0,n.plu=void 0,!n.modifier_categories?.length)return n;let r=[],i=[];for(let e of n.modifier_categories){let a=n.modifiers?.filter(t=>t.category_uid===e.uid);if(!a?.length)continue;let s={...o.cloneDeep(e),uid:O.ItemModifierCategory+t()};r.push(s),i.push(...a.map(e=>({...o.cloneDeep(e),uid:O.ItemModifier+t(),category_uid:s.uid})))}return n.modifier_categories=r,n.modifiers=i,n}let Tn=function(e){return e[e.printable=0]=`printable`,e[e.generative=1]=`generative`,e}({});var En=class{constructor(){v(this,`uid`,O.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)}},Dn=class{constructor(){v(this,`uid`,O.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)}},On=class extends E{constructor(){super(),v(this,`uid`,O.AppReport+t()),v(this,`reports`,[]),v(this,`version`,1)}},kn=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,`printed_time`,``),v(this,`sales_summary`,new An),v(this,`drawer_summary`,new jn),v(this,`non_cash_till_summary`,new Mn),v(this,`payments_summary`,[]),v(this,`loyalty_program_summary`,new Pn),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`,[]),v(this,`first_ref_id`,``),v(this,`last_ref_id`,``)}},An=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)}},jn=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),v(this,`entries`,[])}},Mn=class{constructor(){v(this,`pay_in_total`,0),v(this,`pay_in_count`,0),v(this,`pay_out_total`,0),v(this,`pay_out_count`,0),v(this,`pay_in_by_method`,[]),v(this,`pay_out_by_method`,[]),v(this,`entries`,[])}},Nn=class{constructor(){v(this,`code`,``),v(this,`name`,``),v(this,`total`,0),v(this,`count`,0)}},Pn=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)}},Fn=class{constructor(){v(this,`item`,{}),v(this,`quantity`,0),v(this,`total_amount`,0),v(this,`modifiers`,[])}},In=class{constructor(){v(this,`item`,{}),v(this,`quantity`,0),v(this,`total_amount`,0)}},Ln=class{constructor(){v(this,`category`,null),v(this,`items`,[]),v(this,`total_quantity`,0),v(this,`total_amount`,0)}},Rn=class extends J{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 ti(e,t,n,`configs`,`config`),this.printJobService=new di(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(V.ReceiptPrinter)}async getDefaultPrinterByType(e){return this.getDefaultPrinter(e)}async getDefaultKioskPrinter(){return this.getDefaultPrinter(V.KioskPrinter)}async getDefaultCheckPrinter(){return this.getDefaultPrinter(V.CheckPrinter)}async getDefaultKitchenPrinter(){return this.getDefaultPrinter(V.KitchenPrinter)}async getDefaultOrderPrinter(){return this.getDefaultPrinter(V.OrderPrinter)}async getDefaultKitchenDisplayPrinter(){return this.getDefaultPrinter(V.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 Be().connect(s,t,200)&&n.push(s)}return await this.configService.updateCache({printers:n}),n}async openCashDrawer(e=`27, 112, 48, 55, 121`){let t=await this.getDefaultReceiptPrinter(),n=new z;n.items.push({type:R.OpenCashDrawer,item:{text:e,size:Ue.Normal}});let r=new U(t,n,!1,1);await this.printJobService.addOne(r)}};function Y(e,t=2){let n=10**t;return Math.round(+(e*n).toFixed(6))/n}function zn(e){let t=e.name,n=t.lastIndexOf(`.`);return n===-1||n===t.length-1?``:t.slice(n+1)}function Bn(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 Vn=(e,t)=>e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/[_\-\.]+/g,` `).toLowerCase().replace(/[\s]+(\w)/g,(e,n)=>t(n)),Hn=e=>e.replace(/^\W+|\W+$/g,``),Un=e=>typeof e==`string`?Vn(e,e=>e.toUpperCase()):``,Wn=e=>typeof e==`string`?e.charAt(0).toUpperCase()+e.slice(1):``,Gn=e=>typeof e==`string`?e.replace(/\w\S*/g,e=>Wn(e)):``,Kn=e=>typeof e==`string`?Vn(e,e=>`-`+e):``,qn=e=>typeof e==`string`?Vn(e,e=>`.`+e):``,Jn=e=>Yn(e),Yn=e=>typeof e==`string`?e.toLowerCase():``,Xn=e=>{if(typeof e!=`string`)return``;let t=Vn(e,e=>e.toUpperCase());return t.charAt(0).toUpperCase()+t.slice(1)},Zn=e=>typeof e==`string`?Vn(e,e=>`/`+e):``,Qn=e=>typeof e==`string`?e.replace(/((?:\S[^\.\?\!]*)[\.\?\!]*)/g,e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()):``,$n=e=>typeof e==`string`?Vn(e,e=>`_`+e):``,er=e=>typeof e==`string`?e.replace(/[- _]+/g,` `).split(` `).map(e=>Wn(e)).join(` `):``,tr=e=>nr(e),nr=e=>typeof e==`string`?e.toUpperCase():``,rr=(e,t)=>typeof e==`string`&&typeof t==`string`?e+t:e,ir=(e,t)=>{if(typeof e!=`string`)return``;let n=``;for(let e=0;e<t;e++)n+=`&nbsp;`;return n+e+n},ar=e=>typeof e==`string`?Hn(e):``,or=e=>typeof e==`string`?e.split(` `).join(`-`):``,sr=(e,t=` `)=>typeof e==`string`?(typeof t!=`string`&&(t=` `),e.split(t).join(`+`)):``,cr=(e,t)=>typeof e==`string`&&typeof t==`string`?t+e:e,lr=(e,t)=>typeof e==`string`?typeof t==`string`?e.split(t).join(``):e:``,ur=(e,t)=>typeof e==`string`?typeof t==`string`?e.replace(t,``):e:``,dr=(e,t,n)=>typeof e==`string`?typeof t==`string`?(typeof n!=`string`&&(n=``),e.split(t).join(n)):e:``,fr=(e,t,n)=>typeof e==`string`?typeof t==`string`?(typeof n!=`string`&&(n=``),e.replace(t,n)):e:``,pr=e=>typeof e==`string`?e.split(``).reverse().join(``):``,mr=(e,t=`,`)=>typeof e==`string`?(typeof t!=`string`&&(t=`,`),e.split(t)):[],hr=(e,t)=>typeof e==`string`?e.length<=t?e:yr(e,t)+`…`:``,gr=e=>typeof e==`string`?e.trim():``,_r=e=>typeof e==`string`?e.replace(/^\s+/,``):``,vr=e=>typeof e==`string`?e.replace(/\s+$/,``):``,yr=(e,t,n=``)=>typeof e==`string`?(typeof n!=`string`&&(n=``),e.length>t?e.slice(0,t-n.length)+n:e):``;var br={camelcase:Un,capitalize:Wn,capitalizeAll:Gn,dashcase:Kn,dotcase:qn,downcase:Jn,lowercase:Yn,pascalcase:Xn,pathcase:Zn,sentence:Qn,snakecase:$n,titleize:er,upcase:tr,uppercase:nr,append:rr,center:ir,chop:ar,hyphenate:or,plusify:sr,prepend:cr,remove:lr,removeFirst:ur,replace:dr,replaceFirst:fr,reverse:pr,split:mr,ellipsis:hr,trim:gr,trimLeft:_r,trimRight:vr,truncate:yr,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 xr=e=>e&&typeof e==`object`&&typeof e.fn==`function`,X=(e,t,n)=>xr(n)?e?n.fn?n.fn(t):!0:n.inverse?n.inverse(t):!1:e,Sr=function(...e){let t=e.pop();return X(e.every(e=>!!e),this,t)},Cr=function(...e){let t=e.pop();return X(e.some(e=>!!e),this,t)},wr=function(e,t){return X(!e,this,t)},Tr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),X(e===t,this,n)},Er=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),X(e==t,this,n)},Dr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),X(e!==t,this,n)},Or=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),X(e!=t,this,n)},kr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),X(e>t,this,n)},Ar=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),X(e>=t,this,n)},jr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),X(e<t,this,n)},Mr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),X(e<=t,this,n)},Nr=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 X(i,this,r)},Pr=function(e,t,n){return typeof n==`number`&&(n=arguments[3]),X(e==null?!1:Array.isArray(e)||typeof e==`string`?e.includes(t):typeof e==`object`?t in e:!1,this,n)},Fr=Pr,Ir=function(e,...t){let n=t.pop();return X(t.includes(e),this,n)},Lr=(e,t)=>{if(!(!e||!t))return t.split(`.`).reduce((e,t)=>e?.[t],e)},Rr=e=>{let t=[];for(let n=0;n<e.length-1;n+=2)typeof e[n]==`string`&&!xr(e[n+1])&&t.push({prop:e[n],value:e[n+1]});return t};var zr={and:Sr,or:Cr,not:wr,eq:Tr,is:Er,neq:Dr,isnt:Or,gt:kr,gte:Ar,lt:jr,lte:Mr,compare:Nr,contains:Pr,includes:Fr,in:Ir,findAnd:function(e,...t){if(!Array.isArray(e))return null;let n=Rr(t);return e.find(e=>n.every(t=>Lr(e,t.prop)===t.value))||null},findOr:function(e,...t){if(!Array.isArray(e))return null;let n=Rr(t);return e.find(e=>n.some(t=>Lr(e,t.prop)===t.value))||null},filterAnd:function(e,...t){if(!Array.isArray(e))return[];let n=Rr(t);return e.filter(e=>n.every(t=>Lr(e,t.prop)===t.value))},filterOr:function(e,...t){if(!Array.isArray(e))return[];let n=Rr(t);return e.filter(e=>n.some(t=>Lr(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 X(!e&&!t,this,n)},ifEven:function(e,t){return X(e%2==0,this,t)},ifOdd:function(e,t){return X(e%2!=0,this,t)},ifNth:function(e,t,n){return X(typeof e==`number`&&typeof t==`number`&&t%e===0,this,n)}};function Br(e){let t=e?.handlebars||e?.hbs||m(`handlebars`);return Object.keys(br).forEach(e=>{t.registerHelper(e,br[e])}),Object.keys(zr).forEach(e=>{t.registerHelper(e,zr[e])}),t.helpers}var Vr=Br,Hr=class extends E{constructor(){super(),v(this,`uid`,O.OrderDisplaySystem+t()),v(this,`order_number`,``),v(this,`status`,Ur.Preparing)}};let Ur=function(e){return e.Preparing=`preparing`,e.ReadyForPickup=`ready_for_pickup`,e}({});var Wr=class extends J{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 k(`Display order not found`);if(t.status==`ready_for_pickup`)throw new k(`Order is already ready for pickup`);if(t.status=Ur.ReadyForPickup,t.updated_at=new Date,t.id_in_server==0)throw new k(`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 k(`Display order not found`);if(t.status==`preparing`)throw new k(`Order is already preparing`);if(t.status=Ur.Preparing,t.updated_at=new Date,t.id_in_server==0)throw new k(`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==Ur.ReadyForPickup).reverse().limit(100).toArray();if(e.length===0)throw new k(`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=Ur.Preparing,t.updated_at=new Date,t.id_in_server==0)throw new k(`Order is not synced with server`);return await this.updateOne(t.id_in_server,t),t}};Vr({handlebars:d});const Gr=(e,t)=>e.item?.[t]?e.subtotal:e.subtotal_before_discount?e.quantity*(e.modifiers||[]).filter(e=>e.item?.[t]).reduce((e,t)=>e+t.price*t.quantity,0)*e.subtotal/e.subtotal_before_discount:0,Kr={quantity:1,price:0,remark:``};var qr=class extends J{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 oi(e,t,n,`tills`,`till`),this.sectionItemService=new ri(e,t,n,`section_items`,`section_item`),this.sectionService=new ni(e,t,n,`sections`,`section`),this.configService=new ti(e,t,n,`configs`,`config`),this.printTemplateService=new pi(e,t,n,`print_templates`,`print_template`),this.printerService=new Rn(e,t,n,`printers`,`printer`),this.printJobService=new di(e,t,n,`print_jobs`,`print_job`),this.itemService=new $r(e,t,n,`items`,`item`),this.orderDisplayService=new Wr(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,q.AfterSubtotal),e.grand_total<0&&(e.grand_total=0,e.service_chargeable_subtotal=0),this.calculateInvoiceCharges(e,q.AfterSubtotal),e.subtotal>0&&e.discount_amount>0){let t=1-e.discount_amount/e.subtotal;e.service_chargeable_subtotal=Y(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,q.AfterServiceCharge),e.grand_total<0&&(e.grand_total=0),this.calculateInvoiceCharges(e,q.AfterServiceCharge);let i=t.config.tax.enabled?t.config.tax.rate:0;return this.calculateTax(e,i,t.config.tax.method),e.bcrs_deposit=Y(e.lines.reduce((e,t)=>e+(t.item?.has_bcrs_deposit?t.quantity*.1:0),0),2),e.grand_total=Y(e.grand_total+e.bcrs_deposit,2),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,q.AfterGrantTotal),e.grand_total<0&&(e.grand_total=0),this.calculateInvoiceCharges(e,q.AfterGrantTotal),e.grand_total=Y(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+=Y(n.subtotal,2),e.point_subtotal+=n.point_subtotal;e.subtotal=Y(t,2),e.grand_total=Y(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=Y(e.quantity*(e.price+t),2),e.item.discountable&&(e.discount_amount>0||e.discount_percent>0)&&(e.discount_calc_type==K.Flat||(e.discount_amount=Y(e.subtotal*e.discount_percent,2)),e.subtotal-=e.discount_amount),e.subtotal=Y(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=Y(Y(e.lines.filter(e=>!e.is_take_out).reduce((e,t)=>e+t.subtotal-Gr(t,`is_service_charge_exempt`),0)),2)}calculateDiscount(e,t){if(!e?.lines?.length)return;let n=0;if(e.discountable_subtotal=Y(e.lines.filter(e=>e.item.discountable&&!(e.item.is_discount_nonstackable&&e.discount_amount>0)).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==K.Flat?n+=r.amount:(r.percent_amount=Y((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){let e=n.price+(n.modifiers??[]).reduce((e,t)=>e+t.price*t.quantity,0);r.applying_item_uids.includes(n.item_uid)&&e>t&&(t=e,i=!0)}if(!i){e.discounts=e.discounts.filter(e=>e.uid!=r.uid);continue}r.calc_type==K.Flat?(r.amount=Y(r.amount>t?t:r.amount),n+=r.amount):(r.percent_amount=Y(t*r.percent),n+=r.percent_amount)}e.discount_amount+=Y(n),e.grand_total=Y(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=Y(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,Y(s/100)}calculateDeliveryCharge(e){e.delivery_charge>0&&e.type===ht.Delivery&&(e.grand_total+=e.delivery_charge,e.grand_total=Y(e.grand_total,2))}calculateServiceCharge(e,t){let n=0;e.service_charge=0,!(e.lines==null||e.lines.length<1)&&(e.type==ht.Delivery||e.type==ht.TakeOut||(t>0&&(n=e.service_chargeable_subtotal*(t/100)),e.service_charge=Y(n,2),e.grand_total+=e.service_charge,e.grand_total=Y(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===vt.Inclusive?e.tax=Y(i*r*t/(100+t)+e.service_charge*t/(100+t),2):(e.tax=Y(i*r*t/100+e.service_charge*t/100,2),e.grand_total=Y(e.grand_total+e.tax,2))}calculateCreditDeduction(e){e.minus_credit||(e.minus_credit=0),!(e.minus_credit<=0)&&(e.minus_credit=Y(e.minus_credit),e.minus_credit>e.grand_total&&(e.minus_credit=Y(e.grand_total)),e.grand_total=Y(e.grand_total-e.minus_credit))}calculateTip(e){e.tip>0&&(e.grand_total=Y(e.grand_total+e.tip,2))}calculateTaxSubtotalRatio(e){if(!e.lines)return 1;let t=e.lines.reduce((e,t)=>e+Gr(t,`is_tax_exempt`),0);return!t||e.grand_total===0||e.subtotal===0?1:1-t/e.subtotal}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=Y(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=Math.floor(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=Y((i+a)/2,2);if(r===i||r===a)break;let s=o.cloneDeep(e);s.discounts||(s.discounts=[]),s.discounts.push({...new Tt,calc_type:K.Flat,calc_flow:q.AfterSubtotal,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 Tt,calc_type:K.Flat,calc_flow:q.AfterSubtotal,amount:a}],this.calculate(s,n),s.grand_total>t)throw Error(`Target grand total ${t} is unreachable`);return Y(a,2)}resetInvoiceCalculations(e){e.subtotal=0,e.point_subtotal=0,e.service_chargeable_subtotal=0,e.service_charge=0,e.tax=0,e.bcrs_deposit=0,e.grand_total=0,e.rounding=0,e.discount_amount=0,e.minus_credit=0,e.minus_point=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=Y(Math.max(0,e.tender_amount-Math.max(0,t))),t=Y(t-e.tender_amount)):e.payment_method.allow_custom_amount?(t=Y(t-Math.min(e.tender_amount,Math.max(0,t))),e.change_amount=0):(e.change_amount=0,t=Y(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 q.AfterSubtotal:t=e.subtotal;break;case q.AfterServiceCharge:t=e.subtotal+e.service_charge;break;case q.AfterGrantTotal:t=e.grand_total;break;default:t=e.subtotal}n.percentage>0&&(n.amount=Y(t*(n.percentage/100),2)),e.grand_total+=n.amount,e.grand_total=Y(e.grand_total,2)}}},Jr=class extends qr{addItemToLine(e,n,r,i,a,o,s,c,l){let u={...Kr,...o};e.lines??(e.lines=[]);let d=this.findOrCreateLine(e,i,u.quantity,u.price,a,u.remark,s,c,l);return i.type==I.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=O.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=O.InvoiceLine+t(),e.lines.push(r);for(let i of this.getAttachedLines(e,n.uid)){let n=o.cloneDeep(i);n.uid=O.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 Et;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==K.Percent&&n>100)throw new k(`Discount percent can not be more than 100%`);if(t==K.Flat&&n>e.subtotal)throw new k(`Discount amount can not be more than price`);return e.discount_calc_type=t,t==K.Flat?e.discount_amount=n:e.discount_percent=n,e}minusLineQuantity(e,t,n,r=!1){if(n<=0)throw new k(`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 k(`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,r,i){if(!e||e.length<=0)return e;n=n??0;let a=e.findIndex(e=>e.item_uid===t.item_uid&&e.price===t.price);if(a<0)return e;e[a].quantity+=n;let[s]=e[a].quantity<=0?e.splice(a,1):[];return s?.sent>0&&r&&i&&(r.deleted_modifiers??(r.deleted_modifiers=[])).push({...o.cloneDeep(i),modifiers:[s]}),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 Dt;return a.item=o.cloneDeep(e),a.item_uid=e.uid,a.quantity=t,a.point=e.minus_point??0,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,c=!1){let l=this.addItemToLine(e,t,n,r,o,s,c,i,a);return l.is_combo_item=!0,l.combo_line_uid=i,l.combo_group_uid=a,l}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 k(`Line is not a combo`);let r=o.cloneDeep(n);return r.uid=O.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=O.InvoiceLine+t(),i.combo_line_uid=r.uid,i.is_duplicate=!0,e.lines.push(i)}),e}},Yr=class extends Jr{async addInvoice(e){let t=await this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/add_invoice`,e);if(t.error==A.outdatedInvoice)throw await this.saveOne(t.data),new k(t.error);if(t.error)throw new k(t.error);return t.data}async createInvoice(e,t,n,r=!1){if(e.status=G.Open,e.ref_id||(e.ref_id=await this.getRefId()),!e.call_num){let t=e.ref_id.slice(-3);e.call_num=t===`000`?`777`:t}e.table_name=t.name,e.table_uid=t.uid,t.invoice_uid=e.uid,t.status=P.OPENED,this.sectionItemService.syncInvoiceData(t,e),this.addEmployeeToInvoice(e,n),e.created_at=new Date,e.created_at_timestamp=e.created_at.getTime();let i=(await this.configService.getDefaultOne()).config;e.humanized_created_at=B(e.created_at,i?.order?.datetime_format),t.invoice_created_at=new Date;let a=await this.createKitchenPrintJobs(e),o=await this.createLabelPrintJobs(e),s=await this.createOrderPrintJobs(e),c=this.sortPrintJobsByPrinterSequence([...a,...o,...s]);r&&c.forEach(e=>e.save_only=!0),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=a.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.snapshotSendState(e),g=i?.order?.change_modifier_stock_on_send,_=await this.getItemStockChangeList(e,g);await this.preprocessInvoice(e,g);let v={invoice:e,section_item:t};c.length>0&&(v.print_jobs=c),_.length>0&&(v.items=await this.itemService.getItemsWithStockChanges(_));try{let e=await this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${this.methodName}`,v);if(e.error==A.outdatedInvoice)throw await this.saveOne(e.data),v.invoice=e.data,new k(e.error);if(e.error==A.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),v.section_item=e.data,new k(e.error);return v}catch(t){throw e.kitchen_print_job_uids.length=l,e.label_print_job_uids.length=u,e.order_print_job_uids.length=d,h(),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.snapshotSendState(e),g=(await this.configService.getDefaultOne()).config?.order?.change_modifier_stock_on_send,_=await this.getItemStockChangeList(e,g);await this.preprocessInvoice(e,g);let v={invoice:e,section_item:t};c.length>0&&(v.print_jobs=c),_.length>0&&(v.items=await this.itemService.getItemsWithStockChanges(_));try{let e=await this.http.patch(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/update_invoice`,v);if(e.error==A.outdatedInvoice)throw await this.saveOne(e.data),new k(`${e.error}, system has updated the data, please try again`);if(e.error==A.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),v.section_item=e.data,new k(`${e.error}, system has updated the data, please try again`);return v}catch(t){throw e.kitchen_print_job_uids.length=l,e.label_print_job_uids.length=u,e.order_print_job_uids.length=d,h(),t}}async cancelInvoice(e,t,n){if(e.id_in_server==0&&e.lines.length<=0)throw new k(`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=G.Void,t.invoice_uid=``,t.status=P.CLOSED,this.sectionItemService.reset(t),this.addEmployeeToInvoice(e,n);let r=await this.createReceiptPrintJob(e,V.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==A.outdatedInvoice)throw await this.saveOne(a.data),i.invoice=a.data,new k(a.error);if(a.error==A.outdatedSectionItem)throw await this.sectionItemService.saveOne(a.data),i.section_item=a.data,new k(a.error);return i}async checkInvoice(e,t,n,r){t.status=P.PAYMENT,this.addEmployeeToInvoice(e,n);let i=await this.createReceiptPrintJob(e,V.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.snapshotSendState(e),_=(await this.configService.getDefaultOne()).config?.order?.change_modifier_stock_on_send,v=await this.getItemStockChangeList(e,_);await this.preprocessInvoice(e,_);let y={invoice:e,section_item:t};l.length>0&&(y.print_jobs=l),v.length>0&&(y.items=await this.itemService.getItemsWithStockChanges(v));try{let e=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/check_invoice`,y);if(e.error==A.outdatedInvoice)throw await this.saveOne(e.data),y.invoice=e.data,new k(e.error);if(e.error==A.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),y.section_item=e.data,new k(e.error);return y}catch(t){throw e.kitchen_print_job_uids.length=u,e.label_print_job_uids.length=d,e.order_print_job_uids.length=f,g(),t}}async switchInvoice(e,t,n,r){if(t.uid==n.uid)throw new k(`source and target table can not be the same`);if(t.status!=P.CLOSED)throw new k(`target table is occupied`);if(e.lines==null||!e.id_in_server&&e.lines.length<=0)throw new k(`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=P.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==A.outdatedInvoice)throw await this.saveOne(a.data),i.invoice=a.data,new k(a.error);if(a.error==A.outdatedSourceSectionItem)throw await this.sectionItemService.saveOne(a.data),i.source_section_item=a.data,new k(a.error);if(a.error==A.outdatedTargetSectionItem)throw await this.sectionItemService.saveOne(a.data),i.target_section_item=a.data,new k(a.error);return i}async payInvoice(e,t,n,r,i){e.status=G.Paid,t.invoice_uid=``,t.status=P.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;if(e.humanized_paid_at=B(e.paid_at,o),e.payment_has_cash=e.payments?.some(e=>e.payment_method?.is_cash===!0),!n)for(let t of e.payments??[])delete t.till_uid;let s=this.snapshotSendState(e),c=a?.order?.change_modifier_stock_on_send,l=this.mergeStockChangeLists(await this.getItemStockChangeList(e,c),c?[]:await this.getModifierStockChangeList(e)),u=await this.sectionService.getOne(t.section_uid),d=await this.createLabelPrintJobs(e),f=await this.createReceiptPrintJob(e,V.ReceiptPrinter,u?.disable_auto_print_receipt||!1,0,i),p=await this.createKitchenPrintJobs(e),m=await this.createCancelKitchenPrintJobs(e,e.deleted_lines),h=await this.createVoidSlipPrintJobs(e,e.deleted_lines,t),g=await this.createOrderPrintJobs(e),_=[...d,...p,...m,...h,...g];f&&_.push(f);let v=this.sortPrintJobsByPrinterSequence(_);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 y=e.kitchen_print_job_uids.length,b=e.label_print_job_uids.length,x=e.order_print_job_uids.length,S=p.map(e=>e.uid),C=d.map(e=>e.uid),w=g.map(e=>e.uid);S.length>0&&e.kitchen_print_job_uids.push(S),C.length>0&&e.label_print_job_uids.push(C),w.length>0&&e.order_print_job_uids.push(w),await this.preprocessInvoice(e,c);let T={invoice:e,section_item:t,till:n};v.length>0&&(T.print_jobs=v),l.length>0&&(T.items=await this.itemService.getItemsWithStockChanges(l));try{let t=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/pay_invoice`,T);if(t.error==A.outdatedInvoice)throw await this.saveOne(t.data),T.invoice=t.data,new k(`${t.error}, system has updated the data and please try again`);if(t.error==A.outdatedSectionItem)throw await this.sectionItemService.saveOne(t.data),T.section_item=t.data,new k(`${t.error}, system has updated the data and please try again`);if(e.call_num&&a?.ods?.enabled){let t=new Hr;t.order_number=e.call_num,await this.orderDisplayService.addOne(t)}return T}catch(t){throw e.kitchen_print_job_uids.length=y,e.label_print_job_uids.length=b,e.order_print_job_uids.length=x,s(),t}}async directPayInvoice(e,t,n,r,i,a=!1,o=!1){e.status=G.Paid,n!=null&&this.addEmployeeToInvoice(e,n),e.paid_at=new Date;let s=(await this.configService.getDefaultOne()).config,c=s?.order?.datetime_format;if(e.humanized_paid_at=B(e.paid_at,c),e.created_at=new Date,e.created_at_timestamp=e.created_at.getTime(),e.humanized_created_at=B(e.created_at,c),e.ref_id||(e.ref_id=await this.getRefId()),!e.call_num){let t=e.ref_id.slice(-3);e.call_num=t===`000`?`777`:t}if(e.payment_has_cash=e.payments?.some(e=>e.payment_method?.is_cash===!0),!t)for(let t of e.payments??[])delete t.till_uid;let l=this.snapshotSendState(e),u=s?.order?.change_modifier_stock_on_send,d=this.mergeStockChangeLists(await this.getItemStockChangeList(e,u),u?[]:await this.getModifierStockChangeList(e)),f=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,p=(f?.section_uid?await this.sectionService.getOne(f.section_uid):null)?.disable_auto_print_receipt||!1,m=null,h=null;if(r&&r.type==V.KioskPrinter){let t=!!s?.kiosk?.disable_receipt_printer_receipt||p;m=await this.createReceiptPrintJob(e,V.ReceiptPrinter,t),h=await this.createReceiptPrintJob(e,V.KioskPrinter,!1,0,r,i)}else m=await this.createReceiptPrintJob(e,V.ReceiptPrinter,p||o,0,r);let g=await this.createLabelPrintJobs(e),_=await this.createKitchenPrintJobs(e,a),v=await this.createOrderPrintJobs(e),y=[...g,..._,...v];m&&y.push(m),h&&y.push(h);let b=this.sortPrintJobsByPrinterSequence(y),x=_.map(e=>e.uid),S=g.map(e=>e.uid),C=v.map(e=>e.uid);x.length>0&&(e.kitchen_print_job_uids=[x]),S.length>0&&(e.label_print_job_uids=[S]),C.length>0&&(e.order_print_job_uids=[C]),await this.preprocessInvoice(e,u);let w={invoice:e,till:t};b.length>0&&(w.print_jobs=b),d.length>0&&(w.items=await this.itemService.getItemsWithStockChanges(d));try{let t=await this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/direct_pay_invoice`,w);if(t.error==A.outdatedInvoice)throw await this.saveOne(t.data),w.invoice=t.data,new k(t.error);if(e.call_num&&s?.ods?.enabled){let t=new Hr;t.order_number=e.call_num,await this.orderDisplayService.addOne(t)}return w}catch(e){throw l(),e}}async voidInvoice(e,t,n,r){n&&(e.etc.void_reason=n);let i=e.status,a=this.snapshotSendState(e);e.status=G.Void,e.voided_at=new Date;let o=(await this.configService.getDefaultOne()).config?.order?.datetime_format;e.humanized_voided_at=B(e.voided_at,o),t&&(t.deleted_at=new Date),this.addEmployeeToInvoice(e,r);let s=(await this.configService.getDefaultOne()).config,c=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,l=await this.createReceiptPrintJob(e,V.ReceiptPrinter,!0),u=[],d=[],f=[...e.lines,...(e.deleted_lines||[]).filter(e=>(e.sent||0)-(e.stock_reverted||0)>0)];s.kitchen.print_cancel_whole_invoice&&(u=await this.createCancelKitchenPrintJobs(e,f)||[]),s.receipt.print_cancel_whole_invoice&&(d=await this.createVoidSlipPrintJobs(e,f,c)||[]);let p=[...u,...d];l&&p.push(l);let m={invoice:e,till:t};p.length>0&&(m.print_jobs=p);let h=await this.tillService.db.table(`tills`).where({invoice_uid:e.uid}).toArray(),g=h.filter(e=>e.type===M.CashInvoice&&!e.deleted_at).reduce((e,t)=>e+t.amount,0);if(g>0){let t=new N;t.type=M.CashInvoice,t.amount=-g,t.invoice_uid=e.uid,t.shift_uid=h[0]?.shift_uid,t.user_uid=r?.uid||h[0]?.user_uid,m.till=t}c&&c.status!=P.CLOSED&&c.invoice_uid===e.uid&&(c.invoice_uid=``,c.status=P.CLOSED,m.section_item=c);let _=await this.getItemStockChangeList(e,s?.order?.change_modifier_stock_on_send,!0),v=i==G.Paid&&!s?.order?.change_modifier_stock_on_send?this.mergeStockChangeLists(_,await this.getModifierStockChangeList(e,!0)):_;v.length>0&&(m.items=await this.itemService.getItemsWithStockChanges(v));try{let e=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/void_invoice`,m);if(e.error==A.outdatedInvoice)throw await this.saveOne(e.data),m.invoice=e.data,new k(e.error);return m}catch(t){throw e.status=i,a(),t}}async duplicateInvoice(e,n){if(e.status!=G.Paid)throw new k(`invalid invoice status`);let r=o.cloneDeep(e);if(r.etc.is_duplicate=!0,r.etc.duplicated_from_uid=r.uid,r.uid=O.Invoice+t(),r.status=G.Open,r.ref_id=await this.getRefId(),this.addEmployeeToInvoice(r,n),r.lines)for(let e of r.lines)e.uid=O.InvoiceLine+t();if(r.payments)for(let e of r.payments)e.uid=O.Payment+t();return r}async reprintReceipt(e,n=!1,r){if(!e?.receipt_print_job_uid)throw new k(`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 k(`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 k(`Receipt printer not found`);return i=this.printJobService.replacePrinter(i,a),i.uid=O.PrintJob+t(),i.save_only=n,i.status=nt.Queued,i.print_times=1,i.printed=0,i.retries=0,i.created_at=new Date,i.updated_at=i.created_at,i.created_at_timestamp=i.created_at.getTime(),await this.printJobService.addOne(i),i}async printLastKitchenSlips(e){let n=await this.getOne(e);if(!n)throw new k(`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 k(`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 k(`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=O.PrintJob+t(),r.save_only=!1,r.status=nt.Queued,r.print_times=1,r.printed=0,r.retries=0,r.created_at=new Date,r.updated_at=r.created_at,r.created_at_timestamp=r.created_at.getTime(),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 k(`Invoice not found`);let r=n.order_print_job_uids?.[n.order_print_job_uids.length-1]||[];if(r.length===0)throw new k(`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 k(`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=O.PrintJob+t(),r.save_only=!1,r.status=nt.Queued,r.print_times=1,r.printed=0,r.retries=0,r.created_at=new Date,r.updated_at=r.created_at,r.created_at_timestamp=r.created_at.getTime(),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=q.AfterSubtotal,i=`custom`,a={}){if(e.discounts||(e.discounts=[]),t==K.Percent&&n>100)throw new k(`Discount percent can not be more than 100%`);let o=new Tt;return o.calc_type=t,o.calc_flow=r,o.name=i,o.name_translation=a,t==K.Flat?o.amount=n:o.percent=n,e.discounts.push(o),e}addCouponToInvoice(e,t,n=q.AfterSubtotal){e.discounts||(e.discounts=[]);let r=new Tt;if(r.calc_type=t.coupon.discount_calc_type==1?K.Flat:K.Percent,r.calc_flow=n,r.name=t.coupon.name,r.calc_type==K.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 k(`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 k(`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 k(`Source invoice has no nothing to merge`);if(t.lines.some(e=>e.quantity!=e.sent))throw new k(`Please send first before merging`);if(!await this.getOne(e.uid))throw new k(`Target invoice not found`);if(!await this.getOne(t.uid))throw new k(`Source invoice not found`);if(e?.id_in_server==0)throw new k(`Target invoice is not synced to server`);if(t?.id_in_server==0)throw new k(`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!=G.Paid)throw new k(`invalid invoice status`);if(!t||t.length<1)throw new k(`invalid options`);for(let n of t){let t=e.payments.find(e=>e.uid==n.source_payment.uid);if(!t)throw new k(`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==V.ReceiptPrinter||t==V.CheckPrinter){let n=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,r=t==V.ReceiptPrinter?n?.receipt_printer_uid:n?.check_printer_uid;r&&(o=await this.printerService.getOne(r)),o||(o=t==V.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 k(`Print template not found`);t==V.ReceiptPrinter&&!s.config?.receipt?.enabled&&(n=!0);let l=await this.printTemplateService.renderPrintTemplate(e,s.config,c,{...new W,printer_name:o.name}),u=new U(o,l,n,r);return t!=V.ReceiptPrinter&&(u.printer_type=t),o.connection_type!=et.ETHERNET&&(u.connection_type=o.connection_type),t==V.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,V.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 U(t,await this.printTemplateService.renderPrintTemplate(l,n,a,{...new W,printer_name:t.name}),!1,t.print_times);r.push(i)}else{l.lines=c;let e=new U(t,await this.printTemplateService.renderPrintTemplate(l,n,a,{...new W,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,V.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 U(i,await this.printTemplateService.renderPrintTemplate(u,t,s,{...new W,printer_name:i.name}),!1,i.print_times);n.push(d)}return n}async createFullOrderDocketPrintJob(e){let t=(await this.configService.getDefaultOne()).config;if(!t.receipt.print_docket)return[];let n=(e.lines||[]).filter(e=>e.sent>0).map(e=>({...o.cloneDeep(e),quantity:e.sent}));if(n.length===0)return[];let r=[],i=new Set;for(let e of n)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=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,c=await this.printerService.getPrintersByUids(a);for(let i of c){if(s?.order_printer_uids?.length>0&&!s.order_printer_uids.includes(i.uid))continue;let a=await this.printTemplateService.getOneByParams({uid:i.print_template_uid});if(!a)continue;let c=n.filter(e=>e.item?.order_printers_uids?.includes(i.uid));if(c.length===0)continue;let l=this.getSortedLines(c.map(e=>o.cloneDeep(e)),i);this.sortLineModifiers(l);let u=o.cloneDeep(e);u.lines=l;let d=new U(i,await this.printTemplateService.renderPrintTemplate(u,t,a,{...new W,printer_name:i.name}),!1,i.print_times);r.push(d)}return r}async createVoidSlipPrintJobs(e,t,n){if(!t||t.length===0||e.action===yt.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(i.disable_cancel_print||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 U(i,await this.printTemplateService.renderPrintTemplate(u,r,a,{...new W,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,V.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 U(e,new z,!1,e.print_times);c.commands=o,n.push(c)}return n}filterLinesAndPrintersToPrint(e,t){let n;switch(t){case V.KitchenPrinter:n=`kitchen_printers_uids`;break;case V.OrderPrinter:n=`order_printers_uids`;break;case V.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==V.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===yt.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){if(t.disable_cancel_print)continue;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 U(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 U(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))}snapshotSendState(e){let t=(e.lines??[]).map(e=>({l:e,sent:e.sent,mods:e.modifiers?.map(e=>({m:e,sent:e.sent}))})),n=[...e.deleted_lines??[],...(e.deleted_modifiers??[]).flatMap(e=>e.modifiers??[])].map(e=>({x:e,stock_reverted:e.stock_reverted}));return()=>{t.forEach(({l:e,sent:t,mods:n})=>{e.sent=t,n?.forEach(({m:e,sent:t})=>e.sent=t)}),n.forEach(({x:e,stock_reverted:t})=>e.stock_reverted=t)}}async preprocessInvoice(e,t){if(e.lines){for(let n of e.lines)if(n.sent=n.quantity,t)for(let e of n.modifiers||[])e.sent=e.quantity}return e}rebaseUnsentLines(e,t){if(t?.uid!==e.uid||!t?.lines?.length)return!1;let n=!1;for(let r of t.lines){let t=r.quantity-(r.sent||0);if(t<=0)continue;let i=e.lines?.find(e=>e.uid===r.uid);i?(i.sent??0)>=i.quantity&&(i.quantity+=t,n=!0):r.sent||(r.selected=!1,(e.lines??(e.lines=[])).push(r),n=!0)}return n}addInvoiceCharge(e,t,n,r,i=q.AfterSubtotal){e.charges||(e.charges=[]);let a=new St;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}async getItemStockChangeList(e,t,n=!1){let r=new Map,i=t?await this.buildModifierIndex():null,a=(e,t)=>{if(i)for(let n of e.modifiers||[]){let a=t(n),o=i.uidToSku.get(n.item_uid);if(a)for(let{itemUid:t,modUid:s}of o?i.skuToCopies.get(o)||[]:[{itemUid:e.item_uid,modUid:n.item_uid}]){let e=r.get(t)||new F(t),n=e.modifiers.find(e=>e.item_uid===s);n?n.quantity+=a:e.modifiers.push({item_uid:s,quantity:a}),r.set(t,e)}}};for(let t of e.lines||[]){a(t,e=>(t.sent||0)*(e.sent||0)-(n?0:t.quantity*e.quantity));let e=n?-(t.sent||0):t.quantity-(t.sent||0);if(e===0)continue;let i=r.get(t.item_uid)||new F(t.item_uid);i.quantity-=e,r.set(t.item_uid,i)}for(let t of e.deleted_lines||[]){let e=(t.sent||0)-(t.stock_reverted||0);if(e<=0)continue;a(t,t=>e*(t.sent||0));let n=r.get(t.item_uid)||new F(t.item_uid);n.quantity+=e,r.set(t.item_uid,n),t.stock_reverted=t.sent}for(let t of e.deleted_modifiers||[])a(t,e=>{let n=(t.sent||0)*((e.sent||0)-(e.stock_reverted||0));return e.stock_reverted=e.sent,n});return Array.from(r.values())}async buildModifierIndex(){let e=new Map,t=new Map;for(let n of await this.itemService.getAll())for(let r of n.modifiers||[]){if(!r.sku)continue;e.set(r.uid,r.sku);let i=t.get(r.sku)||[];i.push({itemUid:n.uid,modUid:r.uid}),t.set(r.sku,i)}return{uidToSku:e,skuToCopies:t}}async getModifierStockChangeList(e,t=!1){if(!e.lines||e.lines.length===0)return[];let{uidToSku:n,skuToCopies:r}=await this.buildModifierIndex(),i=new Map;for(let a of e.lines)if(!(!a.modifiers||a.modifiers.length===0))for(let e of a.modifiers){let o=t?a.quantity*e.quantity:-(a.quantity*e.quantity),s=n.get(e.item_uid),c=s?r.get(s)||[]:[{itemUid:a.item_uid,modUid:e.item_uid}];for(let{itemUid:e,modUid:t}of c){let n=i.get(e)||new F(e),r=n.modifiers.find(e=>e.item_uid===t);r||(r={item_uid:t,quantity:0},n.modifiers.push(r)),r.quantity+=o,i.set(e,n)}}return Array.from(i.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 F(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}},Xr=class extends Yr{},Zr=class extends J{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}},Qr=class extends J{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 k(`Password is incorrect`)}else throw new k(`User not found`)}catch(e){throw e instanceof k?e:new k(`Unexpected error, login failed`)}}async createEmployee(e){try{if(await this.getOne(e.uid))throw new k(`User already exists`);return e.password&&(e.password=await p.hash(e.password,12)),this.addOne(e)}catch(e){throw e instanceof k?e:new k(`Unexpected error, creating employee failed`)}}async changePassword(e){try{return await p.hash(e,12)}catch{throw new k(`Unexpected error, changing password failed`)}}},$r=class extends J{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=O.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 k(`Item does not have any modifier categories`);let n=e.modifier_categories.findIndex(e=>e.uid===t.uid);if(n===-1)throw new k(`Modifier category not found`);return e.modifier_categories[n]=t,e}async removeModifierCategory(e,t){if(!e.modifier_categories)throw e.modifier_categories=[],new k(`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=O.ItemModifier+t(),e.modifiers.push(n),e}async updateModifier(e,t){if(!e.modifiers)throw e.modifiers=[],new k(`Item does not have any modifiers`);let n=e.modifiers.findIndex(e=>e.uid===t.uid);if(n===-1)throw new k(`Modifier not found`);return e.modifiers[n]=t,e}async removeModifier(e,t){if(!e.modifiers)throw e.modifiers=[],new k(`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 k(`Item does not have any modifier categories`);if(!e.modifier_categories.find(e=>e.uid===n))throw new k(`Modifier category not found`);let r=e.modifiers.find(e=>e.uid===t);if(!r)throw new k(`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 mn({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 k(`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 k(`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 k(`Item not found`);let r=Number(n.stock);return n.stock=(isNaN(r)?0:r)+t,this.updateOne(n.id_in_server,n)}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}async buildModifierIndex(){let e=new Map,t=new Map;for(let n of await this.getAll())for(let r of n.modifiers||[]){if(!r.sku)continue;e.set(r.uid,r.sku);let i=t.get(r.sku)||[];i.push({itemUid:n.uid,modUid:r.uid}),t.set(r.sku,i)}return{uidToSku:e,skuToCopies:t}}async changeModifiersStockBySku(e,t){if(!e)return[];let{skuToCopies:n}=await this.buildModifierIndex(),r=n.get(e);if(!r?.length)return[];let i=new Map;for(let{itemUid:e,modUid:n}of r){let r=i.get(e);if(!r){let t=await this.getOne(e);if(!t)continue;r=t,i.set(e,r)}let a=r.modifiers?.find(e=>e.uid===n);a&&(a.stock=(Number(a.stock)||0)+t)}return Array.from(i.values())}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){return wn(e)}async cloneModifiers(e,n){let r=o.cloneDeep(e);r.uid=O.ItemModifierCategory+t();let i=[];for(let e of n){let n=o.cloneDeep(e);n.uid=O.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 k(`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!==I.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}},ei=class extends J{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 k(`Category does not have any subcategories`);let n=e.subcategories.findIndex(e=>e.uid===t.uid);if(n===-1)throw new k(`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 k(`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}},ti=class extends J{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 Jt,product:()=>new qt,till:()=>new Yt,report:()=>new Xt,receipt:()=>new Zt,kitchen:()=>new Qt,kds:()=>new $t,label:()=>new en,order:()=>new tn,payment:()=>new rn,user:()=>new an,tax:()=>new on,rounding:()=>new ln,charges:()=>new sn,currency:()=>new cn,inventory:()=>new un,pax_config:()=>new dn,gto:()=>new fn,cash_drawer:()=>new pn,marketing:()=>new Vt})}async updateConfig(e,t){let n=await this.getDefaultOne();n||(n=new At);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 At);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=zn(e);return await this.http.post(`api/v5/merchants/`+this.options.merchant_uid+`/upload-image`,new mn({base64:await Bn(e),name:t,extension:n})),{file_url:`${this.options.base_url}images/${t}.${n}`,thumbnail_url:`${this.options.base_url}images/${t}.thumbnail.${n}`}}},ni=class extends J{constructor(e,t,n,r=`sections`,i=`section`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},ri=class extends J{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||``}}},ii=class extends J{constructor(e,t,n,r=`products`,i=`product`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},ai=class extends J{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 oi(e,t,n)}async cashIn(e,t,n){let r=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status===j.Open).first();if(!r)throw new k(`No opening shift found`);let i=new N;return i.amount=e,i.type=M.CashIn,i.user_uid=r.user_uid,i.shift_uid=r.uid,i.note=t,n&&(i.payment_method_uid=n.uid,i.payment_method_code=n.payment_method_code,i.payment_method_name=n.name,i.payment_method=n),this.tillService.addOne(i)}async cashOut(e,t,n){let r=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status===j.Open).first();if(!r)throw new k(`No opening shift found`);let i=new N;return i.amount=e,i.type=M.CashOut,i.user_uid=r.user_uid,i.shift_uid=r.uid,i.note=t,n&&(i.payment_method_uid=n.uid,i.payment_method_code=n.payment_method_code,i.payment_method_name=n.name,i.payment_method=n),this.tillService.addOne(i)}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==j.Open).first();if(!n)throw new k(`No opening shift found`);return n.declared_amount=e,n.ended_at=new Date,n.user_uid=t,n.status=j.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==j.Open).first();if(r)throw new k(`shift is already opened shift at ${r.started_at}`);let i=new le;if(i.started_at=new Date,i.user_uid=t,i.status=j.Open,await this.addOne(i),await this.insertIfNotExists(i),e>0){let r=new N;r.amount=e,r.type=M.OpenDeposit,r.user_uid=t,r.amount=e,r.shift_uid=i.uid,r.note=n,await this.tillService.addOne(r),await this.tillService.insertIfNotExists(r)}return console.log(`open shift end`),i}},oi=class extends J{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 N;a.shift_uid=t,a.user_uid=n,a.note=r,a.invoice_uid=i;let o=e.filter(e=>e.payment_method.is_cash);a.amount=Y(o.map(e=>e.tender_amount-e.change_amount).reduce((e,t)=>e+t,0)),a.type=M.CashInvoice;for(let e of o)e.till_uid=a.uid;return a}async autoQuery(e,t){return await this.http.get(`sapi/v5/merchants/${this.options.merchant_uid}/${this.moduleName}`,{params:e.build(),...t})}},si=class extends J{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`,{headers:{"Cache-Control":`no-cache, no-store`}}),t=[];for(let n of e){let e=new lt(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}},ci=class extends J{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 ot;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=Y(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}},li=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 k(`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 k(`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}},ui=class extends J{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 Xr(e,t,n,`invoices`,`invoice`),this.tillService=new oi(e,t,n,`tills`,`till`),this.paymentService=new ci(e,t,n,`payments`,`payment`),this.printerService=new Rn(e,t,n,`printers`,`printer`),this.printTemplateService=new pi(e,t,n,`print_templates`,`print_template`),this.printJobService=new di(e,t,n,`print_jobs`,`print_job`),this.configService=new ti(e,t,n,`configs`,`config`)}async syncStandardReports(){let e=await this.getDefaultOne();e||(e=new On);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 k(`No default receipt printer found`);let n=await this.printTemplateService.getOneByParams({report_code_name:e.report_code_name});if(!n)throw new k(`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 U(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 kn;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 i=new Date(e.start_datetime).getTime(),a=new Date(e.end_datetime).getTime(),o=36e5,s=new f().addParam(`created_at`,`GreaterThanOrEqualTo`,new Date(i-o).toISOString()).addParam(`created_at`,`LessThanOrEqualTo`,new Date(a+o).toISOString()),c=e.shift_uid||e.report_code_name==`till_report`?((await this.tillService.autoQuery(s,{timeout:6e5})).results||[]).filter(t=>t.deleted_at==null&&(e.shift_uid?t.shift_uid==e.shift_uid:new Date(t.created_at).getTime()>=i&&new Date(t.created_at).getTime()<=a)):[],l=e=>e.payment_method?e.payment_method.is_cash:!0,u=e=>Y(e.reduce((e,t)=>e+t.amount,0)),d=e=>{let t=new Map;for(let n of e){let e=t.get(n.payment_method_code)??Object.assign(new Nn,{code:n.payment_method_code,name:n.payment_method_name});e.total=Y(e.total+n.amount),e.count++,t.set(n.payment_method_code,e)}return[...t.values()]},p=c.filter(e=>e.type==M.CashIn&&l(e)),m=c.filter(e=>e.type==M.CashOut&&l(e)),h=c.filter(e=>e.type==M.CashIn&&!l(e)),g=c.filter(e=>e.type==M.CashOut&&!l(e)),_=(e,t)=>e.map(e=>({type:e.type,label:t,created_at:new Date(e.created_at).toISOString(),time:B(new Date(e.created_at),`MM/DD HH:mm`),amount:e.type==M.CashOut?-e.amount:e.amount,note:e.note||``,payment_method_code:e.payment_method_code,payment_method_name:e.payment_method_name,invoice_uid:e.invoice_uid||``,ref_id:``})),v=(e,t)=>e.created_at.localeCompare(t.created_at),y=r.drawer_summary;y.open_amount=u(c.filter(e=>e.type==M.OpenDeposit)),y.pay_in_total=u(p),y.pay_in_count=p.length,y.pay_out_total=u(m),y.pay_out_count=m.length,y.cash_invoice_total=u(c.filter(e=>e.type==M.CashInvoice)),y.cash_invoice_count=c.filter(e=>e.type==M.CashInvoice).length,y.drawer_amount=Y(y.open_amount+y.pay_in_total+y.cash_invoice_total-y.pay_out_total),y.difference=e.shift_uid?Y(y.drawer_amount-y.declared_amount):0,y.entries=[..._(c.filter(e=>e.type==M.OpenDeposit),`OPEN`),..._(p,`CASH IN`),..._(c.filter(e=>e.type==M.CashInvoice),`CASH SALE`),..._(m,`CASH OUT`)].sort(v);let b=r.non_cash_till_summary;b.pay_in_total=u(h),b.pay_in_count=h.length,b.pay_out_total=u(g),b.pay_out_count=g.length,b.pay_in_by_method=d(h),b.pay_out_by_method=d(g),b.entries=[..._(h,`PAY IN`),..._(g,`PAY OUT`)].sort(v),r.start_datetime=new Date(e.start_datetime).toISOString(),r.end_datetime=new Date(e.end_datetime).toISOString(),r.humanized_start_datetime=B(new Date(e.start_datetime),t),r.humanized_end_datetime=B(new Date(e.end_datetime),t),r.humanized_printed_datetime=B(new Date,t),r.printed_time=B(new Date,`MM/DD HH:mm`);let x=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),S=(await this.invoiceService.autoQuery(x,{timeout:6e5})).results||[],C=new Map(S.map(e=>[e.uid,e.ref_id]));for(let e of r.drawer_summary.entries)e.type==M.CashInvoice&&(e.ref_id=C.get(e.invoice_uid)||``);return this.processReportInvoicesData(r,S,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===K.Percent?`${Y(i*100)}% Discount`:`${n}${Y(r)} Discount`),f=(e,t,n,r,i,a)=>{let o=u(t,n,n===K.Percent?i:r),s=e.get(o);s?(s.count++,s.total=Y(s.total+a)):e.set(o,{name:t,alias:d(t,n,r,i),calc_type:n,amount:r,percent:i,count:1,total:Y(a)})};t.forEach(t=>{if(t.status==G.Paid){t.ref_id&&((!e.first_ref_id||t.ref_id<e.first_ref_id)&&(e.first_ref_id=t.ref_id),t.ref_id>e.last_ref_id&&(e.last_ref_id=t.ref_id)),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||ht.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=Y(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=Y(n.total_amount+e.price*e.quantity)):(n=new In,n.item=e.item,n.quantity=e.quantity,n.total_amount=Y(e.price*e.quantity),i.set(t,n))})):(a=new Fn,a.item=t.item,a.quantity=t.quantity,a.total_amount=Y(t.subtotal),a.modifiers=[],t.modifiers&&t.modifiers.length>0&&t.modifiers.forEach(e=>{let t={item:e.item,quantity:e.quantity,total_amount:Y(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=Y(r.total_amount+e.price*e.quantity)):(r=new In,r.item=e.item,r.quantity=e.quantity,r.total_amount=Y(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=Y(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:Y(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===K.Percent?e.percent_amount:e.amount;f(t?c:s,e.name||``,e.calc_type,e.amount,e.percent,n)})}t.status==G.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==G.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 Ln,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=Y(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=Y(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=Y(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:Y(e.total)})),e.sales_summary.paid_invoice_total=Y(e.sales_summary.paid_invoice_total),e.sales_summary.sales_total=Y(e.sales_summary.sales_total),e.sales_summary.rounding_total=Y(e.sales_summary.rounding_total),e.sales_summary.tax_total=Y(e.sales_summary.tax_total),e.sales_summary.service_charge_total=Y(e.sales_summary.service_charge_total),e.sales_summary.discount_total=Y(e.sales_summary.discount_total),e.sales_summary.foc_sales_total=Y(e.sales_summary.foc_sales_total),e.sales_summary.foc_rounding_total=Y(e.sales_summary.foc_rounding_total),e.sales_summary.foc_tax_total=Y(e.sales_summary.foc_tax_total),e.sales_summary.foc_service_charge_total=Y(e.sales_summary.foc_service_charge_total),e.sales_summary.void_invoice_total=Y(e.sales_summary.void_invoice_total),e.sales_summary.pax_sales_total=Y(e.sales_summary.pax_sales_total),e.loyalty_program_summary.add_credit_total=Y(e.loyalty_program_summary.add_credit_total),e.loyalty_program_summary.topup_paid_total=Y(e.loyalty_program_summary.topup_paid_total),e.loyalty_program_summary.rewarded_credit_total=Y(e.loyalty_program_summary.rewarded_credit_total),e.loyalty_program_summary.minus_credit_total=Y(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}},di=class extends J{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}},fi=class extends J{constructor(e,t,n,r=`menus`,i=`menu`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},pi=class extends J{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:V.ReceiptPrinter})){let e=new H;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=V.ReceiptPrinter,await this.addOne(e),console.log(`Default Receipt Template added`)}if(!await this.getOneByParams({printer_type:V.CheckPrinter})){let e=new H;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=V.CheckPrinter,await this.addOne(e),console.log(`Default Check Template added`)}if(!await this.getOneByParams({printer_type:V.OrderPrinter})){let e=new H;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=V.OrderPrinter,await this.addOne(e),console.log(`Default Order Template added`)}if(!await this.getOneByParams({printer_type:V.KitchenPrinter})){let e=new H;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=V.KitchenPrinter,await this.addOne(e),console.log(`Default Kitchen Template added`)}if(!await this.getOneByParams({printer_type:V.KioskPrinter})){let e=new H;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=V.KioskPrinter,await this.addOne(e),console.log(`Default Kiosk Template added`)}if(!await this.getOneByParams({printer_type:V.KitchenDisplayPrinter})){let e=new H;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=V.KitchenDisplayPrinter,await this.addOne(e),console.log(`Default Kitchen Display Template added`)}if(!await this.getOneByParams({printer_type:V.LabelPrinter})){let e=new H;e.commands=await this.getPrintTemplate(`tspl_cmds`),e.name=`Default Label Template`,e.printer_type=V.LabelPrinter,await this.addOne(e)}if(!await this.getOneByParams({printer_type:V.QrCodePrinter})){let e=new H;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=V.QrCodePrinter,await this.addOne(e)}if(!await this.getOneByParams({printer_type:V.EventPrinter})){let e=new H;e.name=`Default Event Template`,e.header=await this.getPrintTemplate(`eht`),e.body=await this.getPrintTemplate(`ebt`),e.footer=await this.getPrintTemplate(`eft`),e.printer_type=V.EventPrinter,await this.addOne(e)}if(!await this.getOneByParams({report_code_name:`sales_summary_report`})){let e=new H;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 H;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 H;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 H;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`)}if(!await this.getOneByParams({report_code_name:`till_report`})){let e=new H;e.name=`Till Report`,e.body=await this.getPrintTemplate(`trbt`),e.header=await this.getPrintTemplate(`trht`),e.footer=await this.getPrintTemplate(`trft`),e.report_code_name=`till_report`,await this.addOne(e),console.log(`Till Report Template added`)}}async renderPrintTemplate(e,t,n,r=new W){let i=new z;n.printer_type==V.KitchenPrinter||n.printer_type==V.OrderPrinter?i.codepage=n.codepage||this.getCodepageByCountryCode(t.kitchen.language):i.codepage=n.codepage||this.getCodepageByCountryCode(t.receipt.language);let a=new at;return a.invoice=e,a.config=t,a.normalized_printed_at=B(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 W){let i=new z,a=new at;return a.report_data=e,a.config=t,a.normalized_printed_at=B(a.printed_at,t?.order?.datetime_format),i.codepage=n.codepage||L.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 W){let r=new z;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:L.English,GR:L.Greek,DE:L.WesternEurope,LT:L.BalticRim,PL:L.CentralEurope,RU:L.Cyrillic,TR:L.Turkish,EU:L.MultilingualLatin1WithEuro,PT:L.Portuguese,IS:L.Icelandic,IL:L.Hebrew,CA:L.FrenchCanadian,EG:L.Arabic,NO:L.Nordic,BY:L.Russian,MK:L.ModernGreek,CN:L.SimplifiedChinese,KR:L.Korean,TW:L.TraditionalChinese,FR:L.WesternEuropeanLatin,AE:L.ArabicISO,JP:L.Japanese,CZ:L.CentralEuropeanLatinWindows,BG:L.CyrillicWindows,ES:L.WesternEuropeanLatinWindows,CY:L.GreekWindows,AZ:L.TurkishWindows,PS:L.HebrewWindows,SA:L.ArabicWindows,LV:L.BalticWindows,VN:L.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}}},mi=class extends J{constructor(e,t,n,r=`storages`,i=`storage`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},hi=class extends J{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}},gi=class extends J{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 _i(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}var vi=class{constructor(e){this.db=e}flatten(e){let t={};for(let[n,r]of Object.entries(e))(typeof r!=`object`||!r||r instanceof Date)&&(t[n]=r);return t}async getTableStats(){let e=[];for(let t of this.db.tables){let n=await t.count().catch(()=>-1),r=await t.orderBy(`created_at`).reverse().limit(5).toArray().catch(()=>[]);e.push({name:t.name,count:n,latestRecords:r.map(e=>this.flatten(e))})}return{tables:e.sort((e,t)=>t.count-e.count),totalCount:e.reduce((e,t)=>e+t.count,0)}}};const yi=new Map([[`Item`,$r],[`Section`,ni],[`SectionItem`,ri],[`Category`,ei],[`Config`,ti],[`Shift`,ai],[`Till`,oi],[`Employee`,Qr],[`PaymentMethod`,si],[`Invoice`,Xr],[`Report`,ui],[`Printer`,Rn],[`PrintJob`,di],[`PrintTemplate`,pi],[`EmployeeRole`,Zr],[`OrderDisplay`,Wr],[`Storage`,mi],[`Menu`,fi],[`StockLog`,hi],[`Appointment`,gi]]),Z=`uid, updated_at, created_at, deleted_at, _timestamp, id_in_server, created_at_timestamp`,bi=`${Z}, sequence`,xi=`${bi}, status`,Si=`${Z}, till_type, shift_uid, invoice_uid`,Ci=`${bi}, payment_method_code, is_disabled`,wi=`${Z}, type, status, table_uid`,Ti=`${bi}, name, barcode, codename`,Ei=`${Z}, status, printer_type, connection_type, protocol, save_only, device_uid_to_print`,Di=`${Z}, name, printer_type`,Oi=`${Z}, order_number, status`,ki=`${Z}, model`,Ai={items:Ti,sections:bi,section_items:bi,categories:bi,shifts:xi,tills:Si,employees:`${Z}, role_uid`,payment_methods:Ci,invoices:wi,configs:Z,reports:Z,printers:Z,print_jobs:Ei,print_templates:Di,employee_roles:`${Z}, name, is_default`,order_displays:Oi,storages:ki,menus:Z,stock_logs:`${Z}, entity_type, entity_uid, type`,appointments:`${Z}, status, scheduled_at, employee_uid, customer_id`};var Q=function(e){return e.DISCONNECTED=`disconnected`,e.CONNECTED=`connected`,e.ERROR=`error`,e}(Q||{}),ji=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`,Q.DISCONNECTED),this.mode=e.mode,this.http=_i(e.base_url,e.device_uid,e.token),n||this.initializeDatabase(),Fe.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(Ai),this.status=Q.CONNECTED}catch(e){this.status=Q.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==Q.ERROR)throw Error(`Database connection error`);for(;this.status==Q.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==Q.ERROR)throw Error(`Database connection error`);for(;this.status==Q.DISCONNECTED;)await new Promise(e=>setTimeout(e,100));try{let t=yi.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)}}updateToken(e){this.http.defaults.headers.Authorization=`Bearer ${e}`}get httpClient(){return this.http}async dispose(){await this.dataSource?.close(),this.status=Q.ERROR}getDiagnosticsService(){if(this.status!=Q.CONNECTED)throw Error(`Database connection error`);return new vi(this.dataSource)}};async function Mi(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 Ni={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`]},v7:{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`,`Barcode`]},v8:{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`,`Barcode`,`Original Price`]},v9:{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`,`Barcode`,`Original Price`,`Codename`]},v10:{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`,`Barcode`,`Original Price`,`Codename`,`Config`]},v11:{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.Barcode.Original Price.Codename.Config.Exclude Auto Reset Sold Out.Is Service Charge Exempt.Is Tax Exempt.Is Pax Linked.Is Point Reward Exempt.Is Credit Reward Exempt`.split(`.`)},v12:{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.Barcode.Original Price.Codename.Config.Exclude Auto Reset Sold Out.Is Service Charge Exempt.Is Tax Exempt.Is Pax Linked.Is Point Reward Exempt.Is Credit Reward Exempt.Add Credit.Add Point.Minus Point`.split(`.`)}},Pi=[`category`,`subcategory`,`product`,`modifier_category`,`modifier`,`combo`,`combo_group`,`combo_item`];function Fi(e,t,n=`export.csv`){return Li(Vi(e,t,e=>e.code||``,e=>e.plu||``))}async function Ii(e,t){let n=new Map,r=new Map;for(let t of e){let e=t.code||(t.name?await Mi(`${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 Mi(`${e.name}|${t.toFixed(2)}`):``);i.set(e,n),e.uid&&a.set(e.uid,n)}return{blob:Li(Vi(e,t,e=>n.get(e)||``,e=>i.get(e)||``)),productPluByUid:a,categoryCodeByUid:r}}function Li(e){let t=Ui(e);return new Blob([``+t],{type:`text/csv;charset=utf-8;`})}function Ri(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 zi(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e);return t.length===0?``:t.map(([e,t])=>`${e}:${t}`).join(`|`)}function Bi(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 Vi(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:zi(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)Hi(i,e,r);for(let e of t.subcategories){i.push({type:`subcategory`,name:e.name,sku:``,sequence:e.sequence,name_translations:zi(e.name_translations)});let t=n.get(e.uid)||[];for(let e of t)Hi(i,e,r)}}else for(let e of o)Hi(i,e,r)}return i}function Hi(e,t,n){let r=t.type===I.Combo,i=n(t);if(e.push({type:r?`combo`:`product`,name:t.name,sku:t.sku||``,price:t.price,stock:Ri(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:zi(t.name_translations),item_uid:t.uid,prices:t.prices?.length?t.prices:void 0,plu:i,barcode:t.barcode||``,original_price:t.original_price||void 0,codename:t.codename||``,config:t.config,exclude_auto_reset_sold_out:t.exclude_auto_reset_sold_out,is_service_charge_exempt:t.is_service_charge_exempt,is_tax_exempt:t.is_tax_exempt,is_pax_linked:Number(t.is_pax_linked)||void 0,is_point_reward_exempt:t.is_point_reward_exempt,is_credit_reward_exempt:t.is_credit_reward_exempt,add_credit:t.add_credit,add_point:t.add_point,minus_point:t.minus_point}),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:Ri(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:zi(t.name_translations),prices:t.prices?.length?t.prices:void 0,original_price:t.original_price||void 0,config:t.config,exclude_auto_reset_sold_out:t.exclude_auto_reset_sold_out})}}}function Ui(e){let t=[Ni.v12.headers.join(`,`)];for(let n of e)try{let e=n.prices?.length?`"${JSON.stringify(n.prices).replace(/"/g,`""`)}"`:``,r=n.config&&Object.keys(n.config).length?`"${JSON.stringify(n.config).replace(/"/g,`""`)}"`:``,i=[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,`""`)}"`:``,n.barcode?`"${n.barcode.replace(/"/g,`""`)}"`:``,n.original_price===void 0?``:n.original_price.toString(),n.codename?`"${n.codename.replace(/"/g,`""`)}"`:``,r,n.exclude_auto_reset_sold_out??``,n.is_service_charge_exempt??``,n.is_tax_exempt??``,n.is_pax_linked??``,n.is_point_reward_exempt??``,n.is_credit_reward_exempt??``,n.add_credit??``,n.add_point??``,n.minus_point??``];t.push(i.join(`,`))}catch(e){throw Error(`Export failed on "${n.name}" (type: ${n.type}): ${e.message}`)}return t.join(`
3
+ `)}async function Wi(e){return Zi(Yi(await e.text()))}function Gi(e){let t=Xi(e).map(e=>e.trim());return t.includes(`Add Credit`)?`v12`:t.includes(`Exclude Auto Reset Sold Out`)?`v11`:t.includes(`Config`)?`v10`:t.includes(`Codename`)?`v9`:t.includes(`Original Price`)?`v8`:t.includes(`Barcode`)?`v7`: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 $(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 Ki(e,t,n){if(!e?.trim())return;let r=Number(e);if(isNaN(r)||r<0)throw Error(`Invalid ${t} "${e}" at line ${n}`);return r}function qi(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 Me;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,t){try{let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`not an object`);return t}catch{throw Error(`Invalid Config JSON at line ${t}`)}}function Yi(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=Ii(n),i=wi[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=Bi(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(!Ti.includes(o))throw Error(`Invalid type "${o}" at line ${e+1}. Must be: ${Ti.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=$(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 w;if(_&&_.trim()&&(w=parseInt(_,10),isNaN(w)))throw Error(`Invalid sequence "${_}" at line ${e+1}`);let T,ee,te,ne,E=``,D,re=``,O=``,ie=``,ae,oe=``,se;if((r===`v3`||r===`v4`||r===`v5`||r===`v7`||r===`v8`||r===`v9`||r===`v10`||r===`v11`)&&(T=$(i[12],`print_on_receipt`,e+1),ee=$(i[13],`discountable`,e+1),te=$(i[14],`open_editor_panel`,e+1),ne=$(i[15],`is_delisted`,e+1),E=i[16]?.trim()||``),(r===`v4`||r===`v5`||r===`v7`||r===`v8`||r===`v9`||r===`v10`||r===`v11`)&&i[17]?.trim()&&(D=Li(i[17],e+1)),(r===`v5`||r===`v7`||r===`v8`||r===`v9`||r===`v10`||r===`v11`)&&(re=i[18]?.trim()||``,O=i[19]?.trim()||``),(r===`v7`||r===`v8`||r===`v9`||r===`v10`||r===`v11`)&&(ie=i[20]?.trim()||``),(r===`v8`||r===`v9`||r===`v10`||r===`v11`)&&i[21]?.trim()&&(ae=parseFloat(i[21]),isNaN(ae)))throw Error(`Invalid original_price "${i[21]}" at line ${e+1}`);(r===`v9`||r===`v10`||r===`v11`)&&(oe=i[22]?.trim()||``),(r===`v10`||r===`v11`)&&i[23]?.trim()&&(se=Ri(i[23],e+1));let ce,k,A,j,le,M;if(r===`v11`&&(ce=$(i[24],`exclude_auto_reset_sold_out`,e+1),k=$(i[25],`is_service_charge_exempt`,e+1),A=$(i[26],`is_tax_exempt`,e+1),le=$(i[28],`is_point_reward_exempt`,e+1),M=$(i[29],`is_credit_reward_exempt`,e+1)),r===`v11`&&i[27]?.trim()&&(j=Number(i[27]),isNaN(j)||j<0))throw Error(`Invalid is_pax_linked "${i[27]}" at line ${e+1}`);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:w,item_uid:v?.trim()||``,print_on_receipt:T,discountable:ee,open_editor_panel:te,is_delisted:ne,name_translations:E,prices:D,plu:re,code:O,barcode:ie,original_price:ae,codename:oe,config:se,exclude_auto_reset_sold_out:ce,is_service_charge_exempt:k,is_tax_exempt:A,is_pax_linked:j,is_point_reward_exempt:le,is_credit_reward_exempt:M})}return s}function Bi(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 Vi(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,O.Item+t());for(let t of e)if(t.type===`category`)a=new ye,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=ji(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 be,o.name=t.name,o.sequence=t.sequence||0,o.category_uid=a.uid,t.name_translations&&(o.name_translations=ji(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 Se,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`?F.Combo:F.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=ji(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),t.barcode&&(s.barcode=t.barcode),t.codename&&(s.codename=t.codename),t.original_price!==void 0&&(s.original_price=t.original_price),t.config&&(s.config=t.config),t.exclude_auto_reset_sold_out!==void 0&&(s.exclude_auto_reset_sold_out=t.exclude_auto_reset_sold_out),t.is_service_charge_exempt!==void 0&&(s.is_service_charge_exempt=t.is_service_charge_exempt),t.is_tax_exempt!==void 0&&(s.is_tax_exempt=t.is_tax_exempt),t.is_pax_linked!==void 0&&(s.is_pax_linked=t.is_pax_linked),t.is_point_reward_exempt!==void 0&&(s.is_point_reward_exempt=t.is_point_reward_exempt),t.is_credit_reward_exempt!==void 0&&(s.is_credit_reward_exempt=t.is_credit_reward_exempt),o&&(s.subcategory_uid=o.uid),r.push(s),c=null,l=null}else if(t.type===`combo_group`){if(!s||s.type!==F.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 Se,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 ve,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 xe;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=F.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.original_price!==void 0&&(e.original_price=t.original_price),t.name_translations&&(e.name_translations=ji(t.name_translations)),t.prices?.length){for(let n of t.prices)n.product_uid=e.uid;e.prices=t.prices}t.config&&(e.config=t.config),t.exclude_auto_reset_sold_out!==void 0&&(e.exclude_auto_reset_sold_out=t.exclude_auto_reset_sold_out),s.modifiers.push(e)}return{categories:n,products:r,discardedComboItems:i}}const Hi=`uid.name.sku.price.original_price.stock.is_internal.sequence.image_url.image_thumbnail_url.category_uid.subcategory_uid.type.plu.barcode.codename.print_on_receipt.discountable.open_editor_panel.is_delisted.name_translations.prices.modifiers.modifier_categories.combo_groups.config.exclude_auto_reset_sold_out.is_service_charge_exempt.is_tax_exempt.is_pax_linked.is_point_reward_exempt.is_credit_reward_exempt`.split(`.`),Ui=e=>e==null||e===``||Array.isArray(e)&&!e.length||e?.constructor===Object&&!Object.keys(e).length;function Wi(e,t){let n={...e};for(let e of Hi)Ui(t[e])||(n[e]=t[e]);return n}let Gi=function(e){return e.None=``,e.Always=`always`,e}({}),Ki=function(e){return e.Image=`image`,e.Video=`video`,e.Unsupported=`unsupported`,e}({}),qi=function(e){return e.CdsFullScreenImage=`cds_full_screen_image`,e.CdsHalfScreenImage=`cds_half_screen_image`,e}({});var Ji=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)}},Yi=class extends D{constructor(...e){super(...e),v(this,`uid`,O.Storage+t()),v(this,`model`,void 0),v(this,`data`,void 0)}},Xi=class extends D{constructor(...e){super(...e),v(this,`uid`,O.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 Zi=function(e){return e.In=`IN`,e.Out=`OUT`,e.Adjust=`ADJUST`,e.Production=`PRODUCTION`,e}({}),Qi=function(e){return e.Invoice=`invoice`,e.Purchase=`purchase`,e.Production=`production`,e.Stocktake=`stocktake`,e}({}),$i=function(e){return e.Item=`item`,e.Material=`material`,e}({});var ea=class extends E{constructor(){super(),v(this,`entity_type`,$i.Item),v(this,`entity_uid`,``),v(this,`type`,Zi.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`,O.StockLog+t())}};let ta=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}({}),na=function(e){return e.Pos=`pos`,e.Online=`online`,e.Phone=`phone`,e}({});var ra=class{constructor(){v(this,`uid`,O.AppointmentServiceLine+t()),v(this,`name`,``),v(this,`duration_in_minutes`,0),v(this,`price`,0),v(this,`quantity`,1),v(this,`is_custom`,!1)}},ia=class extends E{constructor(){super(),v(this,`uid`,O.Appointment+t()),v(this,`appointment_no`,``),v(this,`status`,ta.Confirmed),v(this,`source`,na.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 aa=[`#each`,`#if`,`#elseif`,`#else`,`#let`,`#merge`,`#concat`,`#include`,`#?`,`#flatten`];function oa(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];aa.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`)&&sa(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 sa(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,At as AlipayMethod,D as AppBaseModel,xt as AppConfig,E as AppCoreModel,pn as AppCoreService,re as AppExtraModel,mn as AppLocalService,ei as AppMiscService,J as AppRemoteService,yn as AppReport,ti as AppReportService,w as Applying,ia as Appointment,si as AppointmentService,ra as AppointmentServiceLine,na as AppointmentSource,ta as AppointmentStatus,qi as AssetTags,Ki as AssetType,ln as Between,St as Cache,q as CalcFlow,K as CalcType,Ot as CardPaymentCode,rn as CashDrawerConfig,ye as Category,On as CategorySalesSummary,Gr as CategoryService,_e as CategoryType,ht as Charge,Zt as ChargeConfig,I as Codepages,Ee as ComboGroup,Te as ComboGroupItem,Gi as Condition,Nt as Config,Kr as ConfigService,ve as CoreCategory,xe as CoreItem,T as Coupon,te as CouponItemized,ee as CouponUsage,Ct as CrmConfig,Qt as CurrencyConfig,x as Customer,Dt as CustomerDisplaySystemConfig,It as DeployChannel,Ve as Device,Ue as DeviceType,li as DiagnosticsService,ft as DiscountType,Sn as DrawerSummary,De as ElectronSocket,bt as Employee,fe as EmployeeRole,Hr as EmployeeRoleService,Ur as EmployeeService,A as ErrorMsgs,ze as EscPosCompatibility,Me as EscPosPrinter,Tt as EventPrintConfig,an as FileUploadRequest,nn as GTOConfig,zt as GeneralConfig,cn as In,sn as Include,en as InventoryConfig,yt as Invoice,ut as InvoiceAction,mt as InvoiceActivity,Rr as InvoiceBaseService,pt as InvoiceCharge,_t as InvoiceCoreLine,st as InvoiceDeviceType,gt as InvoiceDiscount,vt as InvoiceLine,Br as InvoiceOperationService,Vr as InvoiceService,G as InvoiceStatus,W as InvoiceType,Se as Item,En as ItemSalesSummary,Wr as ItemService,Wt as KdsConfig,jt as KioskSystemConfig,Ut as KitchenConfig,Gt as LabelConfig,zr as LineOperationService,Et as LoyaltyProgram,Tn as LoyaltyProgramSummary,Mt as MarketingConfig,Xi as Menu,ri as MenuService,Ji as Merchant,se as MessageType,O as ModelPrefix,ie as ModelType,Dn as ModifierSalesSummary,He as Node,We as NodePrinter,Cn as NonCashTillSummary,un as Not,ot as Note,at as NoteEntity,it as NoteGroup,rt as NoteGroupEntity,Ft as OnlineOrderConfig,Kt as OrderConfig,Nr as OrderDisplay,Fr as OrderDisplayService,Pr as OrderDisplayStatus,qt as OrderDisplaySystemConfig,ct as OrderFlow,tn as PaxConfig,Qe as Payment,Jt as PaymentConfig,$e as PaymentMethod,et as PaymentMethodHistory,Qr as PaymentMethodService,$r as PaymentService,nt as PaymentStatus,wn as PaymentSummary,Pt as PaynowMethod,we as Price,Ce as PriceType,Ne as PrintAlign,Ie as PrintBarcode,R as PrintCommand,Re as PrintImage,H as PrintJob,ni as PrintJobService,Je as PrintJobStatus,Le as PrintQrcode,Fe as PrintSize,Pe as PrintStyle,V as PrintTemplate,qe as PrintTemplateCore,ii as PrintTemplateService,L as PrintType,Xe as Printer,Ke as PrinterConnections,Ge as PrinterProtocols,kn as PrinterService,Ye as PrinterStatus,B as PrinterType,me as ProductBase,Rt as ProductConfig,Yr as ProductService,F as ProductType,ce as PushData,dn as Raw,Ht as Receipt,U as RenderPrintTemplateOptions,vn as Report,_n as ReportCategory,Vt as ReportConfig,bn as ReportData,gn as ReportType,$t as RoundingConfig,xn as SalesSummary,de as Section,ue as SectionItem,Jr as SectionItemService,P as SectionItemStatus,qr as SectionService,Si as ServiceFactory,ae as ServiceMode,oe as ServiceOptions,le as Shift,Xr as ShiftService,j as ShiftStatus,tt as StandardPaymentMethod,pe as StockChange,ea as StockLog,$i as StockLogEntityType,Qi as StockLogRefType,oi as StockLogService,Zi as StockLogType,Yi as Storage,ai as StorageService,be as Subcategory,ge as System,wt as SystemConfig,k as SystemError,Xt as TaxConfig,lt as TaxMethod,Ze as TemplateData,N as Till,Bt as TillConfig,Zr as TillService,M as TillType,dt as UomType,b as User,Yt as UserConfig,he as Visibility,kt as WechatPayMethod,hn as cloneItemData,Ei as createCSVExport,Di as createCSVExportWithHash,xi as dbSchemas,fn as filterByParams,Lt as getCategoryButtonShape,z as humanizedData,Fi as importFromCSV,Wi as mergeImportedItem,Be as normalizedDate,ne as transformer,oa as validateSTTemplate};
6
+ `);if(t.length===0)throw Error(`CSV file is empty`);let n=t[0].trim(),r=Gi(n),i=Ni[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=Xi(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(!Pi.includes(o))throw Error(`Invalid type "${o}" at line ${e+1}. Must be: ${Pi.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=$(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 w;if(_&&_.trim()&&(w=parseInt(_,10),isNaN(w)))throw Error(`Invalid sequence "${_}" at line ${e+1}`);let T,ee,te,ne,E=``,D,re=``,O=``,ie=``,ae,oe=``,se;if((r===`v3`||r===`v4`||r===`v5`||r===`v7`||r===`v8`||r===`v9`||r===`v10`||r===`v11`||r===`v12`)&&(T=$(i[12],`print_on_receipt`,e+1),ee=$(i[13],`discountable`,e+1),te=$(i[14],`open_editor_panel`,e+1),ne=$(i[15],`is_delisted`,e+1),E=i[16]?.trim()||``),(r===`v4`||r===`v5`||r===`v7`||r===`v8`||r===`v9`||r===`v10`||r===`v11`||r===`v12`)&&i[17]?.trim()&&(D=qi(i[17],e+1)),(r===`v5`||r===`v7`||r===`v8`||r===`v9`||r===`v10`||r===`v11`||r===`v12`)&&(re=i[18]?.trim()||``,O=i[19]?.trim()||``),(r===`v7`||r===`v8`||r===`v9`||r===`v10`||r===`v11`||r===`v12`)&&(ie=i[20]?.trim()||``),(r===`v8`||r===`v9`||r===`v10`||r===`v11`||r===`v12`)&&i[21]?.trim()&&(ae=parseFloat(i[21]),isNaN(ae)))throw Error(`Invalid original_price "${i[21]}" at line ${e+1}`);(r===`v9`||r===`v10`||r===`v11`||r===`v12`)&&(oe=i[22]?.trim()||``),(r===`v10`||r===`v11`||r===`v12`)&&i[23]?.trim()&&(se=Ji(i[23],e+1));let ce,k,A,j,le,M;if((r===`v11`||r===`v12`)&&(ce=$(i[24],`exclude_auto_reset_sold_out`,e+1),k=$(i[25],`is_service_charge_exempt`,e+1),A=$(i[26],`is_tax_exempt`,e+1),le=$(i[28],`is_point_reward_exempt`,e+1),M=$(i[29],`is_credit_reward_exempt`,e+1)),(r===`v11`||r===`v12`)&&i[27]?.trim()&&(j=Number(i[27]),isNaN(j)||j<0))throw Error(`Invalid is_pax_linked "${i[27]}" at line ${e+1}`);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:w,item_uid:v?.trim()||``,print_on_receipt:T,discountable:ee,open_editor_panel:te,is_delisted:ne,name_translations:E,prices:D,plu:re,code:O,barcode:ie,original_price:ae,codename:oe,config:se,exclude_auto_reset_sold_out:ce,is_service_charge_exempt:k,is_tax_exempt:A,is_pax_linked:j,is_point_reward_exempt:le,is_credit_reward_exempt:M,add_credit:Ki(i[30],`add_credit`,e+1),add_point:Ki(i[31],`add_point`,e+1),minus_point:Ki(i[32],`minus_point`,e+1)})}return s}function Xi(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 Zi(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,O.Item+t());for(let t of e)if(t.type===`category`)a=new De,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=Bi(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 Oe,o.name=t.name,o.sequence=t.sequence||0,o.category_uid=a.uid,t.name_translations&&(o.name_translations=Bi(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 Ae,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`?I.Combo:I.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=Bi(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),t.barcode&&(s.barcode=t.barcode),t.codename&&(s.codename=t.codename),t.original_price!==void 0&&(s.original_price=t.original_price),t.config&&(s.config=t.config),t.exclude_auto_reset_sold_out!==void 0&&(s.exclude_auto_reset_sold_out=t.exclude_auto_reset_sold_out),t.is_service_charge_exempt!==void 0&&(s.is_service_charge_exempt=t.is_service_charge_exempt),t.is_tax_exempt!==void 0&&(s.is_tax_exempt=t.is_tax_exempt),t.is_pax_linked!==void 0&&(s.is_pax_linked=t.is_pax_linked),t.is_point_reward_exempt!==void 0&&(s.is_point_reward_exempt=t.is_point_reward_exempt),t.is_credit_reward_exempt!==void 0&&(s.is_credit_reward_exempt=t.is_credit_reward_exempt);for(let e of[`add_credit`,`add_point`,`minus_point`])t[e]===void 0?delete s[e]:s[e]=t[e];o&&(s.subcategory_uid=o.uid),r.push(s),c=null,l=null}else if(t.type===`combo_group`){if(!s||s.type!==I.Combo)throw Error(`Combo group "${t.name}" found without a combo product`);l=new Pe,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 Ne;n.item_uid=e||t.item_uid||``,n.price=t.price||0,n.sequence=t.sequence||0,n.combo_item=new Ae,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 Ee,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 ke;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=I.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.original_price!==void 0&&(e.original_price=t.original_price),t.name_translations&&(e.name_translations=Bi(t.name_translations)),t.prices?.length){for(let n of t.prices)n.product_uid=e.uid;e.prices=t.prices}t.config&&(e.config=t.config),t.exclude_auto_reset_sold_out!==void 0&&(e.exclude_auto_reset_sold_out=t.exclude_auto_reset_sold_out),s.modifiers.push(e)}return{categories:n,products:r,discardedComboItems:i}}const Qi=`uid.name.sku.price.original_price.stock.is_internal.sequence.image_url.image_thumbnail_url.category_uid.subcategory_uid.type.plu.barcode.codename.print_on_receipt.discountable.open_editor_panel.is_delisted.name_translations.prices.modifiers.modifier_categories.combo_groups.config.exclude_auto_reset_sold_out.is_service_charge_exempt.is_tax_exempt.is_pax_linked.is_point_reward_exempt.is_credit_reward_exempt.add_credit.add_point.minus_point`.split(`.`),$i=e=>e==null||e===``||Array.isArray(e)&&!e.length||e?.constructor===Object&&!Object.keys(e).length;function ea(e,t){let n={...e};for(let e of Qi)$i(t[e])||(n[e]=t[e]);return n}let ta=function(e){return e.None=``,e.Always=`always`,e}({}),na=function(e){return e.Image=`image`,e.Video=`video`,e.Unsupported=`unsupported`,e}({}),ra=function(e){return e.CdsFullScreenImage=`cds_full_screen_image`,e.CdsHalfScreenImage=`cds_half_screen_image`,e}({});var ia=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)}},aa=class extends D{constructor(...e){super(...e),v(this,`uid`,O.Storage+t()),v(this,`model`,void 0),v(this,`data`,void 0)}},oa=class extends D{constructor(...e){super(...e),v(this,`uid`,O.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 sa=function(e){return e.In=`IN`,e.Out=`OUT`,e.Adjust=`ADJUST`,e.Production=`PRODUCTION`,e}({}),ca=function(e){return e.Invoice=`invoice`,e.Purchase=`purchase`,e.Production=`production`,e.Stocktake=`stocktake`,e}({}),la=function(e){return e.Item=`item`,e.Material=`material`,e}({});var ua=class extends E{constructor(){super(),v(this,`entity_type`,la.Item),v(this,`entity_uid`,``),v(this,`type`,sa.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`,O.StockLog+t())}};let da=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}({}),fa=function(e){return e.Pos=`pos`,e.Online=`online`,e.Phone=`phone`,e}({});var pa=class{constructor(){v(this,`uid`,O.AppointmentServiceLine+t()),v(this,`name`,``),v(this,`duration_in_minutes`,0),v(this,`price`,0),v(this,`quantity`,1),v(this,`is_custom`,!1)}},ma=class extends E{constructor(){super(),v(this,`uid`,O.Appointment+t()),v(this,`appointment_no`,``),v(this,`status`,da.Confirmed),v(this,`source`,fa.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 ha=[`#each`,`#if`,`#elseif`,`#else`,`#let`,`#merge`,`#concat`,`#include`,`#?`,`#flatten`];function ga(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];ha.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`)&&_a(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 _a(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,zt as AlipayMethod,D as AppBaseModel,At as AppConfig,E as AppCoreModel,Sn as AppCoreService,re as AppExtraModel,Cn as AppLocalService,li as AppMiscService,J as AppRemoteService,On as AppReport,ui as AppReportService,w as Applying,ma as Appointment,gi as AppointmentService,pa as AppointmentServiceLine,fa as AppointmentSource,da as AppointmentStatus,ra as AssetTags,na as AssetType,vn as Between,jt as Cache,q as CalcFlow,K as CalcType,Lt as CardPaymentCode,pn as CashDrawerConfig,De as Category,Ln as CategorySalesSummary,ei as CategoryService,Te as CategoryType,wt as Charge,sn as ChargeConfig,L as Codepages,Pe as ComboGroup,Ne as ComboGroupItem,ta as Condition,Ht as Config,ti as ConfigService,Ee as CoreCategory,ke as CoreItem,T as Coupon,te as CouponItemized,ee as CouponUsage,Mt as CrmConfig,cn as CurrencyConfig,x as Customer,It as CustomerDisplaySystemConfig,Gt as DeployChannel,Ye as Device,Ze as DeviceType,vi as DiagnosticsService,me as DirectiveNames,xt as DiscountType,jn as DrawerSummary,Fe as ElectronSocket,kt as Employee,fe as EmployeeRole,Zr as EmployeeRoleService,Qr as EmployeeService,A as ErrorMsgs,qe as EscPosCompatibility,Be as EscPosPrinter,Pt as EventPrintConfig,mn as FileUploadRequest,fn as GTOConfig,Jt as GeneralConfig,_n as In,gn as Include,un as InventoryConfig,Ot as Invoice,yt as InvoiceAction,Ct as InvoiceActivity,qr as InvoiceBaseService,St as InvoiceCharge,Et as InvoiceCoreLine,gt as InvoiceDeviceType,Tt as InvoiceDiscount,Dt as InvoiceLine,Yr as InvoiceOperationService,Xr as InvoiceService,G as InvoiceStatus,ht as InvoiceType,Ae as Item,Fn as ItemSalesSummary,$r as ItemService,$t as KdsConfig,Bt as KioskSystemConfig,Qt as KitchenConfig,en as LabelConfig,Jr as LineOperationService,Ft as LoyaltyProgram,Pn as LoyaltyProgramSummary,Vt as MarketingConfig,oa as Menu,fi as MenuService,ia as Merchant,se as MessageType,O as ModelPrefix,ie as ModelType,In as ModifierSalesSummary,Xe as Node,Qe as NodePrinter,Mn as NonCashTillSummary,yn as Not,mt as Note,pt as NoteEntity,ft as NoteGroup,dt as NoteGroupEntity,Wt as OnlineOrderConfig,tn as OrderConfig,Hr as OrderDisplay,Wr as OrderDisplayService,Ur as OrderDisplayStatus,nn as OrderDisplaySystemConfig,_t as OrderFlow,xe as PERMISSION_LABELS,he as PageNames,dn as PaxConfig,ot as Payment,rn as PaymentConfig,st as PaymentMethod,ct as PaymentMethodHistory,si as PaymentMethodService,ci as PaymentService,ut as PaymentStatus,Nn as PaymentSummary,Ut as PaynowMethod,Me as Price,je as PriceType,Ve as PrintAlign,We as PrintBarcode,z as PrintCommand,Ke as PrintImage,U as PrintJob,di as PrintJobService,nt as PrintJobStatus,Ge as PrintQrcode,Ue as PrintSize,He as PrintStyle,H as PrintTemplate,tt as PrintTemplateCore,pi as PrintTemplateService,R as PrintType,it as Printer,et as PrinterConnections,$e as PrinterProtocols,Rn as PrinterService,rt as PrinterStatus,V as PrinterType,Se as ProductBase,qt as ProductConfig,ii as ProductService,I as ProductType,ce as PushData,bn as Raw,Zt as Receipt,W as RenderPrintTemplateOptions,Dn as Report,En as ReportCategory,Xt as ReportConfig,kn as ReportData,Tn as ReportType,ln as RoundingConfig,pe as RouteNames,ge as SYSTEM_ROLES,An as SalesSummary,de as Section,ue as SectionItem,ri as SectionItemService,P as SectionItemStatus,ni as SectionService,ji as ServiceFactory,ae as ServiceMode,oe as ServiceOptions,le as Shift,ai as ShiftService,j as ShiftStatus,lt as StandardPaymentMethod,F as StockChange,ua as StockLog,la as StockLogEntityType,ca as StockLogRefType,hi as StockLogService,sa as StockLogType,aa as Storage,mi as StorageService,Oe as Subcategory,we as System,Nt as SystemConfig,k as SystemError,on as TaxConfig,vt as TaxMethod,at as TemplateData,N as Till,Yt as TillConfig,oi as TillService,M as TillType,bt as UomType,b as User,an as UserConfig,Ce as Visibility,Rt as WechatPayMethod,wn as cloneItemData,Fi as createCSVExport,Ii as createCSVExportWithHash,Ai as dbSchemas,xn as filterByParams,ve as functionValues,Kt as getCategoryButtonShape,B as humanizedData,Wi as importFromCSV,ye as itemEditorValues,ea as mergeImportedItem,Je as normalizedDate,be as pageValues,_e as routeValues,ne as transformer,ga as validateSTTemplate};
7
7
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@posx/core",
3
- "version": "5.5.722",
3
+ "version": "5.5.724",
4
4
  "description": "POSX core libraries",
5
5
  "type": "module",
6
6
  "main": "./build/index.js",