@posx/core 5.5.507 → 5.5.509
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/CLAUDE.md +23 -23
- package/LICENSE +21 -21
- package/README.md +85 -85
- package/build/index.d.ts +5 -0
- package/build/index.js +2 -2
- package/dev/.stfolder/syncthing-folder-9a95b7.txt +5 -0
- package/dev/98894488.xlsx +0 -0
- package/dev/HappyThaiSembawang.csv +336 -0
- package/dev/KB/create-new-model.md +34 -0
- package/dev/KB/markdown-lint.md +14 -0
- package/dev/KB/readmefirst.md +6 -0
- package/dev/Merchants/HappyThaiSembawang.csv +400 -0
- package/dev/Merchants/HappyThaiSembawang.xlsx +0 -0
- package/dev/Product_Import_Template.xlsx +0 -0
- package/dev/XPOS Invoice Module.pdf +232 -0
- package/dev/data/invoice.json +1 -0
- package/dev/escpos/receipt.bin +0 -0
- package/dev/escpos/receipt.hex +1 -0
- package/dev/escpos/receipt.json +1 -0
- package/dev/escpos-cli-usage.md +103 -0
- package/dev/harbor-harness-deployment.md +78 -0
- package/dev/nginx-harbor-harness.conf +84 -0
- package/dev/px-cli.md +97 -0
- package/dev/test-logs/2026-02.md +5 -0
- package/dev/tmp/xpos_product_import(1).csv +338 -0
- package/dev/tmp/xpos_product_import_fixed.csv +338 -0
- package/dev//344/272/247/345/223/201/345/257/274/345/205/245/346/250/241/346/235/277.xlsx +0 -0
- package/jest.config.cjs +36 -36
- package/jest.setup.cjs +80 -80
- package/package.json +1 -1
- package/package.publish.json +121 -121
- package/tsdown.config.ts +21 -21
- package/vite.config.ts +86 -86
- package/AGENTS.md +0 -24
- package/memo/technical-docs/01_ARCHITECTURE.md +0 -147
- package/memo/technical-docs/02_CORE_BUSINESS.md +0 -292
- package/memo/technical-docs/03_UI_COMPONENTS.md +0 -59
- package/memo/technical-docs/04_VIEWS.md +0 -82
- package/memo/technical-docs/05_DATA_LAYER.md +0 -375
- package/memo/technical-docs/06_CROSS_PLATFORM.md +0 -246
- package/memo/technical-docs/07_SIMILARITY_INDEX.md +0 -195
- package/memo/technical-docs/CHECKPOINT.md +0 -46
- package/memo/technical-docs/PROJECT_OVERVIEW.md +0 -122
- package/memo/technical-docs/TECHNICAL_DOCS_PLAN.md +0 -77
package/build/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import e from"dayjs";import{nanoid as t}from"nanoid";import n from"esc-pos-encoder-ionic";import r from"wcwidth";import{Dexie as i,liveQuery as a}from"dexie";import{v4 as o}from"uuid";import*as s from"lodash";import c from"axios";import l from"crypto-js";import{SelectTransform as u}from"selecttransform";import{NetworkInterface as d}from"@awesome-cordova-plugins/network-interface";import f from"handlebars";import{QueryBuilder as p}from"@litepos/autoquery";import m from"bcryptjs";var ee=(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 te=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`,``)}},y=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`,``)}},b=class extends y{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`,``)}},ne=function(e){return e[e.All=1]=`All`,e[e.Inclusive=2]=`Inclusive`,e[e.Exclusive=3]=`Exclusive`,e}(ne||{}),re=function(e){return e[e.Flat=1]=`Flat`,e[e.Percent=2]=`Percent`,e}(re||{}),ie=class{constructor(){v(this,`applying_type`,ne.Inclusive),v(this,`applying_items`,[])}},ae=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`,re.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)}},oe=class{constructor(e){v(this,`invoice_uid`,``),e&&(this.invoice_uid=e.invoice_uid)}},se=class{constructor(e){v(this,`guid`,``),v(this,`coupon`,new ae),v(this,`is_multi_stores`,!1),v(this,`usage`,new oe),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 ae(e.coupon),this.is_multi_stores=e.is_multi_stores,this.usage=new oe(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 ce={from(t){return e(t).format(`YYYY-MM-DD HH:mm:ss`)},to(e){return e}};var x=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)}},S=class extends x{constructor(){super(),v(this,`name`,void 0),v(this,`name_translations`,{})}},le=class extends S{constructor(...e){super(...e),v(this,`description`,void 0),v(this,`description_translations`,{})}};let C=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}({}),ue=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}({}),de=function(e){return e.LOCAL=`local`,e.CLOUD=`cloud`,e}({});var fe=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 pe=function(e){return e.Data=`DataMessage`,e.Event=`EventMessage`,e}({});var me=class{constructor(){v(this,`model`,``),v(this,`data`,``),v(this,`has_many`,!1),v(this,`type`,pe.Data)}},w=class extends Error{constructor(e){super(e),this.name=`system_error`}};let T=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}({}),E=function(e){return e.Open=`opened`,e.Closed=`closed`,e}({});var he=class extends x{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`,E.Open),v(this,`uid`,C.Shift+t())}};let D=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 ge=class extends x{constructor(){super(),v(this,`user_uid`,``),v(this,`shift_uid`,``),v(this,`invoice_uid`,``),v(this,`type`,D.CashDeposit),v(this,`amount`,0),v(this,`note`,``),v(this,`uid`,C.Till+t())}};let O=function(e){return e.CLOSED=`closed`,e.OPENED=`opened`,e.PAYMENT=`payment`,e}({});var _e=class extends S{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`,C.SectionItem+t()),v(this,`invoice_uid`,``),v(this,`section_uid`,``),v(this,`status`,O.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,`soup_base_quota`,0),v(this,`soup_base_type`,0),v(this,`is_delete`,!1),v(this,`meta`,{}),v(this,`customer`,{})}},ve=class extends S{constructor(){super(),v(this,`sequence`,0),v(this,`uid`,C.Section+t())}},ye=class extends S{constructor(){super(),v(this,`permissions`,[]),v(this,`is_default`,!1),v(this,`uid`,C.EmployeeRole+t())}},be=class{constructor(e){v(this,`item_uid`,``),v(this,`quantity`,0),v(this,`modifiers`,[]),this.item_uid=e,this.quantity=0,this.modifiers=[]}},k=class extends le{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)}},xe=class{constructor(){v(this,`system`,Se.POS),v(this,`visible`,!1),v(this,`sequence`,0)}};let Se=function(e){return e.POS=`pos`,e.QrCodeOrder=`qr_code_order`,e}({}),Ce=function(e){return e.Product=`product`,e.Modifier=`modifier`,e}({});var we=class extends k{constructor(){super(),v(this,`type`,Ce.Modifier),v(this,`visibility`,[]),v(this,`uid`,C.ItemModifierCategory+t()),v(this,`max_order`,0),v(this,`min_order`,0),v(this,`is_delisted`,!1)}},Te=class extends k{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`,Ce.Product),v(this,`is_delisted`,!1),v(this,`subcategories`,[]),v(this,`uid`,C.Category+t()),v(this,`max_order`,0),v(this,`min_order`,0)}},Ee=class extends k{constructor(){super(),v(this,`category_uid`,``),v(this,`uid`,C.Subcategory+t())}};let A=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 De=class extends k{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`,A.Modifier),v(this,`barcode`,``),v(this,`category_uid`,``),v(this,`price`,0),v(this,`original_price`,0),v(this,`prices`,[]),v(this,`stock`,1e3),v(this,`print_on_receipt`,!0),v(this,`price_adjustable`,!1),v(this,`is_sold_out`,!1),v(this,`recipe`,``),v(this,`is_remark_disabled`,!1),v(this,`uid`,C.ItemModifier+t())}},j=class extends De{constructor(){super(),v(this,`codename`,``),v(this,`sku`,``),v(this,`recipe`,``),v(this,`barcode`,``),v(this,`type`,A.ByQuantity),v(this,`add_credit`,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`,C.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`,[])}},Oe=class extends x{constructor(){super(),v(this,`lookup_keys`,[]),v(this,`product_uid`,``),v(this,`uid`,C.Price+t()),v(this,`amount`,0),v(this,`name`,``),v(this,`name_translations`,{})}},ke=class{constructor(){v(this,`item_uid`,``),v(this,`combo_item`,new j),v(this,`price`,0),v(this,`sequence`,0),v(this,`meta`,{})}},Ae=class{constructor(){v(this,`uid`,C.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`,{})}},M=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(M,`State`,{CLOSED:0,OPENING:1,OPENED:2,CLOSING:3}),v(M,`electronSocket`,null);function je(e){return e===`69`}const Me={Ẳ: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 Ne(e,t=63){let n=[];for(let r of e)if(Me[r]!==void 0)n.push(Me[r]);else{let e=r.charCodeAt(0);e<=127?n.push(e):n.push(t)}return Uint8Array.from(n)}function Pe(){return typeof Socket>`u`?new M:new Socket}var Fe=class{constructor(){v(this,`socket`,void 0),this.socket=Pe(),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 t=new n,r=t.initialize();if(e.codepage&&!Object.values(N).includes(e.codepage)){let t=parseInt(e.codepage,10);r.raw([31,27,31,255,t,10,0])}else e.codepage&&Object.values(N).includes(e.codepage)?t.codepage(e.codepage):t.codepage(N.SimplifiedChinese);for(let t of e.items){if(!t)throw Error(`Item is undefined or null`);switch(t.style){case Le.Bold:r.bold(!0);break;case Le.Italic:r.italic(!0);break;case Le.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 P.Text:if(t.item?.text){if(t.item.size===Re.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(je(e.codepage)){let e=Ne(t.item.text);r.raw(Array.from(e))}else r.text(t.item.text,t.item.line_width??48);t.item.size===Re.Custom&&r.raw([29,33,0])}break;case P.Table:if(t.table){if(t.table.size===Re.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(n=>{if(je(e.codepage)){let e=Ne(n);r.raw(Array.from(e))}else r.text(n,t.table.line_width??48);r.newline()}),t.table.size===Re.Custom&&r.raw([29,33,0])}break;case P.Line:r.line(t.item?.text?.repeat(48)??`-`.repeat(48),t.item?.line_width??48);break;case P.NewLine:t.repeat=t.repeat??1;for(let e=0;e<t.repeat;e++)r.newline();break;case P.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 P.QRCode:t.qrcode&&r.qrcode(t.qrcode.data,t.qrcode.model,t.qrcode.size,t.qrcode.errorlevel);break;case P.Barcode:t.barcode&&r.barcode(t.barcode.data,t.barcode.symbology,t.barcode.height);break;case P.Cut:r.cut(t.item?.text??`full`);break;case P.Beeper:r.beeper();break;case P.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 n=Array.from(e).reduce((e,t)=>e+r(t),0);return e+` `.repeat(Math.max(0,t-n))}padStart(e,t){let n=Array.from(e).reduce((e,t)=>e+r(t),0);return` `.repeat(Math.max(0,t-n))+e}wrapText(e,t){if(typeof e!=`string`&&(e=e.toString()),!e)return[``];let n=[],i=``,a=0;for(let o of e){let e=r(o);a+e>t&&(n.push(i),i=``,a=0),i+=o,a+=e}return i&&n.push(i),n}async disconnect(){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 N=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}({}),Ie=function(e){return e.Left=`left`,e.Center=`center`,e.Right=`right`,e}({}),Le=function(e){return e.Normal=`normal`,e.Bold=`bold`,e.Italic=`italic`,e.Underline=`underline`,e}({}),Re=function(e){return e.Custom=`custom`,e.Normal=`normal`,e.Small=`small`,e}({}),P=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 ze=class{constructor(){v(this,`data`,``),v(this,`symbology`,`ean13`),v(this,`height`,0)}},Be=class{constructor(){v(this,`data`,``),v(this,`model`,2),v(this,`size`,6),v(this,`errorlevel`,`m`)}},Ve=class{constructor(){v(this,`base64_data`,``),v(this,`width`,0),v(this,`height`,0),v(this,`algorithm`,`threshold`),v(this,`threshold`,128)}};let He=function(e){return e[e.SunmiPrinter=0]=`SunmiPrinter`,e}({});var F=class{constructor(){v(this,`codepage`,N.WesternEuropeanLatin),v(this,`items`,[])}};function I(t,n){return e(t).format(n||`YYYY-MMM-DD HH:mm:ss`)}function Ue(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 We=class extends S{constructor(){super(),v(this,`machine_name`,``),v(this,`connection_id`,``),v(this,`type`,Ke.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:``})}},Ge=class extends S{constructor(){super(),v(this,`type`,Ke.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 Ke=function(e){return e.Client=`client`,e.Node=`node`,e}({}),L=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}({});var qe=class{constructor(){v(this,`printer_name`,``),v(this,`status`,``),v(this,`port_name`,``),v(this,`error`,``)}};let Je=function(e){return e.ESCPOS=`ESC/POS`,e.TSPL=`TSPL`,e}({}),Ye=function(e){return e.USB=`USB`,e.WINDOWS_DRIVER=`WINDOWS_DRIVER`,e.ETHERNET=`ETHERNET`,e.BLUETOOTH=`BLUETOOTH`,e.BUILTIN=`BUILTIN`,e}({});var Xe=class{constructor(){v(this,`header`,``),v(this,`body`,``),v(this,`footer`,``),v(this,`commands`,``),v(this,`type`,L.ReceiptPrinter)}},R=class extends S{constructor(){super(),v(this,`header`,``),v(this,`body`,``),v(this,`footer`,``),v(this,`commands`,``),v(this,`printer_type`,L.ReceiptPrinter),v(this,`codepage`,void 0),v(this,`uid`,C.PrintTemplate+t()),v(this,`report_code_name`,``)}};let Ze=function(e){return e.Queued=`queued`,e.Printed=`printed`,e.Failed=`failed`,e.Expired=`expired`,e}({});var z=class extends S{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`,L.ReceiptPrinter),v(this,`protocol`,Je.ESCPOS),v(this,`connection_type`,Ye.ETHERNET),v(this,`data`,new F),v(this,`status`,Ze.Queued),v(this,`retries`,0),v(this,`commands`,``),v(this,`uid`,C.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 Qe=function(e){return e.Online=`online`,e.Offline=`offline`,e}({});var $e=class extends S{constructor(){super(),v(this,`device_uid`,``),v(this,`type`,L.ReceiptPrinter),v(this,`is_not_default`,!1),v(this,`driver_printer_name`,``),v(this,`fallback_printer_uid`,0),v(this,`protocol`,Je.ESCPOS),v(this,`connection_type`,Ye.ETHERNET),v(this,`print_template_uid`,``),v(this,`uid`,C.Printer+t()),v(this,`ip_address`,``),v(this,`status`,Qe.Online),v(this,`kitchen_itemized_print`,!1),v(this,`print_times`,1),v(this,`retries`,1)}},et=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=I(this.printed_at)}},B=class{constructor(){v(this,`printer_name`,``),v(this,`kitchen_itemized_print`,!1),v(this,`is_cancel`,!1)}},tt=class extends x{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 nt),v(this,`payment_method_history`,void 0),v(this,`uid`,C.Payment+t()),v(this,`updated_at`,new Date)}},nt=class extends S{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,`uid`,C.PaymentMethod+t())}},rt=class extends nt{constructor(){super(),v(this,`changed_at`,new Date),v(this,`changed_by`,``)}},it=class{toPaymentMethod(){let e=new nt;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 at=function(e){return e.STARTED=`payment_started`,e.COMPLETED=`payment_completed`,e.FAILED=`payment_failed`,e.CANCELLED=`payment_cancelled`,e}({});var ot=class extends S{constructor(){super()}},st=class extends ot{constructor(){super()}},ct=class extends S{constructor(){super(),v(this,`note_group_uid`,``),v(this,`related_model`,ue.Invoice),v(this,`usage`,0)}},lt=class extends ct{constructor(){super()}};let V=function(e){return e.DineIn=`dine_in`,e.TakeOut=`take_out`,e.Delivery=`delivery`,e}({}),ut=function(e){return e.PayToOrder=`pay_to_order`,e.OrderFirstAndPayLater=`order_first_and_pay_later`,e.OnSelection=`on_selection`,e}({}),dt=function(e){return e.Inclusive=`inclusive`,e.Exclusive=`exclusive`,e}({}),H=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}({}),ft=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}({}),pt=function(e){return e.quantity=`quantity`,e.weight=`weight`,e}({}),U=function(e){return e.Flat=`flat`,e.Percent=`percent`,e}({}),W=function(e){return e.AfterSubtotal=`after_subtotal`,e.AfterServiceCharge=`after_service_charge`,e.AfterGrantTotal=`after_grant_total`,e}({}),mt=function(e){return e.Custom=`custom`,e.Voucher=`voucher`,e.Coupon=`coupon`,e}({});var ht=class{constructor(){v(this,`uid`,C.InvoiceCharge+t()),v(this,`name`,``),v(this,`percentage`,0),v(this,`amount`,0),v(this,`calc_flow`,W.AfterSubtotal)}},gt=class{constructor(){v(this,`action`,ft.Create),v(this,`action_by`,``),v(this,`device_uid`,``),v(this,`action_at`,new Date)}},_t=class{constructor(){v(this,`uid`,C.Charge+t()),v(this,`name`,``),v(this,`percent`,0),v(this,`calc_flow`,W.AfterSubtotal),v(this,`trigger_condition`,``)}},vt=class{constructor(){v(this,`calc_type`,U.Flat),v(this,`amount`,0),v(this,`percent`,0),v(this,`percent_amount`,0),v(this,`type`,mt.Custom),v(this,`calc_flow`,W.AfterSubtotal),v(this,`applying_item_uids`,[]),v(this,`name`,``),v(this,`name_translation`,{}),v(this,`voucher_uid`,``),v(this,`coupon_uid`,``),v(this,`uid`,C.InvoiceDiscount+t())}},yt=class{constructor(){v(this,`item_uid`,``),v(this,`item`,new De),v(this,`price`,0),v(this,`unit_of_measure`,pt.quantity),v(this,`quantity`,0),v(this,`sent`,0),v(this,`is_cancel_printed`,!1),v(this,`selected`,!1),v(this,`sales_user_uid`,``)}},bt=class extends x{constructor(){super(),v(this,`item_uid`,``),v(this,`price`,0),v(this,`unit_of_measure`,pt.quantity),v(this,`quantity`,0),v(this,`remark`,``),v(this,`invoice_uid`,``),v(this,`discount_calc_type`,U.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 j),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,`is_cancel_printed`,!1),v(this,`selected`,!1),v(this,`sales_user_uid`,``),v(this,`meta`,{})}},xt=class extends x{constructor(){super(),v(this,`ref_id`,``),v(this,`call_num`,``),v(this,`table_uid`,``),v(this,`table_name`,``),v(this,`type`,V.DineIn),v(this,`pax`,0),v(this,`adult_pax`,0),v(this,`child_pax`,0),v(this,`baby_pax`,0),v(this,`subtotal`,0),v(this,`point_subtotal`,0),v(this,`service_chargeable_subtotal`,0),v(this,`discountable_subtotal`,0),v(this,`service_charge`,0),v(this,`delivery_id`,0),v(this,`delivery_charge`,0),v(this,`delivery_type`,``),v(this,`delivery_by`,``),v(this,`use_customer_point`,!1),v(this,`add_point`,0),v(this,`minus_point`,0),v(this,`rewarded_point_rate`,0),v(this,`rewarded_point`,0),v(this,`use_customer_balance`,!1),v(this,`add_credit`,0),v(this,`minus_credit`,0),v(this,`rewarded_credit_rate`,0),v(this,`rewarded_credit`,0),v(this,`discounts`,[]),v(this,`discount_amount`,0),v(this,`tax`,0),v(this,`rounding`,0),v(this,`tip`,0),v(this,`grand_total`,0),v(this,`customer_id`,0),v(this,`remark`,``),v(this,`sales_user_uid`,``),v(this,`status`,H.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 te),v(this,`payment_source_method`,``),v(this,`payment_source_last4`,``),v(this,`payment_source_charge_ref`,``),v(this,`is_sales_exclusive`,!1),v(this,`etc`,{}),v(this,`action`,void 0),v(this,`lines`,[]),v(this,`deleted_lines`,[]),v(this,`payment_has_cash`,!1),v(this,`payments`,[]),v(this,`table_switch_id`,0),v(this,`employee_uid`,``),v(this,`employee_name`,``),v(this,`receipt_print_override`,!1),v(this,`customer`,new b),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,`charges`,[]),v(this,`is_charge_triggered`,!1),v(this,`uid`,C.Invoice+t()),v(this,`meta`,{}),v(this,`price_lookup_key`,``)}},St=class extends x{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`,C.Employee+t()),v(this,`role_uid`,``),v(this,`language`,`en`),v(this,`can_login`,!0)}},Ct=class extends x{constructor(){super(),v(this,`config`,new jt),v(this,`cache`,new wt),v(this,`storage`,{pricing_lookup_keys:[],pay_in_reasons:[],pay_out_reasons:[]})}},wt=class{constructor(){v(this,`printers`,[])}},Tt=class{constructor(){}},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`)}},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)}};let Ot=function(e){return e.SmoochPay=`SPCD`,e.YeahPay=`YEAP`,e}({});var kt=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,`landing_image`,``),v(this,`menu_banner_image`,``),v(this,`home_page_images`,[]),v(this,`paynow_method`,Mt.WyoPaynow),v(this,`card_payment_code`,Ot.SmoochPay)}},At=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})}},jt=class{constructor(){v(this,`general`,new It),v(this,`product`,new Ft),v(this,`till`,new Lt),v(this,`report`,new Rt),v(this,`receipt`,new zt),v(this,`kitchen`,new Bt),v(this,`kds`,new Vt),v(this,`label`,new Ht),v(this,`order`,new Ut),v(this,`ods`,new Wt),v(this,`payment`,new Gt),v(this,`user`,new Kt),v(this,`tax`,new qt),v(this,`rounding`,new Xt),v(this,`inventory`,new Zt),v(this,`pax_config`,new Qt),v(this,`gto`,new $t),v(this,`cash_drawer`,new en),v(this,`marketing`,new At),v(this,`charges`,new Jt),v(this,`currency`,new Yt),v(this,`cds`,new Dt),v(this,`kiosk`,new kt),v(this,`online_order`,new Nt),v(this,`loyalty_program`,new Et),v(this,`crm`,new Tt)}};let Mt=function(e){return e.FomoOnlinePaynow=`PNWO`,e.WyoPaynow=`WPPN`,e}({});var Nt=class{constructor(){v(this,`enable_membership`,!1),v(this,`login_call_to_action_text`,``),v(this,`menu_banner_image_url`,``),v(this,`paynow_method`,void 0),v(this,`disable_pay_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:ut.OrderFirstAndPayLater,select_order_flow:!1,select_menus:!1}),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`,{})}};let Pt=function(e){return e.PROD=`prod`,e.DEV=`dev`,e}({});var Ft=class{constructor(){v(this,`enable_codename_search`,!1)}},It=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`,Pt.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`}}])}},Lt=class{constructor(){v(this,`control`,!0),v(this,`slip`,!0)}},Rt=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,`hide_non_price_item`,!1),v(this,`receipt_no_reset_daily`,!1),v(this,`language`,`en`),v(this,`disable_persistent_tcp`,!1)}},Bt=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`)}},Vt=class{constructor(){v(this,`enabled`,!0),v(this,`display_order_after_payment`,!1),v(this,`print_slip_upon_completed`,!1)}},Ht=class{constructor(){v(this,`print`,!1),v(this,`text_to_raster`,!1)}},Ut=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`)}},Wt=class{constructor(){v(this,`enabled`,!1),v(this,`language`,`en`)}},Gt=class{constructor(){v(this,`quick_cash_payment`,!1),v(this,`notification`,!0),v(this,`quick`,!1)}},Kt=class{constructor(){v(this,`control`,!0)}},qt=class{constructor(){v(this,`enabled`,!0),v(this,`method`,dt.Inclusive),v(this,`rate`,7),v(this,`name`,`GST`)}},Jt=class{constructor(){v(this,`service_charge`,!1),v(this,`service_charge_rate`,10)}},Yt=class{constructor(){v(this,`currency_symbol`,`$`),v(this,`is_symbol_after_amount`,!1)}},Xt=class{constructor(){v(this,`base`,.1),v(this,`up`,!0),v(this,`cashless`,!1),v(this,`prepayment_rounding`,!1)}},Zt=class{constructor(){v(this,`inventory_control`,!1),v(this,`sold_out_for_today_only`,!1)}},Qt=class{constructor(){v(this,`pax`,!0),v(this,`detail`,!1)}},$t=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`)}},en=class{constructor(){v(this,`kick_code`,`27, 112, 48, 55, 121`),v(this,`connection_mode`,`via_receipt_printer`)}},tn=class{constructor(e){v(this,`name`,``),v(this,`base64`,``),v(this,`extension`,`png`),Object.assign(this,e)}};const nn=e=>e===``||e===void 0,rn=e=>t=>nn(e)||t.includes(e),an=e=>t=>nn(e)||e.includes(t),on=(e,t)=>n=>n>e&&n<t,sn=e=>typeof e==`function`?(t,n)=>!e(t,n):t=>t!=e,cn=e=>e,ln=e=>t=>!t.deleted_at&&Object.keys(e).every(n=>{if(nn(e[n])||t[n]===e[n])return!0;if(typeof e[n]==`function`)return e[n](t[n],t)});var un=class{constructor(){v(this,`db`,void 0),v(this,`moduleName`,void 0)}get table(){return this.db.table(this.moduleName)}liveQuery(e){return a(e)}async saveOne(e){let n={...e};return n.created_at||(n.created_at=new Date),n.uid||(n.uid=t()),n.updated_at=new Date,await this.db.table(this.moduleName).put(n),n}async saveMany(e){let n=e.map(e=>(e.uid||(e.uid=t(),e.created_at=new Date),e.updated_at=new Date,e));return await this.db.table(this.moduleName).bulkPut(n),n}async hasAny(){return await this.db.table(this.moduleName).count()>0}async getOne(e){return await this.db.table(this.moduleName).get(e)||null}async getOneByParams(e){return this.db.table(this.moduleName).filter(ln(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(ln(e)).count(),o=this.db.table(this.moduleName).filter(ln(e));return r!==-1&&o.offset((n-1)*r).limit(r),{list:await o.toArray(),count:a,page:n,pageSize:r}}},dn=class extends un{async updateOne(e,t){throw Error(`Method not implemented.`)}async deleteOne(e){throw Error(`Method not implemented.`)}},G=class extends un{constructor(...e){super(...e),v(this,`http`,void 0),v(this,`methodName`,void 0),v(this,`options`,void 0)}async addOne(e){return this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${this.methodName}`,e)}async updateOne(e,t){return this.http.patch(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${e}`,t)}async updateMany(e){return this.http.patch(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}`,e)}async deleteOne(e){return e.deleted_at=new Date,this.http.delete(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${e.id_in_server}`)}async hardDeleteOne(e){return await this.db.table(this.moduleName).delete(e.uid),e}};let fn=function(e){return e[e.printable=0]=`printable`,e[e.generative=1]=`generative`,e}({});var pn=class{constructor(){v(this,`uid`,C.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)}},mn=class{constructor(){v(this,`uid`,C.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)}},hn=class extends x{constructor(){super(),v(this,`uid`,C.AppReport+t()),v(this,`reports`,[]),v(this,`version`,1)}},gn=class{constructor(){v(this,`start_datetime`,``),v(this,`humanized_start_datetime`,``),v(this,`end_datetime`,``),v(this,`humanized_end_datetime`,``),v(this,`humanized_printed_datetime`,``),v(this,`sales_summary`,new _n),v(this,`drawer_summary`,new vn),v(this,`payments_summary`,[]),v(this,`loyalty_program_summary`,new bn),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`,{})}},_n=class{constructor(){v(this,`sales_total`,0),v(this,`foc_sales_total`,0),v(this,`foc_sales_count`,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)}},vn=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)}},yn=class{constructor(){v(this,`code`,``),v(this,`name`,``),v(this,`total`,0),v(this,`count`,0)}},bn=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)}},xn=class{constructor(){v(this,`item`,{}),v(this,`quantity`,0),v(this,`total_amount`,0),v(this,`modifiers`,[])}},Sn=class{constructor(){v(this,`item`,{}),v(this,`quantity`,0),v(this,`total_amount`,0)}},Cn=class{constructor(){v(this,`category`,null),v(this,`items`,[]),v(this,`total_quantity`,0),v(this,`total_amount`,0)}},wn=class extends G{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 Rr(e,t,n,`configs`,`config`),this.printJobService=new X(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(L.ReceiptPrinter)}async getDefaultPrinterByType(e){return this.getDefaultPrinter(e)}async getDefaultKioskPrinter(){return this.getDefaultPrinter(L.KioskPrinter)}async getDefaultCheckPrinter(){return this.getDefaultPrinter(L.CheckPrinter)}async getDefaultKitchenPrinter(){return this.getDefaultPrinter(L.KitchenPrinter)}async getDefaultOrderPrinter(){return this.getDefaultPrinter(L.OrderPrinter)}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 d.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 Fe().connect(s,t,200)&&n.push(s)}return await this.configService.updateCache({printers:n}),n}async openCashDrawer(){let e=await this.getDefaultReceiptPrinter(),t=new F;t.items.push({type:P.OpenCashDrawer});let n=new z(e,t,!1,1);await this.printJobService.addOne(n)}};function K(e,t=2){let n=10**t;return Math.round(e*n)/n}function Tn(e){let t=e.name,n=t.lastIndexOf(`.`);return n===-1||n===t.length-1?``:t.slice(n+1)}function En(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 q=(e,t)=>e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/[_\-\.]+/g,` `).toLowerCase().replace(/[\s]+(\w)/g,(e,n)=>t(n)),Dn=e=>e.replace(/^\W+|\W+$/g,``),On=e=>typeof e==`string`?q(e,e=>e.toUpperCase()):``,kn=e=>typeof e==`string`?e.charAt(0).toUpperCase()+e.slice(1):``,An=e=>typeof e==`string`?e.replace(/\w\S*/g,e=>kn(e)):``,jn=e=>typeof e==`string`?q(e,e=>`-`+e):``,Mn=e=>typeof e==`string`?q(e,e=>`.`+e):``,Nn=e=>Pn(e),Pn=e=>typeof e==`string`?e.toLowerCase():``,Fn=e=>{if(typeof e!=`string`)return``;let t=q(e,e=>e.toUpperCase());return t.charAt(0).toUpperCase()+t.slice(1)},In=e=>typeof e==`string`?q(e,e=>`/`+e):``,Ln=e=>typeof e==`string`?e.replace(/((?:\S[^\.\?\!]*)[\.\?\!]*)/g,e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()):``,Rn=e=>typeof e==`string`?q(e,e=>`_`+e):``,zn=e=>typeof e==`string`?e.replace(/[- _]+/g,` `).split(` `).map(e=>kn(e)).join(` `):``,Bn=e=>Vn(e),Vn=e=>typeof e==`string`?e.toUpperCase():``,Hn=(e,t)=>typeof e==`string`&&typeof t==`string`?e+t:e,Un=(e,t)=>{if(typeof e!=`string`)return``;let n=``;for(let e=0;e<t;e++)n+=` `;return n+e+n},Wn=e=>typeof e==`string`?Dn(e):``,Gn=e=>typeof e==`string`?e.split(` `).join(`-`):``,Kn=(e,t=` `)=>typeof e==`string`?(typeof t!=`string`&&(t=` `),e.split(t).join(`+`)):``,qn=(e,t)=>typeof e==`string`&&typeof t==`string`?t+e:e,Jn=(e,t)=>typeof e==`string`?typeof t==`string`?e.split(t).join(``):e:``,Yn=(e,t)=>typeof e==`string`?typeof t==`string`?e.replace(t,``):e:``,Xn=(e,t,n)=>typeof e==`string`?typeof t==`string`?(typeof n!=`string`&&(n=``),e.split(t).join(n)):e:``,Zn=(e,t,n)=>typeof e==`string`?typeof t==`string`?(typeof n!=`string`&&(n=``),e.replace(t,n)):e:``,Qn=e=>typeof e==`string`?e.split(``).reverse().join(``):``,$n=(e,t=`,`)=>typeof e==`string`?(typeof t!=`string`&&(t=`,`),e.split(t)):[],er=(e,t)=>typeof e==`string`?e.length<=t?e:ir(e,t)+`…`:``,tr=e=>typeof e==`string`?e.trim():``,nr=e=>typeof e==`string`?e.replace(/^\s+/,``):``,rr=e=>typeof e==`string`?e.replace(/\s+$/,``):``,ir=(e,t,n=``)=>typeof e==`string`?(typeof n!=`string`&&(n=``),e.length>t?e.slice(0,t-n.length)+n:e):``;var ar={camelcase:On,capitalize:kn,capitalizeAll:An,dashcase:jn,dotcase:Mn,downcase:Nn,lowercase:Pn,pascalcase:Fn,pathcase:In,sentence:Ln,snakecase:Rn,titleize:zn,upcase:Bn,uppercase:Vn,append:Hn,center:Un,chop:Wn,hyphenate:Gn,plusify:Kn,prepend:qn,remove:Jn,removeFirst:Yn,replace:Xn,replaceFirst:Zn,reverse:Qn,split:$n,ellipsis:er,trim:tr,trimLeft:nr,trimRight:rr,truncate:ir,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 or=e=>e&&typeof e==`object`&&typeof e.fn==`function`,J=(e,t,n)=>or(n)?e?n.fn?n.fn(t):!0:n.inverse?n.inverse(t):!1:e,sr=function(...e){let t=e.pop();return J(e.every(e=>!!e),this,t)},cr=function(...e){let t=e.pop();return J(e.some(e=>!!e),this,t)},lr=function(e,t){return J(!e,this,t)},ur=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),J(e===t,this,n)},dr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),J(e==t,this,n)},fr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),J(e!==t,this,n)},pr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),J(e!=t,this,n)},mr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),J(e>t,this,n)},hr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),J(e>=t,this,n)},gr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),J(e<t,this,n)},_r=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),J(e<=t,this,n)},vr=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 J(i,this,r)},yr=function(e,t,n){return typeof n==`number`&&(n=arguments[3]),J(e==null?!1:Array.isArray(e)||typeof e==`string`?e.includes(t):typeof e==`object`?t in e:!1,this,n)},br=yr,xr=function(e,...t){let n=t.pop();return J(t.includes(e),this,n)},Sr=(e,t)=>{if(!(!e||!t))return t.split(`.`).reduce((e,t)=>e?.[t],e)},Cr=e=>{let t=[];for(let n=0;n<e.length-1;n+=2)typeof e[n]==`string`&&!or(e[n+1])&&t.push({prop:e[n],value:e[n+1]});return t};var wr={and:sr,or:cr,not:lr,eq:ur,is:dr,neq:fr,isnt:pr,gt:mr,gte:hr,lt:gr,lte:_r,compare:vr,contains:yr,includes:br,in:xr,findAnd:function(e,...t){if(!Array.isArray(e))return null;let n=Cr(t);return e.find(e=>n.every(t=>Sr(e,t.prop)===t.value))||null},findOr:function(e,...t){if(!Array.isArray(e))return null;let n=Cr(t);return e.find(e=>n.some(t=>Sr(e,t.prop)===t.value))||null},filterAnd:function(e,...t){if(!Array.isArray(e))return[];let n=Cr(t);return e.filter(e=>n.every(t=>Sr(e,t.prop)===t.value))},filterOr:function(e,...t){if(!Array.isArray(e))return[];let n=Cr(t);return e.filter(e=>n.some(t=>Sr(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 J(!e&&!t,this,n)},ifEven:function(e,t){return J(e%2==0,this,t)},ifOdd:function(e,t){return J(e%2!=0,this,t)},ifNth:function(e,t,n){return J(typeof e==`number`&&typeof t==`number`&&t%e===0,this,n)}};function Tr(e){let t=e?.handlebars||e?.hbs||ee(`handlebars`);return Object.keys(ar).forEach(e=>{t.registerHelper(e,ar[e])}),Object.keys(wr).forEach(e=>{t.registerHelper(e,wr[e])}),t.helpers}var Er=Tr,Dr=class extends x{constructor(){super(),v(this,`uid`,C.OrderDisplaySystem+t()),v(this,`order_number`,``),v(this,`status`,Y.Preparing)}};let Y=function(e){return e.Preparing=`preparing`,e.ReadyForPickup=`ready_for_pickup`,e}({});var Or=class extends G{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 w(`Display order not found`);if(t.status==`ready_for_pickup`)throw new w(`Order is already ready for pickup`);if(t.status=Y.ReadyForPickup,t.updated_at=new Date,t.id_in_server==0)throw new w(`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 w(`Display order not found`);if(t.status==`preparing`)throw new w(`Order is already preparing`);if(t.status=Y.Preparing,t.updated_at=new Date,t.id_in_server==0)throw new w(`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==Y.ReadyForPickup).reverse().limit(100).toArray();if(e.length===0)throw new w(`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=Y.Preparing,t.updated_at=new Date,t.id_in_server==0)throw new w(`Order is not synced with server`);return await this.updateOne(t.id_in_server,t),t}};Er({handlebars:f});const kr={quantity:1,price:0,remark:``};var Ar=class extends G{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,`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 Ur(e,t,n,`tills`,`till`),this.sectionItemService=new Br(e,t,n,`section_items`,`section_item`),this.configService=new Rr(e,t,n,`configs`,`config`),this.printTemplateService=new Yr(e,t,n,`print_templates`,`print_template`),this.printerService=new wn(e,t,n,`printers`,`printer`),this.printJobService=new X(e,t,n,`print_jobs`,`print_job`),this.itemService=new Ir(e,t,n,`items`,`item`),this.orderDisplayService=new Or(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,W.AfterSubtotal),e.grand_total<0&&(e.grand_total=0,e.service_chargeable_subtotal=0),this.calculateInvoiceCharges(e,W.AfterSubtotal),e.subtotal>0&&e.discount_amount>0){let t=1-e.discount_amount/e.subtotal;e.service_chargeable_subtotal=K(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,W.AfterServiceCharge),e.grand_total<0&&(e.grand_total=0),this.calculateInvoiceCharges(e,W.AfterServiceCharge);let i=t.config.tax.enabled?t.config.tax.rate:0;return this.calculateTax(e,i,t.config.tax.method),this.calculateDeliveryCharge(e),this.calculateCreditDeduction(e),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,W.AfterGrantTotal),e.grand_total<0&&(e.grand_total=0),this.calculateInvoiceCharges(e,W.AfterGrantTotal),e.grand_total=K(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),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+=K(n.subtotal,2),e.point_subtotal+=n.point_subtotal;e.subtotal=K(t,2),e.grand_total=K(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=K(e.quantity*(e.price+t),2),e.item.discountable&&(e.discount_amount>0||e.discount_percent>0)&&(e.discount_calc_type==U.Flat||(e.discount_amount=K(e.subtotal*e.discount_percent,2)),e.subtotal-=e.discount_amount),e.subtotal=K(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=K(K(e.lines.filter(e=>!e.is_take_out&&!e.item.is_service_charge_exempt).reduce((e,t)=>e+t.subtotal,0)),2)}calculateDiscount(e,t){if(!e?.lines?.length)return;let n=0;if(e.discountable_subtotal=K(e.lines.filter(e=>e.item.discountable).reduce((e,t)=>e+t.subtotal,0),2),e.discounts?.length){for(let r of e.discounts.filter(e=>e.calc_flow==t))if(!r.applying_item_uids?.length)r.calc_type==U.Flat?n+=r.amount:(r.percent_amount=K((e.discountable_subtotal-e.discount_amount-n)*r.percent),n+=r.percent_amount);else{let t=0,i=!1;for(let n of e.lines)r.applying_item_uids.includes(n.item_uid)&&n.price>t&&(t=n.price,i=!0);if(!i){e.discounts=e.discounts.filter(e=>e.uid!=r.uid);continue}r.calc_type==U.Flat?(r.amount=K(r.amount>t?t:r.amount),n+=r.amount):(r.percent_amount=K(t*r.percent),n+=r.percent_amount)}e.discount_amount+=K(n),e.grand_total=K(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=K(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,K(s/100)}calculateDeliveryCharge(e){e.delivery_charge>0&&e.type===V.Delivery&&(e.grand_total+=e.delivery_charge,e.grand_total=K(e.grand_total,2))}calculateServiceCharge(e,t){let n=0;e.service_charge=0,!(e.lines==null||e.lines.length<1)&&(e.type==V.Delivery||e.type==V.TakeOut||(t>0&&(n=e.service_chargeable_subtotal*(t/100)),e.service_charge=K(n,2),e.grand_total+=e.service_charge,e.grand_total=K(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===dt.Inclusive?e.tax=K(i*r*t/(100+t)+e.service_charge*t/(100+t),2):(e.tax=K(i*r*t/100+e.service_charge*t/100,2),e.grand_total=K(e.grand_total+e.tax,2))}calculateCreditDeduction(e){e.minus_credit>0&&(e.minus_credit>e.grand_total&&(e.minus_credit=e.grand_total),e.grand_total-=e.minus_credit)}calculateTaxSubtotalRatio(e){let t=1;return!e.lines||!e.lines.some(e=>e.item.is_tax_exempt)||e.grand_total===0||e.subtotal===0||(t=1-e.lines.filter(e=>e.item.is_tax_exempt).reduce((e,t)=>e+t.subtotal,0)/e.subtotal),t}calculateRewardCredit(e,t,n,r){if(e.rewarded_credit=0,e.grand_total<=0||t>0&&t>e.grand_total)return;let i=e.rewarded_credit_rate,a=e.grand_total;n&&(a-=e.service_charge),r&&(a-=e.tax),a-=e.lines.filter(e=>e.item.is_credit_reward_exempt).reduce((e,t)=>e+t.subtotal,0),e.rewarded_credit=K(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}}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)}resetInvoiceCalculations(e){e.subtotal=0,e.point_subtotal=0,e.service_chargeable_subtotal=0,e.service_charge=0,e.tax=0,e.grand_total=0,e.rounding=0,e.discount_amount=0,e.minus_credit=0,e.rewarded_credit=0,e.rewarded_point=0,e.add_credit=0,e.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=K(e.payments.reduce((e,t)=>e+t.tender_amount,0)-e.grand_total);e.payments.filter(e=>e.payment_method.is_cash);let n=e.payments.filter(e=>e.payment_method.is_cash);n.forEach(e=>e.change_amount=0);let r=n[n.length-1];r.change_amount=K(t)}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 W.AfterSubtotal:t=e.subtotal;break;case W.AfterServiceCharge:t=e.subtotal+e.service_charge;break;case W.AfterGrantTotal:t=e.grand_total;break;default:t=e.subtotal}n.percentage>0&&(n.amount=K(t*(n.percentage/100),2)),e.grand_total+=n.amount,e.grand_total=K(e.grand_total,2)}}},jr=class extends Ar{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==A.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=C.InvoiceLine+t(),e.lines.push(d)),d}duplicateLine(e,n){let r=s.cloneDeep(n);return r.is_duplicate=!0,r.duplicated_from_uid=n.uid,r.uid=C.InvoiceLine+t(),e.lines.push(r),e}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 yt;return n.item=s.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==U.Percent&&n>100)throw new w(`Discount percent can not be more than 100%`);if(t==U.Flat&&n>e.subtotal)throw new w(`Discount amount can not be more than price`);return e.discount_calc_type=t,t==U.Flat?e.discount_amount=n:e.discount_percent=n,e}minusLineQuantity(e,t,n,r=!1){if(n<=0)throw new w(`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 w(`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=s.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}addLineQuantity(e,t,n){if(e.lines==null||e.lines.length<=0)return e;t.quantity+=n}minusModifierQuantity(e,t,n=0){if(!e||e.length<=0)return e;{n=n??0;let r=e.findIndex(e=>e.item_uid===t.item_uid&&e.price===t.price);return r<0||(e[r].quantity<=n?e.splice(r,1):e[r].quantity-=n),e}}changeModifierQuantity(e,t,n){if(!e||e.length<=0)return e;n=n??0;let r=e.findIndex(e=>e.item_uid===t.item_uid&&e.price===t.price);return r<0?e:(e[r].quantity+=n,e[r].quantity<=0&&e.splice(r,1),e)}addModifierQuantity(e,t,n=0){if(!e||e.length<=0)return e;{n=n??0;let r=e.findIndex(e=>e.item_uid===t.item_uid&&e.price===t.price);return r<0||(e[r].quantity+=n),e}}changeModifierPrice(e,t){return e&&(e.price=t,e)}overwriteNoteToLine(e,t){return t&&(e.remark=t),e}findOrCreateLine(e,t,n,r=0,i=[],a=``,o=!1,s,c){if(r=r??t.price,!e.lines||e.lines.length<=0||o)return this.createInvoiceLine(t,n,r,i,a);{let o=e.lines.filter(e=>e.item_uid===t.uid);if(!o||o.length<=0)return this.createInvoiceLine(t,n,r,i,a);if(s&&c){for(let e of o.filter(e=>e.is_combo_item))if(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(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 bt;return a.item=s.cloneDeep(e),a.item_uid=e.uid,a.quantity=t,a.point=e.minus_point,a.price=n??e.price,a.quantity=t,a.modifiers=r,a.remark=i,a}compareModifiers(e,t){if(e.length!==t.length)return!1;for(let n of e)if(!t.some(e=>e.item_uid===n.item_uid&&e.price===n.price&&e.quantity===n.quantity))return!1;return!0}compareLines(e,t){return!(e.remark!=t.remark||e.price!=t.price||e.is_take_out!=t.is_take_out||e.discount_calc_type!=t.discount_calc_type||e.discount_amount!=t.discount_amount||e.discount_percent!=t.discount_percent||!this.compareModifiers(e.modifiers,t.modifiers))}addComboItemToLine(e,t,n,r,i,a,o,s){let c=this.addItemToLine(e,t,n,r,o,s,!1,i,a);return c.is_combo_item=!0,c.combo_line_uid=i,c.combo_group_uid=a,c}removeAllComboItems(e,t,n=!1){if(!e.lines||e.lines.length==0)return[];let r=e.lines.filter(e=>e.combo_line_uid==t&&e.is_combo_item);return e.lines=s.differenceBy(e.lines,r,`uid`),n||e.deleted_lines.push(...r),r}duplicateComboLines(e,n){if(!n.is_combo)throw new w(`Line is not a combo`);let r=s.cloneDeep(n);return r.uid=C.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=s.cloneDeep(n);i.uid=C.InvoiceLine+t(),i.combo_line_uid=r.uid,i.is_duplicate=!0,e.lines.push(i)}),e}},Mr=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==T.outdatedInvoice)throw await this.saveOne(t.data),new w(t.error);if(t.error)throw new w(t.error);return t.data}async createInvoice(e,t,n){e.status=H.Open,e.ref_id||(e.ref_id=await this.getRefId()),e.call_num||(e.call_num=e.ref_id.slice(-3)),e.table_name=t.name,e.table_uid=t.uid,t.invoice_uid=e.uid,t.status=O.OPENED,this.sectionItemService.syncInvoiceData(t,e),this.addEmployeeToInvoice(e,n),e.created_at=new Date,e.created_at_timestamp=e.created_at.getTime();let r=(await this.configService.getDefaultOne()).config?.order?.datetime_format;e.humanized_created_at=I(e.created_at,r),t.invoice_created_at=new Date;let i=await this.createKitchenPrintJobs(e),a=await this.createLabelPrintJobs(e),o=await this.createOrderPrintJobs(e),s=this.sortPrintJobsByPrinterSequence([...i,...a,...o]);e.kitchen_print_job_uids||(e.kitchen_print_job_uids=[]),e.label_print_job_uids||(e.label_print_job_uids=[]);let c=e.kitchen_print_job_uids.length,l=e.label_print_job_uids.length,u=i.map(e=>e.uid),d=a.map(e=>e.uid);u.length>0&&e.kitchen_print_job_uids.push(u),d.length>0&&e.label_print_job_uids.push(d),await this.preprocessInvoice(e);let f={invoice:e,section_item:t};s.length>0&&(f.print_jobs=s);try{let e=await this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${this.methodName}`,f);if(e.error==T.outdatedInvoice)throw await this.saveOne(e.data),f.invoice=e.data,new w(e.error);if(e.error==T.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),f.section_item=e.data,new w(e.error);return f}catch(t){throw e.kitchen_print_job_uids.length=c,e.label_print_job_uids.length=l,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.createLabelPrintJobs(e),o=await this.createOrderPrintJobs(e),s=this.sortPrintJobsByPrinterSequence([...r,...i,...a,...o]);e.kitchen_print_job_uids||(e.kitchen_print_job_uids=[]),e.label_print_job_uids||(e.label_print_job_uids=[]);let c=e.kitchen_print_job_uids.length,l=e.label_print_job_uids.length,u=r.map(e=>e.uid),d=a.map(e=>e.uid);u.length>0&&e.kitchen_print_job_uids.push(u),d.length>0&&e.label_print_job_uids.push(d),await this.preprocessInvoice(e);let f={invoice:e,section_item:t};s.length>0&&(f.print_jobs=s);try{let e=await this.http.patch(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/update_invoice`,f);if(e.error==T.outdatedInvoice)throw await this.saveOne(e.data),new w(`${e.error}, system has updated the data, please try again`);if(e.error==T.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),f.section_item=e.data,new w(`${e.error}, system has updated the data, please try again`);return f}catch(t){throw e.kitchen_print_job_uids.length=c,e.label_print_job_uids.length=l,t}}async cancelInvoice(e,t,n){if(e.id_in_server==0&&e.lines.length<=0)throw new w(`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=H.Void,t.invoice_uid=``,t.status=O.CLOSED,this.sectionItemService.reset(t),this.addEmployeeToInvoice(e,n);let r=await this.createReceiptPrintJob(e,L.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==T.outdatedInvoice)throw await this.saveOne(a.data),i.invoice=a.data,new w(a.error);if(a.error==T.outdatedSectionItem)throw await this.sectionItemService.saveOne(a.data),i.section_item=a.data,new w(a.error);return i}async checkInvoice(e,t,n){t.status=O.PAYMENT,this.addEmployeeToInvoice(e,n);let r=await this.createReceiptPrintJob(e,L.CheckPrinter),i=await this.createLabelPrintJobs(e),a=await this.createKitchenPrintJobs(e),o=await this.createOrderPrintJobs(e),s=[...i,...a,...o];r&&s.push(r);let c=this.sortPrintJobsByPrinterSequence(s);e.kitchen_print_job_uids||(e.kitchen_print_job_uids=[]),e.label_print_job_uids||(e.label_print_job_uids=[]);let l=e.kitchen_print_job_uids.length,u=e.label_print_job_uids.length,d=a.map(e=>e.uid),f=i.map(e=>e.uid);d.length>0&&e.kitchen_print_job_uids.push(d),f.length>0&&e.label_print_job_uids.push(f),await this.preprocessInvoice(e);let p={invoice:e,section_item:t};c.length>0&&(p.print_jobs=c);try{let e=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/check_invoice`,p);if(e.error==T.outdatedInvoice)throw await this.saveOne(e.data),p.invoice=e.data,new w(e.error);if(e.error==T.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),p.section_item=e.data,new w(e.error);return p}catch(t){throw e.kitchen_print_job_uids.length=l,e.label_print_job_uids.length=u,t}}async switchInvoice(e,t,n,r){if(t.uid==n.uid)throw new w(`source and target table can not be the same`);if(t.status!=O.CLOSED)throw new w(`target table is occupied`);if(e.lines==null||e.lines.length<=0)throw new w(`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=O.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==T.outdatedInvoice)throw await this.saveOne(a.data),i.invoice=a.data,new w(a.error);if(a.error==T.outdatedSourceSectionItem)throw await this.sectionItemService.saveOne(a.data),i.source_section_item=a.data,new w(a.error);if(a.error==T.outdatedTargetSectionItem)throw await this.sectionItemService.saveOne(a.data),i.target_section_item=a.data,new w(a.error);return i}async payInvoice(e,t,n,r){e.status=H.Paid,t.invoice_uid=``,t.status=O.CLOSED,this.sectionItemService.reset(t),this.addEmployeeToInvoice(e,r),e.paid_at=new Date;let i=(await this.configService.getDefaultOne()).config,a=i?.order?.datetime_format;e.humanized_paid_at=I(e.paid_at,a),e.payment_has_cash=e.payments?.some(e=>e.payment_method?.is_cash===!0);let o=await this.getStockChangeList(e,!1),s=await this.createLabelPrintJobs(e),c=await this.createReceiptPrintJob(e,L.ReceiptPrinter),l=await this.createKitchenPrintJobs(e),u=await this.createCancelKitchenPrintJobs(e,e.deleted_lines),d=await this.createOrderPrintJobs(e),f=[...s,...l,...u,...d];c&&f.push(c);let p=this.sortPrintJobsByPrinterSequence(f);e.kitchen_print_job_uids||(e.kitchen_print_job_uids=[]),e.label_print_job_uids||(e.label_print_job_uids=[]);let m=e.kitchen_print_job_uids.length,ee=e.label_print_job_uids.length,h=l.map(e=>e.uid),g=s.map(e=>e.uid);h.length>0&&e.kitchen_print_job_uids.push(h),g.length>0&&e.label_print_job_uids.push(g),await this.preprocessInvoice(e);let _={invoice:e,section_item:t,till:n};p.length>0&&(_.print_jobs=p);try{let t=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/pay_invoice`,_);if(t.error==T.outdatedInvoice)throw await this.saveOne(t.data),_.invoice=t.data,new w(`${t.error}, system has updated the data and please try again`);if(t.error==T.outdatedSectionItem)throw await this.sectionItemService.saveOne(t.data),_.section_item=t.data,new w(`${t.error}, system has updated the data and please try again`);if(o.length>0&&await this.itemService.changeItemsStock(o),e.call_num&&i?.ods?.enabled){let t=new Dr;t.order_number=e.call_num,await this.orderDisplayService.addOne(t)}return _}catch(t){throw e.kitchen_print_job_uids.length=m,e.label_print_job_uids.length=ee,t}}async directPayInvoice(e,t,n,r,i,a=!1){e.status=H.Paid,n!=null&&this.addEmployeeToInvoice(e,n),e.paid_at=new Date;let o=(await this.configService.getDefaultOne()).config,s=o?.order?.datetime_format;e.humanized_paid_at=I(e.paid_at,s),e.created_at=new Date,e.created_at_timestamp=e.created_at.getTime(),e.humanized_created_at=I(e.created_at,s),e.ref_id||(e.ref_id=await this.getRefId()),e.call_num||(e.call_num=e.ref_id.slice(-3)),e.payment_has_cash=e.payments?.some(e=>e.payment_method?.is_cash===!0);let c=await this.getStockChangeList(e,!1),l=null,u=null;r&&r.type==L.KioskPrinter?(l=await this.createReceiptPrintJob(e,L.ReceiptPrinter),u=await this.createReceiptPrintJob(e,L.KioskPrinter,!1,0,r,i)):l=await this.createReceiptPrintJob(e,L.ReceiptPrinter,!1,0,r);let d=await this.createLabelPrintJobs(e),f=await this.createKitchenPrintJobs(e,a),p=await this.createOrderPrintJobs(e),m=[...d,...f,...p];l&&m.push(l),u&&m.push(u);let ee=this.sortPrintJobsByPrinterSequence(m),h=f.map(e=>e.uid),g=d.map(e=>e.uid);h.length>0&&(e.kitchen_print_job_uids=[h]),g.length>0&&(e.label_print_job_uids=[g]),await this.preprocessInvoice(e);let _={invoice:e,till:t};ee.length>0&&(_.print_jobs=ee);let v=await this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/direct_pay_invoice`,_);if(v.error==T.outdatedInvoice)throw await this.saveOne(v.data),_.invoice=v.data,new w(v.error);if(c.length>0&&await this.itemService.changeItemsStock(c),e.call_num&&o?.ods?.enabled){let t=new Dr;t.order_number=e.call_num,await this.orderDisplayService.addOne(t)}return _}async voidInvoice(e,t,n,r){n&&(e.etc.void_reason=n);let i=e.status;e.status=H.Void,e.voided_at=new Date;let a=(await this.configService.getDefaultOne()).config?.order?.datetime_format;e.humanized_voided_at=I(e.voided_at,a),t&&(t.deleted_at=new Date),this.addEmployeeToInvoice(e,r);let o=(await this.configService.getDefaultOne()).config,s=await this.createReceiptPrintJob(e,L.ReceiptPrinter,!0),c=[];o.kitchen.print_cancel_whole_invoice&&(c=await this.createCancelKitchenPrintJobs(e,e.lines)||[]);let l=[...c];s&&l.push(s);let u={invoice:e,till:t};if(l.length>0&&(u.print_jobs=l),e.table_uid){let t=await this.sectionItemService.getOne(e.table_uid);t.status!=O.CLOSED&&(t.invoice_uid=``,t.status=O.CLOSED,u.section_item=t)}let d=[];i==H.Paid&&(d=await this.getStockChangeList(e));let f=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/void_invoice`,u);if(f.error==T.outdatedInvoice)throw await this.saveOne(f.data),u.invoice=f.data,new w(f.error);return d.length>0&&await this.itemService.changeItemsStock(d),u}async duplicateInvoice(e,n){if(e.status!=H.Paid)throw new w(`invalid invoice status`);let r=s.cloneDeep(e);if(r.etc.is_duplicate=!0,r.etc.duplicated_from_uid=r.uid,r.uid=C.Invoice+t(),r.status=H.Open,r.ref_id=await this.getRefId(),this.addEmployeeToInvoice(r,n),r.lines)for(let e of r.lines)e.uid=C.InvoiceLine+t();if(r.payments)for(let e of r.payments)e.uid=C.Payment+t();return r}async reprintReceipt(e,n=!1){if(!e?.receipt_print_job_uid)throw new w(`The invoice does not have a receipt`);let r=await this.printJobService.getOne(e.receipt_print_job_uid);if(!r){let t=new p().addParam(`uid`,`EqualTo`,e.receipt_print_job_uid),n=await this.printJobService.autoquery(t);if(!n.results||n.results.length<=0)throw new w(`The invoice does not have a receipt`);r=n.results[0]}let i=await this.printerService.getOne(r.printer_uid);if(i||(i=await this.printerService.getDefaultReceiptPrinter()),!i)throw new w(`Receipt printer not found`);return r=this.printJobService.replacePrinter(r,i),r.uid=C.PrintJob+t(),r.save_only=n,r.status=Ze.Queued,r.print_times=1,r.printed=0,r.retries=0,await this.printJobService.addOne(r),r}async printLastKitchenSlips(e){let n=await this.getOne(e);if(!n)throw new w(`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 w(`No kitchen or label print found`);let o=new p().addParam(`uid`,`In`,a),s=await this.printJobService.autoquery(o);if(!s.results||s.results.length===0)throw new w(`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=C.PrintJob+t(),r.save_only=!1,r.status=Ze.Queued,r.print_times=1,r.printed=0,r.retries=0,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=W.AfterSubtotal,i=`custom`,a={}){if(e.discounts||(e.discounts=[]),t==U.Percent&&n>100)throw new w(`Discount percent can not be more than 100%`);let o=new vt;return o.calc_type=t,o.calc_flow=r,o.name=i,o.name_translation=a,t==U.Flat?o.amount=n:o.percent=n,e.discounts.push(o),e}addCouponToInvoice(e,t,n=W.AfterSubtotal){e.discounts||(e.discounts=[]);let r=new vt;if(r.calc_type=t.coupon.discount_calc_type==1?U.Flat:U.Percent,r.calc_flow=n,r.name=t.coupon.name,r.calc_type==U.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||s.intersection(r.applying_item_uids,e.lines.map(e=>e.item_uid)).length===0))throw new w(`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 w(`Customer object can not be null`);return e.customer_id=t.id,e.customer=s.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 w(`Source invoice has no nothing to merge`);if(t.lines.some(e=>e.quantity!=e.sent))throw new w(`Please send first before merging`);if(!await this.getOne(e.uid))throw new w(`Target invoice not found`);if(!await this.getOne(t.uid))throw new w(`Source invoice not found`);if(e?.id_in_server==0)throw new w(`Target invoice is not synced to server`);if(t?.id_in_server==0)throw new w(`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!=H.Paid)throw new w(`invalid invoice status`);if(!t||t.length<1)throw new w(`invalid options`);for(let n of t){let t=e.payments.find(e=>e.uid==n.source_payment.uid);if(!t)throw new w(`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=s.cloneDeep(n.target_payment_method),t.payment_method_history=s.cloneDeep(n.target_payment_method),t.payment_method_history.changed_at=new Date}return 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==L.ReceiptPrinter||t==L.CheckPrinter){let n=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,r=t==L.ReceiptPrinter?n?.receipt_printer_uid:n?.check_printer_uid;r&&(o=await this.printerService.getOne(r)),o||(o=t==L.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 w(`Print template not found`);t==L.ReceiptPrinter&&!s.config?.receipt?.enabled&&(n=!0);let l=await this.printTemplateService.renderPrintTemplate(e,s.config,c,{...new B,printer_name:o.name}),u=new z(o,l,n,r);return t!=L.ReceiptPrinter&&(u.printer_type=t),o.connection_type!=Ye.ETHERNET&&(u.connection_type=o.connection_type),t==L.ReceiptPrinter&&(e.receipt_print_job_uid=u.uid),a&&(u.device_uid_to_print=a),u}sortLinesByItemSequence(e){return s.chain(e||[]).groupBy(e=>e.is_combo_item?e.combo_line_uid:e.uid).map(e=>s.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()}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,L.KitchenPrinter),o=await this.printerService.getPrintersByUids(a);for(let t of o){let a=await this.printTemplateService.getOneByParams({uid:t.print_template_uid});if(!a)continue;let o=i.filter(e=>e.item.kitchen_printers_uids.includes(t.uid)),c=this.sortLinesByItemSequence(o),l=s.cloneDeep(e);if(t.kitchen_itemized_print)for(let e of c){l.lines=[e];let i=new z(t,await this.printTemplateService.renderPrintTemplate(l,n,a,{...new B,printer_name:t.name}),!1,t.print_times);r.push(i)}else{l.lines=c;let e=new z(t,await this.printTemplateService.renderPrintTemplate(l,n,a,{...new B,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,L.OrderPrinter),a=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,o=await this.printerService.getPrintersByUids(i);for(let i of o){if(a?.order_printer_uids?.length>0&&!a.order_printer_uids.includes(i.uid))continue;let o=await this.printTemplateService.getOneByParams({uid:i.print_template_uid});if(!o)continue;let c=r.filter(e=>e.item.order_printers_uids.includes(i.uid)),l=this.sortLinesByItemSequence(c),u=s.cloneDeep(e);u.lines=l;let d=new z(i,await this.printTemplateService.renderPrintTemplate(u,t,o,{...new B,printer_name:i.name}),!1,i.print_times);n.push(d)}return n}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,L.LabelPrinter);if(i.length==0||r.length==0)return[];let a=await this.printerService.getPrintersByUids(i),o=s.cloneDeep(e),c=r.length,l=1;for(let e of r){if(e.meta.total_index=c,e.meta.index=l,e.modifiers?.length&&e.item.modifiers?.length){let t=new Map(e.item.modifiers.map(e=>[e.uid,e.sequence??0]));e.modifiers.sort((e,n)=>(t.get(e.item_uid)??0)-(t.get(n.item_uid)??0))}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=f.compile(r.commands);o.lines=[i];let s=a({invoice:o,config:t}),c=new z(e,new F,!1,e.print_times);c.commands=s,n.push(c)}return n}filterLinesAndPrintersToPrint(e,t){let n;switch(t){case L.KitchenPrinter:n=`kitchen_printers_uids`;break;case L.OrderPrinter:n=`order_printers_uids`;break;case L.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=s.cloneDeep(a);if(e.quantity-=e.sent,t==L.LabelPrinter)for(let t=0;t<e.quantity;t++){let t=s.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=s.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)return[];let{lines:r,printerUids:i}=this.filterDeletedLinesForCancelPrint(t);if(r.length===0)return[];let a=await this.printerService.getPrintersByUids(i),o=[];for(let t of a){let i=await this.printTemplateService.getOneByParams({uid:t.print_template_uid});if(!i)continue;let a=r.filter(e=>e.item.kitchen_printers_uids.includes(t.uid)),c=this.sortLinesByItemSequence(a),l=s.cloneDeep(e);if(t.kitchen_itemized_print)for(let e of c){l.lines=[e];let r=new z(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);o.push(r)}else{l.lines=c;let e=new z(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);o.push(e)}}for(let t of e.deleted_lines)t.is_cancel_printed=!0;return o}sortPrintJobsByPrinterSequence(e){return e.sort((e,t)=>(e?.print_sequence??999)-(t?.print_sequence??999))}async preprocessInvoice(e){if(e.lines)for(let t of e.lines)t.sent=t.quantity;return e}addInvoiceCharge(e,t,n,r,i=W.AfterSubtotal){e.charges||(e.charges=[]);let a=new ht;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 getStockChangeList(e,t=!0){if(!e.lines||e.lines.length===0)return[];let n=t?1:-1,r=new Map;for(let t of e.lines){let e=r.get(t.item_uid)||new be(t.item_uid);if(e.quantity+=t.quantity*n,t.modifiers&&t.modifiers.length>0)for(let r of t.modifiers){let i=e.modifiers.find(e=>e.item_uid===r.item_uid);i||(i={item_uid:r.item_uid,quantity:0},e.modifiers.push(i)),i.quantity+=t.quantity*r.quantity*n}r.set(t.item_uid,e)}return Array.from(r.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=s.cloneDeep(e),i=s.cloneDeep(n);i.quantity=1,r.lines=[i],t.push(r)}return t}},Nr=class extends Mr{},Pr=class extends G{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}},Fr=class extends G{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 m.compare(t,n.password))return!0;throw new w(`Password is incorrect`)}else throw new w(`User not found`)}catch(e){throw e instanceof w?e:new w(`Unexpected error, login failed`)}}async createEmployee(e){try{if(await this.getOne(e.uid))throw new w(`User already exists`);return e.password&&(e.password=await m.hash(e.password,12)),this.addOne(e)}catch(e){throw e instanceof w?e:new w(`Unexpected error, creating employee failed`)}}async changePassword(e){try{return await m.hash(e,12)}catch{throw new w(`Unexpected error, changing password failed`)}}},Ir=class extends G{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),async()=>await this.db.table(this.moduleName).where(`name`).anyOfIgnoreCase(e).or(`codename`).anyOfIgnoreCase(e).or(`barcode`).anyOfIgnoreCase(e).toArray())}async addModifierCategory(e,n){return n.uid=C.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 w(`Item does not have any modifier categories`);let n=e.modifier_categories.findIndex(e=>e.uid===t.uid);if(n===-1)throw new w(`Modifier category not found`);return e.modifier_categories[n]=t,e}async removeModifierCategory(e,t){if(!e.modifier_categories)throw e.modifier_categories=[],new w(`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=C.ItemModifier+t(),e.modifiers.push(n),e}async updateModifier(e,t){if(!e.modifiers)throw e.modifiers=[],new w(`Item does not have any modifiers`);let n=e.modifiers.findIndex(e=>e.uid===t.uid);if(n===-1)throw new w(`Modifier not found`);return e.modifiers[n]=t,e}async removeModifier(e,t){if(!e.modifiers)throw e.modifiers=[],new w(`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 w(`Item does not have any modifier categories`);if(!e.modifier_categories.find(e=>e.uid===n))throw new w(`Modifier category not found`);let r=e.modifiers.find(e=>e.uid===t);if(!r)throw new w(`Modifier not found`);return r.category_uid=n,e}async addImageAsync(e,t){let n=o(),r=this.getFileExtension(e);await this.http.post(`api/v5/merchants/`+this.options.merchant_uid+`/upload-image`,new tn({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 w(`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 w(`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 w(`Item not found`);let r=Number(n.stock);return n.stock=(isNaN(r)?0:r)+t,this.updateOne(n.id_in_server,n)}async changeItemsStock(e){let t=[];for(let n of e){let e=await this.getOne(n.item_uid);if(!e)continue;let r=Number(e.stock);e.stock=(isNaN(r)?0:r)+n.quantity;for(let t of n.modifiers){let n=e.modifiers?.find(e=>e.uid===t.item_uid);if(!n)continue;let r=Number(n.stock);n.stock=(isNaN(r)?0:r)+Number(t.quantity)}t.push(e)}await this.updateMany(t)}convertFileToBase64(e){return new Promise((t,n)=>{let r=new FileReader;r.onloadend=()=>{typeof r.result==`string`?t(r.result.split(`,`)[1]):n(Error(`Could not convert file to Base64.`))},r.onerror=()=>n(Error(`File reading failed.`)),r.readAsDataURL(e)})}getFileExtension(e){let t=e.name,n=t.lastIndexOf(`.`);return n===-1||n===t.length-1?``:t.slice(n+1)}async cloneItem(e){let n=s.cloneDeep(e);if(n.uid=C.Item+t(),n.id_in_server=0,!n.modifier_categories||n.modifier_categories.length===0)return n;let r=[],i=[];for(let e of n.modifier_categories){let t=n.modifiers?.filter(t=>t.category_uid===e.uid);if(!t||t.length===0)continue;let{modifierCategory:a,modifiers:o}=await this.cloneModifiers(e,t);r.push(a),i.push(...o)}return n.modifier_categories=r,n.modifiers=i,n}async cloneModifiers(e,n){let r=s.cloneDeep(e);r.uid=C.ItemModifierCategory+t();let i=[];for(let e of n){let n=s.cloneDeep(e);n.uid=C.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 w(`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.type!==A.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}},Lr=class extends G{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 w(`Category does not have any subcategories`);let n=e.subcategories.findIndex(e=>e.uid===t.uid);if(n===-1)throw new w(`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 w(`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}},Rr=class extends G{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 It,product:()=>new Ft,till:()=>new Lt,report:()=>new Rt,receipt:()=>new zt,kitchen:()=>new Bt,kds:()=>new Vt,label:()=>new Ht,order:()=>new Ut,payment:()=>new Gt,user:()=>new Kt,tax:()=>new qt,rounding:()=>new Xt,charges:()=>new Jt,currency:()=>new Yt,inventory:()=>new Zt,pax_config:()=>new Qt,gto:()=>new $t,cash_drawer:()=>new en,marketing:()=>new At})}async updateConfig(e,t){let n=await this.getDefaultOne();n||(n=new Ct);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 Ct);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=o(),n=Tn(e);return await this.http.post(`api/v5/merchants/`+this.options.merchant_uid+`/upload-image`,new tn({base64:await En(e),name:t,extension:n})),{file_url:`${this.options.base_url}images/${t}.${n}`,thumbnail_url:`${this.options.base_url}images/${t}.thumbnail.${n}`}}},zr=class extends G{constructor(e,t,n,r=`sections`,i=`section`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Br=class extends G{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||``}}},Vr=class extends G{constructor(e,t,n,r=`products`,i=`product`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Hr=class extends G{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 Ur(e,t,n)}async cashIn(e,t){let n=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status===E.Open).first();if(!n)throw new w(`No opening shift found`);let r=new ge;return r.amount=e,r.type=D.CashIn,r.user_uid=n.user_uid,r.shift_uid=n.uid,r.note=t,this.tillService.addOne(r)}async cashOut(e,t){let n=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status===E.Open).first();if(!n)throw new w(`No opening shift found`);let r=new ge;return r.amount=e,r.type=D.CashOut,r.user_uid=n.user_uid,r.shift_uid=n.uid,r.note=t,this.tillService.addOne(r)}async closeShift(e,t){let n=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status==E.Open).first();if(!n)throw new w(`No opening shift found`);return n.declared_amount=e,n.ended_at=new Date,n.user_uid=t,n.status=E.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==E.Open).first();if(r)throw new w(`shift is already opened shift at ${r.started_at}`);let i=new he;if(i.started_at=new Date,i.user_uid=t,i.status=E.Open,await this.addOne(i),e>0){let r=new ge;r.amount=e,r.type=D.OpenDeposit,r.user_uid=t,r.amount=e,r.shift_uid=i.uid,r.note=n,await this.tillService.addOne(r)}return console.log(`open shift end`),i}},Ur=class extends G{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 ge;return a.shift_uid=t,a.user_uid=n,a.note=r,a.invoice_uid=i,a.amount=K(e.filter(e=>e.payment_method.is_cash).map(e=>e.tender_amount-e.change_amount).reduce((e,t)=>e+t,0)),a.type=D.CashInvoice,a}},Wr=class extends G{constructor(e,t,n,r=`payment_methods`,i=`payment_method`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async syncStandardPaymentMethods(){try{let{data:e}=await this.http.get(`api/v5/merchants/`+this.options.merchant_uid+`/standard_payment_methods`),t=[];for(let n of e){let e=new it(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}},Gr=class extends G{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 tt;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=K(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=s.cloneDeep(n),e.payments.push(r),e}async removePayment(e,t){return e.payments=e.payments.filter(e=>e.uid!==t),e}},Kr=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 w(`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 w(`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}},qr=class extends G{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 Nr(e,t,n,`invoices`,`invoice`),this.tillService=new Ur(e,t,n,`tills`,`till`),this.paymentService=new Gr(e,t,n,`payments`,`payment`),this.printerService=new wn(e,t,n,`printers`,`printer`),this.printTemplateService=new Yr(e,t,n,`print_templates`,`print_template`),this.printJobService=new X(e,t,n,`print_jobs`,`print_job`),this.configService=new Rr(e,t,n,`configs`,`config`)}async syncStandardReports(){let e=await this.getDefaultOne();e||(e=new hn);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 w(`No default receipt printer found`);let n=await this.printTemplateService.getOneByParams({report_code_name:e.report_code_name});if(!n)throw new w(`No print template found`);let r=await this.configService.getDefaultOne(),i=await this.getReportData(e,r.config?.order?.datetime_format),a=new z(t,await this.printTemplateService.renderReportPrintTemplate(i,r.config,n),!1,e.copies);await this.printJobService.addOne(a)}async getReportData(e,t){let n=new gn;if(e.shift_uid){await this.db.table(`shifts`).where(`uid`).equals(e.shift_uid).and(e=>e.deleted_at==null||e.deleted_at==null).first(),n.drawer_summary.declared_amount=e.declared_amount;let t=await this.db.table(`tills`).where(`shift_uid`).equals(e.shift_uid).and(e=>e.deleted_at==null).toArray();n.drawer_summary.open_amount=K(t.filter(e=>e.type==D.OpenDeposit).reduce((e,t)=>e+t.amount,0)),n.drawer_summary.pay_in_total=K(t.filter(e=>e.type==D.CashIn).reduce((e,t)=>e+t.amount,0)),n.drawer_summary.cash_invoice_total=K(t.filter(e=>e.type==D.CashInvoice).reduce((e,t)=>e+t.amount,0)),n.drawer_summary.cash_invoice_count=t.filter(e=>e.type==D.CashInvoice).length,n.drawer_summary.pay_in_count=t.filter(e=>e.type==D.CashIn).length,n.drawer_summary.pay_out_total=K(t.filter(e=>e.type==D.CashOut).reduce((e,t)=>e+t.amount,0)),n.drawer_summary.pay_out_count=t.filter(e=>e.type==D.CashOut).length,n.drawer_summary.drawer_amount=K(n.drawer_summary.open_amount+n.drawer_summary.pay_in_total+n.drawer_summary.cash_invoice_total-n.drawer_summary.pay_out_total),n.drawer_summary.difference=K(n.drawer_summary.drawer_amount-n.drawer_summary.declared_amount)}n.start_datetime=new Date(e.start_datetime).toISOString(),n.end_datetime=new Date(e.end_datetime).toISOString(),n.humanized_start_datetime=I(new Date(e.start_datetime),t),n.humanized_end_datetime=I(new Date(e.end_datetime),t),n.humanized_printed_datetime=I(new Date,t);let r=new p().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),i=(await this.invoiceService.autoQuery(r,{timeout:6e5})).results||[];return this.processReportInvoicesData(n,i)}async processReportInvoicesData(e,t=[]){let n=new Map,r=new Map,i=await this.db.table(`categories`).toArray(),a=new Map(i.map(e=>[e.uid,e]));t.forEach(t=>{t.status==H.Paid&&(e.sales_summary.paid_invoice_total+=t.grand_total,e.sales_summary.sales_total+=t.grand_total,e.sales_summary.paid_invoice_count++,e.sales_summary.rounding_total+=t.rounding,e.sales_summary.tax_total+=t.tax,e.sales_summary.service_charge_total+=t.service_charge,e.sales_summary.discount_total+=t.discount_amount,t.add_credit>0&&(e.loyalty_program_summary.add_credit_total+=t.add_credit,e.loyalty_program_summary.add_credit_count++,e.loyalty_program_summary.topup_paid_count++),t.rewarded_credit>0&&(e.loyalty_program_summary.rewarded_credit_total+=t.rewarded_credit,e.loyalty_program_summary.rewarded_credit_count++),t.minus_credit>0&&(e.loyalty_program_summary.minus_credit_total+=t.minus_credit,e.loyalty_program_summary.minus_credit_count++),t.rewarded_point>0&&(e.loyalty_program_summary.rewarded_point_total+=t.rewarded_point,e.loyalty_program_summary.rewarded_point_count++),t.minus_point>0&&(e.loyalty_program_summary.minus_point_total+=t.minus_point,e.loyalty_program_summary.minus_point_count++),e.sales_summary.total_pax+=t.pax,t.pax>0&&(e.sales_summary.pax_sales_total+=t.grand_total),t.lines.forEach(t=>{t.item.add_credit>0&&(e.loyalty_program_summary.topup_paid_total+=t.subtotal);let i=this.generateItemKey(t),a=n.get(i);a?(a.quantity+=t.quantity,a.total_amount=K(a.total_amount+t.subtotal),t.modifiers&&t.modifiers.length>0&&t.modifiers.forEach(e=>{let t=e.item.name.trim(),n=r.get(t);n?(n.quantity+=e.quantity,n.total_amount=K(n.total_amount+e.price*e.quantity)):(n=new Sn,n.item=e.item,n.quantity=e.quantity,n.total_amount=K(e.price*e.quantity),r.set(t,n))})):(a=new xn,a.item=t.item,a.quantity=t.quantity,a.total_amount=K(t.subtotal),a.modifiers=[],t.modifiers&&t.modifiers.length>0&&t.modifiers.forEach(e=>{let t={item:e.item,quantity:e.quantity,total_amount:K(e.price*e.quantity)};a.modifiers.push(t);let n=e.item.name.trim(),i=r.get(n);i?(i.quantity+=e.quantity,i.total_amount=K(i.total_amount+e.price*e.quantity)):(i=new Sn,i.item=e.item,i.quantity=e.quantity,i.total_amount=K(e.price*e.quantity),r.set(n,i))}),n.set(i,a))}),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=K(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:K(t.tender_amount-t.change_amount)})})),t.is_sales_exclusive&&(e.sales_summary.foc_sales_total+=t.grand_total,e.sales_summary.foc_sales_count++),t.status==H.Void&&(e.sales_summary.void_invoice_total+=t.grand_total,e.sales_summary.void_invoice_count++)});let o=Array.from(n.values());o.sort((e,t)=>{let n=a.get(e.item.category_uid),r=a.get(t.item.category_uid),i=n?.sequence??999999,o=r?.sequence??999999;return i===o?(e.item.sequence??999999)-(t.item.sequence??999999):i-o}),e.item_sales_summary=o;let s=0,c=0,l=new Map;o.forEach(e=>{if(s+=e.total_amount,c+=e.quantity,!e.item.category_uid)return;let t=e.item.category_uid,n=l.get(t);n||(n=new Cn,n.category=a.get(e.item.category_uid)||null,l.set(t,n)),n.items.push(e),n.total_quantity+=e.quantity,n.total_amount+=e.total_amount}),e.item_sales_summary_total=K(s),e.item_sales_summary_total_count=c;let u=Array.from(l.values());u.sort((e,t)=>(e.category?.sequence??999999)-(t.category?.sequence??999999)),u.forEach(e=>{e.total_amount=K(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=u;let d=Array.from(r.values());d.sort((e,t)=>t.quantity===e.quantity?t.total_amount-e.total_amount:t.quantity-e.quantity),e.modifier_sales_summary=d;let f=0,p=0;return e.modifier_sales_summary.forEach(e=>{f+=e.total_amount,p+=e.quantity}),e.modifier_sales_summary_total=K(f),e.modifier_sales_summary_total_count=p,e.sales_summary.paid_invoice_total=K(e.sales_summary.paid_invoice_total),e.sales_summary.sales_total=K(e.sales_summary.sales_total),e.sales_summary.rounding_total=K(e.sales_summary.rounding_total),e.sales_summary.tax_total=K(e.sales_summary.tax_total),e.sales_summary.service_charge_total=K(e.sales_summary.service_charge_total),e.sales_summary.discount_total=K(e.sales_summary.discount_total),e.sales_summary.foc_sales_total=K(e.sales_summary.foc_sales_total),e.sales_summary.void_invoice_total=K(e.sales_summary.void_invoice_total),e.sales_summary.pax_sales_total=K(e.sales_summary.pax_sales_total),e.loyalty_program_summary.add_credit_total=K(e.loyalty_program_summary.add_credit_total),e.loyalty_program_summary.topup_paid_total=K(e.loyalty_program_summary.topup_paid_total),e.loyalty_program_summary.rewarded_credit_total=K(e.loyalty_program_summary.rewarded_credit_total),e.loyalty_program_summary.minus_credit_total=K(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}},X=class extends G{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,e}},Jr=class extends G{constructor(e,t,n,r=`menus`,i=`menu`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Yr=class extends G{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=c.create({baseURL:`https://revopos-cdn.sgp1.digitaloceanspaces.com`,timeout:3e3})}async initialize(){if(!await this.getOneByParams({printer_type:L.ReceiptPrinter})){let e=new R;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=L.ReceiptPrinter,await this.addOne(e),console.log(`Default Receipt Template added`)}if(!await this.getOneByParams({printer_type:L.CheckPrinter})){let e=new R;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=L.CheckPrinter,await this.addOne(e),console.log(`Default Check Template added`)}if(!await this.getOneByParams({printer_type:L.OrderPrinter})){let e=new R;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=L.OrderPrinter,await this.addOne(e),console.log(`Default Order Template added`)}if(!await this.getOneByParams({printer_type:L.KitchenPrinter})){let e=new R;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=L.KitchenPrinter,await this.addOne(e),console.log(`Default Kitchen Template added`)}if(!await this.getOneByParams({printer_type:L.KioskPrinter})){let e=new R;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=L.KioskPrinter,await this.addOne(e),console.log(`Default Kiosk Template added`)}if(!await this.getOneByParams({printer_type:L.LabelPrinter})){let e=new R;e.commands=await this.getPrintTemplate(`tspl_cmds`),e.name=`Default Label Template`,e.printer_type=L.LabelPrinter,await this.addOne(e)}if(!await this.getOneByParams({printer_type:L.QrCodePrinter})){let e=new R;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=L.QrCodePrinter,await this.addOne(e)}if(!await this.getOneByParams({report_code_name:`sales_summary_report`})){let e=new R;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 R;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 R;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 R;e.name=`Modifier Sales Report`,e.body=await this.getPrintTemplate(`msrbt`),e.header=await this.getPrintTemplate(`msrht`),e.footer=await this.getPrintTemplate(`msrft`),e.report_code_name=`modifier_sales_report`,await this.addOne(e),console.log(`Modifier Sales Report Template added`)}}async renderPrintTemplate(e,t,n,r=new B){let i=new F;n.printer_type==L.KitchenPrinter||n.printer_type==L.OrderPrinter?i.codepage=n.codepage||this.getCodepageByCountryCode(t.kitchen.language):i.codepage=n.codepage||this.getCodepageByCountryCode(t.receipt.language);let a=new et;return a.invoice=e,a.config=t,a.normalized_printed_at=I(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 B){let i=new F,a=new et;return a.report_data=e,a.config=t,a.normalized_printed_at=I(a.printed_at,t?.order?.datetime_format),i.codepage=n.codepage||N.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 B){let r=new F;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 l.AES.decrypt(t.data,this.secretKey).toString(l.enc.Utf8)}getCodepageByCountryCode(e){let t={US:N.English,GR:N.Greek,DE:N.WesternEurope,LT:N.BalticRim,PL:N.CentralEurope,RU:N.Cyrillic,TR:N.Turkish,EU:N.MultilingualLatin1WithEuro,PT:N.Portuguese,IS:N.Icelandic,IL:N.Hebrew,CA:N.FrenchCanadian,EG:N.Arabic,NO:N.Nordic,BY:N.Russian,MK:N.ModernGreek,CN:N.SimplifiedChinese,KR:N.Korean,TW:N.TraditionalChinese,FR:N.WesternEuropeanLatin,AE:N.ArabicISO,JP:N.Japanese,CZ:N.CentralEuropeanLatinWindows,BG:N.CyrillicWindows,ES:N.WesternEuropeanLatinWindows,CY:N.GreekWindows,AZ:N.TurkishWindows,PS:N.HebrewWindows,SA:N.ArabicWindows,LV:N.BalticWindows,VN:N.Vietnamese};return e&&t[e.toUpperCase()]||t.CN}async renderPrintCommand(e,t){try{let n=new u,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=s.flatMap(i,e=>e),i=s.compact(i),i}catch(e){throw console.error(e),e}}},Xr=class extends G{constructor(e,t,n,r=`storages`,i=`storage`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Zr=class extends G{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}};function Qr(e,t,n){let r=c.create({baseURL:e,timeout:2e4,headers:{"x-device-uid":t,Authorization:`Bearer ${n}`}});return r.interceptors.response.use(function(e){return e.data},function(e){return Promise.reject(e)}),r}const $r=new Map([[`Item`,Ir],[`Section`,zr],[`SectionItem`,Br],[`Category`,Lr],[`Config`,Rr],[`Shift`,Hr],[`Till`,Ur],[`Employee`,Fr],[`PaymentMethod`,Wr],[`Invoice`,Nr],[`Report`,qr],[`Printer`,wn],[`PrintJob`,X],[`PrintTemplate`,Yr],[`EmployeeRole`,Pr],[`OrderDisplay`,Or],[`Storage`,Xr],[`Menu`,Jr],[`StockLog`,Zr]]),Z=`uid, updated_at, created_at, deleted_at, _timestamp, id_in_server, created_at_timestamp`,Q=`${Z}, sequence`,ei=`${Q}, status`,ti=`${Z}, till_type, shift_uid, invoice_uid`,ni=`${Q}, payment_method_code, is_disabled`,ri=`${Z}, type, status, table_uid`,ii=`${Q}, name, barcode, codename`,ai=`${Z}, status, printer_type, connection_type, protocol, save_only, device_uid_to_print`,oi=`${Z}, name, printer_type`,si=`${Z}, order_number, status`,ci=`${Z}, model`,li={items:ii,sections:Q,section_items:Q,categories:Q,shifts:ei,tills:ti,employees:`${Z}, role_uid`,payment_methods:ni,invoices:ri,configs:Z,reports:Z,printers:Z,print_jobs:ai,print_templates:oi,employee_roles:`${Z}, name, is_default`,order_displays:si,storages:ci,menus:Z,stock_logs:`${Z}, entity_type, entity_uid, type`};var $=function(e){return e.DISCONNECTED=`disconnected`,e.CONNECTED=`connected`,e.ERROR=`error`,e}($||{}),ui=class e{constructor(e,t,n=!1){this.options=e,this.win=t,v(this,`mode`,void 0),v(this,`http`,void 0),v(this,`dataSource`,void 0),v(this,`status`,$.DISCONNECTED),this.mode=e.mode,this.http=Qr(e.base_url,e.device_uid,e.token),n||this.initializeDatabase(),M.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 i(this.options.database.name),this.dataSource.version(29).stores(li),this.status=$.CONNECTED}catch(e){this.status=$.ERROR,console.error(`Database connection error:`,e)}return this.dataSource}async dropDatabase(){await i.delete(this.options.database.name),await this.initializeDatabase()}clearTableData(e){return this.dataSource.table(e).clear()}async getService(e){if(this.status==$.ERROR)throw Error(`Database connection error`);for(;this.status==$.DISCONNECTED;)await new Promise(e=>setTimeout(e,100));try{return new e(this.http,this.dataSource,this.options)}catch(e){throw Error(`Service instantiation error: `+e?.message)}}async getServiceByName(e){if(this.status==$.ERROR)throw Error(`Database connection error`);for(;this.status==$.DISCONNECTED;)await new Promise(e=>setTimeout(e,100));try{let t=$r.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)}}};function di(e,t,n=`export.csv`){let r=mi(pi(e,t));return new Blob([``+r],{type:`text/csv;charset=utf-8;`})}function fi(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 pi(e,t){let n=[];for(let r of e){n.push({type:`category`,name:r.name,sku:``,price:void 0,stock:void 0,is_internal:r.is_internal,min_order:void 0,max_order:void 0,image_url:r.image_url||``,image_thumbnail_url:r.image_thumbnail_url||``,sequence:r.sequence});let e=t.filter(e=>e.category_uid===r.uid);for(let t of e){let e=t.type===A.Combo;if(n.push({type:e?`combo`:`product`,name:t.name,sku:t.sku||``,price:t.price,stock:fi(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}),e&&t.combo_groups&&t.combo_groups.length>0){for(let e of t.combo_groups)if(n.push({type:`combo_group`,name:e.name,sku:``,price:void 0,stock:void 0,is_internal:void 0,min_order:e.min_order,max_order:e.max_order,image_url:``,image_thumbnail_url:``,sequence:e.sequence}),e.combo_items&&e.combo_items.length>0)for(let t of e.combo_items)n.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(!e&&t.modifier_categories&&t.modifier_categories.length>0){for(let e of t.modifier_categories)if(n.push({type:`modifier_category`,name:e.name,sku:``,price:void 0,stock:void 0,is_internal:void 0,min_order:e.min_order,max_order:e.max_order,image_url:``,image_thumbnail_url:``,sequence:e.sequence}),t.modifiers&&t.modifiers.length>0){let r=t.modifiers.filter(t=>t.category_uid===e.uid);for(let e of r)n.push({type:`modifier`,name:e.name,sku:e.sku||``,price:e.price,stock:fi(e.stock),is_internal:e.is_internal,min_order:void 0,max_order:void 0,image_url:e.image_url||``,image_thumbnail_url:e.image_thumbnail_url||``,sequence:e.sequence})}}}}return n}function mi(e){let t=[[`Type`,`Name`,`SKU`,`Price`,`Stock`,`Is Internal`,`Min Order`,`Max Order`,`Image URL`,`Thumbnail URL`,`Sequence`,`Item UID`].join(`,`)];for(let n of e){let e=[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||``];t.push(e.join(`,`))}return t.join(`
|
|
1
|
+
import e from"dayjs";import{nanoid as t}from"nanoid";import n from"esc-pos-encoder-ionic";import r from"wcwidth";import{Dexie as i,liveQuery as a}from"dexie";import{v4 as o}from"uuid";import*as s from"lodash";import c from"axios";import l from"crypto-js";import{SelectTransform as u}from"selecttransform";import{NetworkInterface as d}from"@awesome-cordova-plugins/network-interface";import f from"handlebars";import{QueryBuilder as p}from"@litepos/autoquery";import m from"bcryptjs";var ee=(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 te=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`,``)}},y=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`,``)}},ne=class extends y{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`,``)}},re=function(e){return e[e.All=1]=`All`,e[e.Inclusive=2]=`Inclusive`,e[e.Exclusive=3]=`Exclusive`,e}(re||{}),ie=function(e){return e[e.Flat=1]=`Flat`,e[e.Percent=2]=`Percent`,e}(ie||{}),ae=class{constructor(){v(this,`applying_type`,re.Inclusive),v(this,`applying_items`,[])}},oe=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`,ie.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)}},se=class{constructor(e){v(this,`invoice_uid`,``),e&&(this.invoice_uid=e.invoice_uid)}},ce=class{constructor(e){v(this,`guid`,``),v(this,`coupon`,new oe),v(this,`is_multi_stores`,!1),v(this,`usage`,new se),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 oe(e.coupon),this.is_multi_stores=e.is_multi_stores,this.usage=new se(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 le={from(t){return e(t).format(`YYYY-MM-DD HH:mm:ss`)},to(e){return e}};var b=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)}},x=class extends b{constructor(){super(),v(this,`name`,void 0),v(this,`name_translations`,{})}},ue=class extends x{constructor(...e){super(...e),v(this,`description`,void 0),v(this,`description_translations`,{})}};let S=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}({}),de=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}({}),fe=function(e){return e.LOCAL=`local`,e.CLOUD=`cloud`,e}({});var pe=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 me=function(e){return e.Data=`DataMessage`,e.Event=`EventMessage`,e}({});var he=class{constructor(){v(this,`model`,``),v(this,`data`,``),v(this,`has_many`,!1),v(this,`type`,me.Data)}},C=class extends Error{constructor(e){super(e),this.name=`system_error`}};let w=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}({}),T=function(e){return e.Open=`opened`,e.Closed=`closed`,e}({});var ge=class extends b{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`,T.Open),v(this,`uid`,S.Shift+t())}};let E=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 _e=class extends b{constructor(){super(),v(this,`user_uid`,``),v(this,`shift_uid`,``),v(this,`invoice_uid`,``),v(this,`type`,E.CashDeposit),v(this,`amount`,0),v(this,`note`,``),v(this,`uid`,S.Till+t())}};let D=function(e){return e.CLOSED=`closed`,e.OPENED=`opened`,e.PAYMENT=`payment`,e}({});var ve=class extends x{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`,S.SectionItem+t()),v(this,`invoice_uid`,``),v(this,`section_uid`,``),v(this,`status`,D.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,`soup_base_quota`,0),v(this,`soup_base_type`,0),v(this,`is_delete`,!1),v(this,`meta`,{}),v(this,`customer`,{})}},ye=class extends x{constructor(){super(),v(this,`sequence`,0),v(this,`uid`,S.Section+t())}},be=class extends x{constructor(){super(),v(this,`permissions`,[]),v(this,`is_default`,!1),v(this,`uid`,S.EmployeeRole+t())}},xe=class{constructor(e){v(this,`item_uid`,``),v(this,`quantity`,0),v(this,`modifiers`,[]),this.item_uid=e,this.quantity=0,this.modifiers=[]}},O=class extends ue{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)}},Se=class{constructor(){v(this,`system`,Ce.POS),v(this,`visible`,!1),v(this,`sequence`,0)}};let Ce=function(e){return e.POS=`pos`,e.QrCodeOrder=`qr_code_order`,e}({}),we=function(e){return e.Product=`product`,e.Modifier=`modifier`,e}({});var Te=class extends O{constructor(){super(),v(this,`type`,we.Modifier),v(this,`visibility`,[]),v(this,`uid`,S.ItemModifierCategory+t()),v(this,`max_order`,0),v(this,`min_order`,0),v(this,`is_delisted`,!1)}},Ee=class extends O{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`,we.Product),v(this,`is_delisted`,!1),v(this,`subcategories`,[]),v(this,`uid`,S.Category+t()),v(this,`max_order`,0),v(this,`min_order`,0)}},De=class extends O{constructor(){super(),v(this,`category_uid`,``),v(this,`uid`,S.Subcategory+t())}};let k=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 Oe=class extends O{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`,k.Modifier),v(this,`barcode`,``),v(this,`category_uid`,``),v(this,`price`,0),v(this,`original_price`,0),v(this,`prices`,[]),v(this,`stock`,1e3),v(this,`print_on_receipt`,!0),v(this,`price_adjustable`,!1),v(this,`is_sold_out`,!1),v(this,`recipe`,``),v(this,`is_remark_disabled`,!1),v(this,`uid`,S.ItemModifier+t())}},A=class extends Oe{constructor(){super(),v(this,`codename`,``),v(this,`sku`,``),v(this,`recipe`,``),v(this,`barcode`,``),v(this,`type`,k.ByQuantity),v(this,`add_credit`,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`,S.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`,[])}},ke=class extends b{constructor(){super(),v(this,`lookup_keys`,[]),v(this,`product_uid`,``),v(this,`uid`,S.Price+t()),v(this,`amount`,0),v(this,`name`,``),v(this,`name_translations`,{})}},Ae=class{constructor(){v(this,`item_uid`,``),v(this,`combo_item`,new A),v(this,`price`,0),v(this,`sequence`,0),v(this,`meta`,{})}},je=class{constructor(){v(this,`uid`,S.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`,{})}},j=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(j,`State`,{CLOSED:0,OPENING:1,OPENED:2,CLOSING:3}),v(j,`electronSocket`,null);function Me(e){return e===`69`}const Ne={Ẳ: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 Pe(e,t=63){let n=[];for(let r of e)if(Ne[r]!==void 0)n.push(Ne[r]);else{let e=r.charCodeAt(0);e<=127?n.push(e):n.push(t)}return Uint8Array.from(n)}function Fe(){return typeof Socket>`u`?new j:new Socket}var Ie=class{constructor(){v(this,`socket`,void 0),this.socket=Fe(),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 t=new n,r=t.initialize();if(e.codepage&&!Object.values(M).includes(e.codepage)){let t=parseInt(e.codepage,10);r.raw([31,27,31,255,t,10,0])}else e.codepage&&Object.values(M).includes(e.codepage)?t.codepage(e.codepage):t.codepage(M.SimplifiedChinese);for(let t of e.items){if(!t)throw Error(`Item is undefined or null`);switch(t.style){case Re.Bold:r.bold(!0);break;case Re.Italic:r.italic(!0);break;case Re.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 N.Text:if(t.item?.text){if(t.item.size===ze.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(Me(e.codepage)){let e=Pe(t.item.text);r.raw(Array.from(e))}else r.text(t.item.text,t.item.line_width??48);t.item.size===ze.Custom&&r.raw([29,33,0])}break;case N.Table:if(t.table){if(t.table.size===ze.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(n=>{if(Me(e.codepage)){let e=Pe(n);r.raw(Array.from(e))}else r.text(n,t.table.line_width??48);r.newline()}),t.table.size===ze.Custom&&r.raw([29,33,0])}break;case N.Line:r.line(t.item?.text?.repeat(48)??`-`.repeat(48),t.item?.line_width??48);break;case N.NewLine:t.repeat=t.repeat??1;for(let e=0;e<t.repeat;e++)r.newline();break;case N.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 N.QRCode:t.qrcode&&r.qrcode(t.qrcode.data,t.qrcode.model,t.qrcode.size,t.qrcode.errorlevel);break;case N.Barcode:t.barcode&&r.barcode(t.barcode.data,t.barcode.symbology,t.barcode.height);break;case N.Cut:r.cut(t.item?.text??`full`);break;case N.Beeper:r.beeper();break;case N.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 n=Array.from(e).reduce((e,t)=>e+r(t),0);return e+` `.repeat(Math.max(0,t-n))}padStart(e,t){let n=Array.from(e).reduce((e,t)=>e+r(t),0);return` `.repeat(Math.max(0,t-n))+e}wrapText(e,t){if(typeof e!=`string`&&(e=e.toString()),!e)return[``];let n=[],i=``,a=0;for(let o of e){let e=r(o);a+e>t&&(n.push(i),i=``,a=0),i+=o,a+=e}return i&&n.push(i),n}async disconnect(){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 M=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}({}),Le=function(e){return e.Left=`left`,e.Center=`center`,e.Right=`right`,e}({}),Re=function(e){return e.Normal=`normal`,e.Bold=`bold`,e.Italic=`italic`,e.Underline=`underline`,e}({}),ze=function(e){return e.Custom=`custom`,e.Normal=`normal`,e.Small=`small`,e}({}),N=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 Be=class{constructor(){v(this,`data`,``),v(this,`symbology`,`ean13`),v(this,`height`,0)}},Ve=class{constructor(){v(this,`data`,``),v(this,`model`,2),v(this,`size`,6),v(this,`errorlevel`,`m`)}},He=class{constructor(){v(this,`base64_data`,``),v(this,`width`,0),v(this,`height`,0),v(this,`algorithm`,`threshold`),v(this,`threshold`,128)}};let Ue=function(e){return e[e.SunmiPrinter=0]=`SunmiPrinter`,e}({});var P=class{constructor(){v(this,`codepage`,M.WesternEuropeanLatin),v(this,`items`,[])}};function F(t,n){return e(t).format(n||`YYYY-MMM-DD HH:mm:ss`)}function We(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 Ge=class extends x{constructor(){super(),v(this,`machine_name`,``),v(this,`connection_id`,``),v(this,`type`,qe.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:``})}},Ke=class extends x{constructor(){super(),v(this,`type`,qe.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 qe=function(e){return e.Client=`client`,e.Node=`node`,e}({}),I=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}({});var Je=class{constructor(){v(this,`printer_name`,``),v(this,`status`,``),v(this,`port_name`,``),v(this,`error`,``)}};let Ye=function(e){return e.ESCPOS=`ESC/POS`,e.TSPL=`TSPL`,e}({}),Xe=function(e){return e.USB=`USB`,e.WINDOWS_DRIVER=`WINDOWS_DRIVER`,e.ETHERNET=`ETHERNET`,e.BLUETOOTH=`BLUETOOTH`,e.BUILTIN=`BUILTIN`,e}({});var Ze=class{constructor(){v(this,`header`,``),v(this,`body`,``),v(this,`footer`,``),v(this,`commands`,``),v(this,`type`,I.ReceiptPrinter)}},L=class extends x{constructor(){super(),v(this,`header`,``),v(this,`body`,``),v(this,`footer`,``),v(this,`commands`,``),v(this,`printer_type`,I.ReceiptPrinter),v(this,`codepage`,void 0),v(this,`uid`,S.PrintTemplate+t()),v(this,`report_code_name`,``)}};let Qe=function(e){return e.Queued=`queued`,e.Printed=`printed`,e.Failed=`failed`,e.Expired=`expired`,e}({});var R=class extends x{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`,I.ReceiptPrinter),v(this,`protocol`,Ye.ESCPOS),v(this,`connection_type`,Xe.ETHERNET),v(this,`data`,new P),v(this,`status`,Qe.Queued),v(this,`retries`,0),v(this,`commands`,``),v(this,`uid`,S.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 $e=function(e){return e.Online=`online`,e.Offline=`offline`,e}({});var et=class extends x{constructor(){super(),v(this,`device_uid`,``),v(this,`type`,I.ReceiptPrinter),v(this,`is_not_default`,!1),v(this,`driver_printer_name`,``),v(this,`fallback_printer_uid`,0),v(this,`protocol`,Ye.ESCPOS),v(this,`connection_type`,Xe.ETHERNET),v(this,`print_template_uid`,``),v(this,`uid`,S.Printer+t()),v(this,`ip_address`,``),v(this,`status`,$e.Online),v(this,`kitchen_itemized_print`,!1),v(this,`print_times`,1),v(this,`retries`,1)}},tt=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=F(this.printed_at)}},z=class{constructor(){v(this,`printer_name`,``),v(this,`kitchen_itemized_print`,!1),v(this,`is_cancel`,!1)}},nt=class extends b{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 rt),v(this,`payment_method_history`,void 0),v(this,`uid`,S.Payment+t()),v(this,`updated_at`,new Date)}},rt=class extends x{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,`uid`,S.PaymentMethod+t())}},it=class extends rt{constructor(){super(),v(this,`changed_at`,new Date),v(this,`changed_by`,``)}},at=class{toPaymentMethod(){let e=new rt;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 ot=function(e){return e.STARTED=`payment_started`,e.COMPLETED=`payment_completed`,e.FAILED=`payment_failed`,e.CANCELLED=`payment_cancelled`,e}({});var st=class extends x{constructor(){super()}},ct=class extends st{constructor(){super()}},lt=class extends x{constructor(){super(),v(this,`note_group_uid`,``),v(this,`related_model`,de.Invoice),v(this,`usage`,0)}},ut=class extends lt{constructor(){super()}};let B=function(e){return e.DineIn=`dine_in`,e.TakeOut=`take_out`,e.Delivery=`delivery`,e}({}),dt=function(e){return e.PayToOrder=`pay_to_order`,e.OrderFirstAndPayLater=`order_first_and_pay_later`,e.OnSelection=`on_selection`,e}({}),ft=function(e){return e.Inclusive=`inclusive`,e.Exclusive=`exclusive`,e}({}),V=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}({}),pt=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}({}),mt=function(e){return e.quantity=`quantity`,e.weight=`weight`,e}({}),H=function(e){return e.Flat=`flat`,e.Percent=`percent`,e}({}),U=function(e){return e.AfterSubtotal=`after_subtotal`,e.AfterServiceCharge=`after_service_charge`,e.AfterGrantTotal=`after_grant_total`,e}({}),ht=function(e){return e.Custom=`custom`,e.Voucher=`voucher`,e.Coupon=`coupon`,e}({});var gt=class{constructor(){v(this,`uid`,S.InvoiceCharge+t()),v(this,`name`,``),v(this,`percentage`,0),v(this,`amount`,0),v(this,`calc_flow`,U.AfterSubtotal)}},_t=class{constructor(){v(this,`action`,pt.Create),v(this,`action_by`,``),v(this,`device_uid`,``),v(this,`action_at`,new Date)}},vt=class{constructor(){v(this,`uid`,S.Charge+t()),v(this,`name`,``),v(this,`percent`,0),v(this,`calc_flow`,U.AfterSubtotal),v(this,`trigger_condition`,``)}},W=class{constructor(){v(this,`calc_type`,H.Flat),v(this,`amount`,0),v(this,`percent`,0),v(this,`percent_amount`,0),v(this,`type`,ht.Custom),v(this,`calc_flow`,U.AfterSubtotal),v(this,`applying_item_uids`,[]),v(this,`name`,``),v(this,`name_translation`,{}),v(this,`voucher_uid`,``),v(this,`coupon_uid`,``),v(this,`uid`,S.InvoiceDiscount+t())}},yt=class{constructor(){v(this,`item_uid`,``),v(this,`item`,new Oe),v(this,`price`,0),v(this,`unit_of_measure`,mt.quantity),v(this,`quantity`,0),v(this,`sent`,0),v(this,`is_cancel_printed`,!1),v(this,`selected`,!1),v(this,`sales_user_uid`,``)}},bt=class extends b{constructor(){super(),v(this,`item_uid`,``),v(this,`price`,0),v(this,`unit_of_measure`,mt.quantity),v(this,`quantity`,0),v(this,`remark`,``),v(this,`invoice_uid`,``),v(this,`discount_calc_type`,H.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 A),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,`is_cancel_printed`,!1),v(this,`selected`,!1),v(this,`sales_user_uid`,``),v(this,`meta`,{})}},xt=class extends b{constructor(){super(),v(this,`ref_id`,``),v(this,`call_num`,``),v(this,`table_uid`,``),v(this,`table_name`,``),v(this,`type`,B.DineIn),v(this,`pax`,0),v(this,`adult_pax`,0),v(this,`child_pax`,0),v(this,`baby_pax`,0),v(this,`subtotal`,0),v(this,`point_subtotal`,0),v(this,`service_chargeable_subtotal`,0),v(this,`discountable_subtotal`,0),v(this,`service_charge`,0),v(this,`delivery_id`,0),v(this,`delivery_charge`,0),v(this,`delivery_type`,``),v(this,`delivery_by`,``),v(this,`use_customer_point`,!1),v(this,`add_point`,0),v(this,`minus_point`,0),v(this,`rewarded_point_rate`,0),v(this,`rewarded_point`,0),v(this,`use_customer_balance`,!1),v(this,`add_credit`,0),v(this,`minus_credit`,0),v(this,`rewarded_credit_rate`,0),v(this,`rewarded_credit`,0),v(this,`discounts`,[]),v(this,`discount_amount`,0),v(this,`tax`,0),v(this,`rounding`,0),v(this,`tip`,0),v(this,`grand_total`,0),v(this,`customer_id`,0),v(this,`remark`,``),v(this,`sales_user_uid`,``),v(this,`status`,V.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 te),v(this,`payment_source_method`,``),v(this,`payment_source_last4`,``),v(this,`payment_source_charge_ref`,``),v(this,`is_sales_exclusive`,!1),v(this,`etc`,{}),v(this,`action`,void 0),v(this,`lines`,[]),v(this,`deleted_lines`,[]),v(this,`payment_has_cash`,!1),v(this,`payments`,[]),v(this,`table_switch_id`,0),v(this,`employee_uid`,``),v(this,`employee_name`,``),v(this,`receipt_print_override`,!1),v(this,`customer`,new ne),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,`charges`,[]),v(this,`is_charge_triggered`,!1),v(this,`uid`,S.Invoice+t()),v(this,`meta`,{}),v(this,`price_lookup_key`,``)}},St=class extends b{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`,S.Employee+t()),v(this,`role_uid`,``),v(this,`language`,`en`),v(this,`can_login`,!0)}},Ct=class extends b{constructor(){super(),v(this,`config`,new jt),v(this,`cache`,new wt),v(this,`storage`,{pricing_lookup_keys:[],pay_in_reasons:[],pay_out_reasons:[]})}},wt=class{constructor(){v(this,`printers`,[])}},Tt=class{constructor(){}},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)}},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)}};let Ot=function(e){return e.SmoochPay=`SPCD`,e.YeahPay=`YEAP`,e}({});var kt=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,`landing_image`,``),v(this,`menu_banner_image`,``),v(this,`home_page_images`,[]),v(this,`paynow_method`,Mt.WyoPaynow),v(this,`card_payment_code`,Ot.SmoochPay)}},At=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})}},jt=class{constructor(){v(this,`general`,new It),v(this,`product`,new Ft),v(this,`till`,new Lt),v(this,`report`,new Rt),v(this,`receipt`,new zt),v(this,`kitchen`,new Bt),v(this,`kds`,new Vt),v(this,`label`,new Ht),v(this,`order`,new Ut),v(this,`ods`,new Wt),v(this,`payment`,new Gt),v(this,`user`,new Kt),v(this,`tax`,new qt),v(this,`rounding`,new Xt),v(this,`inventory`,new Zt),v(this,`pax_config`,new Qt),v(this,`gto`,new $t),v(this,`cash_drawer`,new en),v(this,`marketing`,new At),v(this,`charges`,new Jt),v(this,`currency`,new Yt),v(this,`cds`,new Dt),v(this,`kiosk`,new kt),v(this,`online_order`,new Nt),v(this,`loyalty_program`,new Et),v(this,`crm`,new Tt)}};let Mt=function(e){return e.FomoOnlinePaynow=`PNWO`,e.WyoPaynow=`WPPN`,e}({});var Nt=class{constructor(){v(this,`enable_membership`,!1),v(this,`login_call_to_action_text`,``),v(this,`menu_banner_image_url`,``),v(this,`paynow_method`,void 0),v(this,`disable_pay_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:dt.OrderFirstAndPayLater,select_order_flow:!1,select_menus:!1}),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`,{})}};let Pt=function(e){return e.PROD=`prod`,e.DEV=`dev`,e}({});var Ft=class{constructor(){v(this,`enable_codename_search`,!1)}},It=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`,Pt.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`}}])}},Lt=class{constructor(){v(this,`control`,!0),v(this,`slip`,!0)}},Rt=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,`hide_non_price_item`,!1),v(this,`receipt_no_reset_daily`,!1),v(this,`language`,`en`),v(this,`disable_persistent_tcp`,!1)}},Bt=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`)}},Vt=class{constructor(){v(this,`enabled`,!0),v(this,`display_order_after_payment`,!1),v(this,`print_slip_upon_completed`,!1)}},Ht=class{constructor(){v(this,`print`,!1),v(this,`text_to_raster`,!1)}},Ut=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`)}},Wt=class{constructor(){v(this,`enabled`,!1),v(this,`language`,`en`)}},Gt=class{constructor(){v(this,`quick_cash_payment`,!1),v(this,`notification`,!0),v(this,`quick`,!1)}},Kt=class{constructor(){v(this,`control`,!0)}},qt=class{constructor(){v(this,`enabled`,!0),v(this,`method`,ft.Inclusive),v(this,`rate`,7),v(this,`name`,`GST`)}},Jt=class{constructor(){v(this,`service_charge`,!1),v(this,`service_charge_rate`,10)}},Yt=class{constructor(){v(this,`currency_symbol`,`$`),v(this,`is_symbol_after_amount`,!1)}},Xt=class{constructor(){v(this,`base`,.1),v(this,`up`,!0),v(this,`cashless`,!1),v(this,`prepayment_rounding`,!1)}},Zt=class{constructor(){v(this,`inventory_control`,!1),v(this,`sold_out_for_today_only`,!1)}},Qt=class{constructor(){v(this,`pax`,!0),v(this,`detail`,!1)}},$t=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`)}},en=class{constructor(){v(this,`kick_code`,`27, 112, 48, 55, 121`),v(this,`connection_mode`,`via_receipt_printer`)}},tn=class{constructor(e){v(this,`name`,``),v(this,`base64`,``),v(this,`extension`,`png`),Object.assign(this,e)}};const nn=e=>e===``||e===void 0,rn=e=>t=>nn(e)||t.includes(e),an=e=>t=>nn(e)||e.includes(t),on=(e,t)=>n=>n>e&&n<t,sn=e=>typeof e==`function`?(t,n)=>!e(t,n):t=>t!=e,cn=e=>e,ln=e=>t=>!t.deleted_at&&Object.keys(e).every(n=>{if(nn(e[n])||t[n]===e[n])return!0;if(typeof e[n]==`function`)return e[n](t[n],t)});var un=class{constructor(){v(this,`db`,void 0),v(this,`moduleName`,void 0)}get table(){return this.db.table(this.moduleName)}liveQuery(e){return a(e)}async saveOne(e){let n={...e};return n.created_at||(n.created_at=new Date),n.uid||(n.uid=t()),n.updated_at=new Date,await this.db.table(this.moduleName).put(n),n}async saveMany(e){let n=e.map(e=>(e.uid||(e.uid=t(),e.created_at=new Date),e.updated_at=new Date,e));return await this.db.table(this.moduleName).bulkPut(n),n}async hasAny(){return await this.db.table(this.moduleName).count()>0}async getOne(e){return await this.db.table(this.moduleName).get(e)||null}async getOneByParams(e){return this.db.table(this.moduleName).filter(ln(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(ln(e)).count(),o=this.db.table(this.moduleName).filter(ln(e));return r!==-1&&o.offset((n-1)*r).limit(r),{list:await o.toArray(),count:a,page:n,pageSize:r}}},dn=class extends un{async updateOne(e,t){throw Error(`Method not implemented.`)}async deleteOne(e){throw Error(`Method not implemented.`)}},G=class extends un{constructor(...e){super(...e),v(this,`http`,void 0),v(this,`methodName`,void 0),v(this,`options`,void 0)}async addOne(e){return this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${this.methodName}`,e)}async updateOne(e,t){return this.http.patch(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${e}`,t)}async updateMany(e){return this.http.patch(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}`,e)}async deleteOne(e){return e.deleted_at=new Date,this.http.delete(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${e.id_in_server}`)}async hardDeleteOne(e){return await this.db.table(this.moduleName).delete(e.uid),e}};let fn=function(e){return e[e.printable=0]=`printable`,e[e.generative=1]=`generative`,e}({});var pn=class{constructor(){v(this,`uid`,S.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)}},mn=class{constructor(){v(this,`uid`,S.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)}},hn=class extends b{constructor(){super(),v(this,`uid`,S.AppReport+t()),v(this,`reports`,[]),v(this,`version`,1)}},gn=class{constructor(){v(this,`start_datetime`,``),v(this,`humanized_start_datetime`,``),v(this,`end_datetime`,``),v(this,`humanized_end_datetime`,``),v(this,`humanized_printed_datetime`,``),v(this,`sales_summary`,new _n),v(this,`drawer_summary`,new vn),v(this,`payments_summary`,[]),v(this,`loyalty_program_summary`,new bn),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`,{})}},_n=class{constructor(){v(this,`sales_total`,0),v(this,`foc_sales_total`,0),v(this,`foc_sales_count`,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)}},vn=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)}},yn=class{constructor(){v(this,`code`,``),v(this,`name`,``),v(this,`total`,0),v(this,`count`,0)}},bn=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)}},xn=class{constructor(){v(this,`item`,{}),v(this,`quantity`,0),v(this,`total_amount`,0),v(this,`modifiers`,[])}},Sn=class{constructor(){v(this,`item`,{}),v(this,`quantity`,0),v(this,`total_amount`,0)}},Cn=class{constructor(){v(this,`category`,null),v(this,`items`,[]),v(this,`total_quantity`,0),v(this,`total_amount`,0)}},wn=class extends G{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 Rr(e,t,n,`configs`,`config`),this.printJobService=new qr(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(I.ReceiptPrinter)}async getDefaultPrinterByType(e){return this.getDefaultPrinter(e)}async getDefaultKioskPrinter(){return this.getDefaultPrinter(I.KioskPrinter)}async getDefaultCheckPrinter(){return this.getDefaultPrinter(I.CheckPrinter)}async getDefaultKitchenPrinter(){return this.getDefaultPrinter(I.KitchenPrinter)}async getDefaultOrderPrinter(){return this.getDefaultPrinter(I.OrderPrinter)}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 d.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 Ie().connect(s,t,200)&&n.push(s)}return await this.configService.updateCache({printers:n}),n}async openCashDrawer(){let e=await this.getDefaultReceiptPrinter(),t=new P;t.items.push({type:N.OpenCashDrawer});let n=new R(e,t,!1,1);await this.printJobService.addOne(n)}};function K(e,t=2){let n=10**t;return Math.round(e*n)/n}function Tn(e){let t=e.name,n=t.lastIndexOf(`.`);return n===-1||n===t.length-1?``:t.slice(n+1)}function En(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 q=(e,t)=>e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/[_\-\.]+/g,` `).toLowerCase().replace(/[\s]+(\w)/g,(e,n)=>t(n)),Dn=e=>e.replace(/^\W+|\W+$/g,``),On=e=>typeof e==`string`?q(e,e=>e.toUpperCase()):``,kn=e=>typeof e==`string`?e.charAt(0).toUpperCase()+e.slice(1):``,An=e=>typeof e==`string`?e.replace(/\w\S*/g,e=>kn(e)):``,jn=e=>typeof e==`string`?q(e,e=>`-`+e):``,Mn=e=>typeof e==`string`?q(e,e=>`.`+e):``,Nn=e=>Pn(e),Pn=e=>typeof e==`string`?e.toLowerCase():``,Fn=e=>{if(typeof e!=`string`)return``;let t=q(e,e=>e.toUpperCase());return t.charAt(0).toUpperCase()+t.slice(1)},In=e=>typeof e==`string`?q(e,e=>`/`+e):``,Ln=e=>typeof e==`string`?e.replace(/((?:\S[^\.\?\!]*)[\.\?\!]*)/g,e=>e.charAt(0).toUpperCase()+e.substr(1).toLowerCase()):``,Rn=e=>typeof e==`string`?q(e,e=>`_`+e):``,zn=e=>typeof e==`string`?e.replace(/[- _]+/g,` `).split(` `).map(e=>kn(e)).join(` `):``,Bn=e=>Vn(e),Vn=e=>typeof e==`string`?e.toUpperCase():``,Hn=(e,t)=>typeof e==`string`&&typeof t==`string`?e+t:e,Un=(e,t)=>{if(typeof e!=`string`)return``;let n=``;for(let e=0;e<t;e++)n+=` `;return n+e+n},Wn=e=>typeof e==`string`?Dn(e):``,Gn=e=>typeof e==`string`?e.split(` `).join(`-`):``,Kn=(e,t=` `)=>typeof e==`string`?(typeof t!=`string`&&(t=` `),e.split(t).join(`+`)):``,qn=(e,t)=>typeof e==`string`&&typeof t==`string`?t+e:e,Jn=(e,t)=>typeof e==`string`?typeof t==`string`?e.split(t).join(``):e:``,Yn=(e,t)=>typeof e==`string`?typeof t==`string`?e.replace(t,``):e:``,Xn=(e,t,n)=>typeof e==`string`?typeof t==`string`?(typeof n!=`string`&&(n=``),e.split(t).join(n)):e:``,Zn=(e,t,n)=>typeof e==`string`?typeof t==`string`?(typeof n!=`string`&&(n=``),e.replace(t,n)):e:``,Qn=e=>typeof e==`string`?e.split(``).reverse().join(``):``,$n=(e,t=`,`)=>typeof e==`string`?(typeof t!=`string`&&(t=`,`),e.split(t)):[],er=(e,t)=>typeof e==`string`?e.length<=t?e:ir(e,t)+`…`:``,tr=e=>typeof e==`string`?e.trim():``,nr=e=>typeof e==`string`?e.replace(/^\s+/,``):``,rr=e=>typeof e==`string`?e.replace(/\s+$/,``):``,ir=(e,t,n=``)=>typeof e==`string`?(typeof n!=`string`&&(n=``),e.length>t?e.slice(0,t-n.length)+n:e):``;var ar={camelcase:On,capitalize:kn,capitalizeAll:An,dashcase:jn,dotcase:Mn,downcase:Nn,lowercase:Pn,pascalcase:Fn,pathcase:In,sentence:Ln,snakecase:Rn,titleize:zn,upcase:Bn,uppercase:Vn,append:Hn,center:Un,chop:Wn,hyphenate:Gn,plusify:Kn,prepend:qn,remove:Jn,removeFirst:Yn,replace:Xn,replaceFirst:Zn,reverse:Qn,split:$n,ellipsis:er,trim:tr,trimLeft:nr,trimRight:rr,truncate:ir,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 or=e=>e&&typeof e==`object`&&typeof e.fn==`function`,J=(e,t,n)=>or(n)?e?n.fn?n.fn(t):!0:n.inverse?n.inverse(t):!1:e,sr=function(...e){let t=e.pop();return J(e.every(e=>!!e),this,t)},cr=function(...e){let t=e.pop();return J(e.some(e=>!!e),this,t)},lr=function(e,t){return J(!e,this,t)},ur=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),J(e===t,this,n)},dr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),J(e==t,this,n)},fr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),J(e!==t,this,n)},pr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),J(e!=t,this,n)},mr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),J(e>t,this,n)},hr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),J(e>=t,this,n)},gr=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),J(e<t,this,n)},_r=function(e,t,n){return arguments.length===2&&(n=t,t=n?.hash?.compare),J(e<=t,this,n)},vr=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 J(i,this,r)},yr=function(e,t,n){return typeof n==`number`&&(n=arguments[3]),J(e==null?!1:Array.isArray(e)||typeof e==`string`?e.includes(t):typeof e==`object`?t in e:!1,this,n)},br=yr,xr=function(e,...t){let n=t.pop();return J(t.includes(e),this,n)},Sr=(e,t)=>{if(!(!e||!t))return t.split(`.`).reduce((e,t)=>e?.[t],e)},Cr=e=>{let t=[];for(let n=0;n<e.length-1;n+=2)typeof e[n]==`string`&&!or(e[n+1])&&t.push({prop:e[n],value:e[n+1]});return t};var wr={and:sr,or:cr,not:lr,eq:ur,is:dr,neq:fr,isnt:pr,gt:mr,gte:hr,lt:gr,lte:_r,compare:vr,contains:yr,includes:br,in:xr,findAnd:function(e,...t){if(!Array.isArray(e))return null;let n=Cr(t);return e.find(e=>n.every(t=>Sr(e,t.prop)===t.value))||null},findOr:function(e,...t){if(!Array.isArray(e))return null;let n=Cr(t);return e.find(e=>n.some(t=>Sr(e,t.prop)===t.value))||null},filterAnd:function(e,...t){if(!Array.isArray(e))return[];let n=Cr(t);return e.filter(e=>n.every(t=>Sr(e,t.prop)===t.value))},filterOr:function(e,...t){if(!Array.isArray(e))return[];let n=Cr(t);return e.filter(e=>n.some(t=>Sr(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 J(!e&&!t,this,n)},ifEven:function(e,t){return J(e%2==0,this,t)},ifOdd:function(e,t){return J(e%2!=0,this,t)},ifNth:function(e,t,n){return J(typeof e==`number`&&typeof t==`number`&&t%e===0,this,n)}};function Tr(e){let t=e?.handlebars||e?.hbs||ee(`handlebars`);return Object.keys(ar).forEach(e=>{t.registerHelper(e,ar[e])}),Object.keys(wr).forEach(e=>{t.registerHelper(e,wr[e])}),t.helpers}var Er=Tr,Dr=class extends b{constructor(){super(),v(this,`uid`,S.OrderDisplaySystem+t()),v(this,`order_number`,``),v(this,`status`,Y.Preparing)}};let Y=function(e){return e.Preparing=`preparing`,e.ReadyForPickup=`ready_for_pickup`,e}({});var Or=class extends G{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 C(`Display order not found`);if(t.status==`ready_for_pickup`)throw new C(`Order is already ready for pickup`);if(t.status=Y.ReadyForPickup,t.updated_at=new Date,t.id_in_server==0)throw new C(`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 C(`Display order not found`);if(t.status==`preparing`)throw new C(`Order is already preparing`);if(t.status=Y.Preparing,t.updated_at=new Date,t.id_in_server==0)throw new C(`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==Y.ReadyForPickup).reverse().limit(100).toArray();if(e.length===0)throw new C(`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=Y.Preparing,t.updated_at=new Date,t.id_in_server==0)throw new C(`Order is not synced with server`);return await this.updateOne(t.id_in_server,t),t}};Er({handlebars:f});const kr={quantity:1,price:0,remark:``};var Ar=class extends G{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,`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 X(e,t,n,`tills`,`till`),this.sectionItemService=new Br(e,t,n,`section_items`,`section_item`),this.configService=new Rr(e,t,n,`configs`,`config`),this.printTemplateService=new Yr(e,t,n,`print_templates`,`print_template`),this.printerService=new wn(e,t,n,`printers`,`printer`),this.printJobService=new qr(e,t,n,`print_jobs`,`print_job`),this.itemService=new Ir(e,t,n,`items`,`item`),this.orderDisplayService=new Or(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,U.AfterSubtotal),e.grand_total<0&&(e.grand_total=0,e.service_chargeable_subtotal=0),this.calculateInvoiceCharges(e,U.AfterSubtotal),e.subtotal>0&&e.discount_amount>0){let t=1-e.discount_amount/e.subtotal;e.service_chargeable_subtotal=K(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,U.AfterServiceCharge),e.grand_total<0&&(e.grand_total=0),this.calculateInvoiceCharges(e,U.AfterServiceCharge);let i=t.config.tax.enabled?t.config.tax.rate:0;return this.calculateTax(e,i,t.config.tax.method),this.calculateDeliveryCharge(e),this.calculateCreditDeduction(e),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,U.AfterGrantTotal),e.grand_total<0&&(e.grand_total=0),this.calculateInvoiceCharges(e,U.AfterGrantTotal),e.grand_total=K(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),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+=K(n.subtotal,2),e.point_subtotal+=n.point_subtotal;e.subtotal=K(t,2),e.grand_total=K(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=K(e.quantity*(e.price+t),2),e.item.discountable&&(e.discount_amount>0||e.discount_percent>0)&&(e.discount_calc_type==H.Flat||(e.discount_amount=K(e.subtotal*e.discount_percent,2)),e.subtotal-=e.discount_amount),e.subtotal=K(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=K(K(e.lines.filter(e=>!e.is_take_out&&!e.item.is_service_charge_exempt).reduce((e,t)=>e+t.subtotal,0)),2)}calculateDiscount(e,t){if(!e?.lines?.length)return;let n=0;if(e.discountable_subtotal=K(e.lines.filter(e=>e.item.discountable).reduce((e,t)=>e+t.subtotal,0),2),e.discounts?.length){for(let r of e.discounts.filter(e=>e.calc_flow==t))if(!r.applying_item_uids?.length)r.calc_type==H.Flat?n+=r.amount:(r.percent_amount=K((e.discountable_subtotal-e.discount_amount-n)*r.percent),n+=r.percent_amount);else{let t=0,i=!1;for(let n of e.lines)r.applying_item_uids.includes(n.item_uid)&&n.price>t&&(t=n.price,i=!0);if(!i){e.discounts=e.discounts.filter(e=>e.uid!=r.uid);continue}r.calc_type==H.Flat?(r.amount=K(r.amount>t?t:r.amount),n+=r.amount):(r.percent_amount=K(t*r.percent),n+=r.percent_amount)}e.discount_amount+=K(n),e.grand_total=K(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=K(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,K(s/100)}calculateDeliveryCharge(e){e.delivery_charge>0&&e.type===B.Delivery&&(e.grand_total+=e.delivery_charge,e.grand_total=K(e.grand_total,2))}calculateServiceCharge(e,t){let n=0;e.service_charge=0,!(e.lines==null||e.lines.length<1)&&(e.type==B.Delivery||e.type==B.TakeOut||(t>0&&(n=e.service_chargeable_subtotal*(t/100)),e.service_charge=K(n,2),e.grand_total+=e.service_charge,e.grand_total=K(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===ft.Inclusive?e.tax=K(i*r*t/(100+t)+e.service_charge*t/(100+t),2):(e.tax=K(i*r*t/100+e.service_charge*t/100,2),e.grand_total=K(e.grand_total+e.tax,2))}calculateCreditDeduction(e){e.minus_credit>0&&(e.minus_credit>e.grand_total&&(e.minus_credit=e.grand_total),e.grand_total-=e.minus_credit)}calculateTaxSubtotalRatio(e){let t=1;return!e.lines||!e.lines.some(e=>e.item.is_tax_exempt)||e.grand_total===0||e.subtotal===0||(t=1-e.lines.filter(e=>e.item.is_tax_exempt).reduce((e,t)=>e+t.subtotal,0)/e.subtotal),t}calculateRewardCredit(e,t,n,r){if(e.rewarded_credit=0,e.grand_total<=0||t>0&&t>e.grand_total)return;let i=e.rewarded_credit_rate,a=e.grand_total;n&&(a-=e.service_charge),r&&(a-=e.tax),a-=e.lines.filter(e=>e.item.is_credit_reward_exempt).reduce((e,t)=>e+t.subtotal,0),e.rewarded_credit=K(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}}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=K((i+a)/2,2);if(r===i||r===a)break;let o=s.cloneDeep(e);o.discounts||(o.discounts=[]),o.discounts.push({...new W,calc_type:H.Flat,calc_flow:U.AfterServiceCharge,amount:r}),this.calculate(o,n),o.grand_total<=t?a=r:i=r}let o=s.cloneDeep(e);if(o.discounts=[...o.discounts||[],{...new W,calc_type:H.Flat,calc_flow:U.AfterServiceCharge,amount:a}],this.calculate(o,n),o.grand_total>t)throw Error(`Target grand total ${t} is unreachable`);return K(a,2)}resetInvoiceCalculations(e){e.subtotal=0,e.point_subtotal=0,e.service_chargeable_subtotal=0,e.service_charge=0,e.tax=0,e.grand_total=0,e.rounding=0,e.discount_amount=0,e.minus_credit=0,e.rewarded_credit=0,e.rewarded_point=0,e.add_credit=0,e.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=K(e.payments.reduce((e,t)=>e+t.tender_amount,0)-e.grand_total);e.payments.filter(e=>e.payment_method.is_cash);let n=e.payments.filter(e=>e.payment_method.is_cash);n.forEach(e=>e.change_amount=0);let r=n[n.length-1];r.change_amount=K(t)}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 U.AfterSubtotal:t=e.subtotal;break;case U.AfterServiceCharge:t=e.subtotal+e.service_charge;break;case U.AfterGrantTotal:t=e.grand_total;break;default:t=e.subtotal}n.percentage>0&&(n.amount=K(t*(n.percentage/100),2)),e.grand_total+=n.amount,e.grand_total=K(e.grand_total,2)}}},jr=class extends Ar{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==k.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=S.InvoiceLine+t(),e.lines.push(d)),d}duplicateLine(e,n){let r=s.cloneDeep(n);return r.is_duplicate=!0,r.duplicated_from_uid=n.uid,r.uid=S.InvoiceLine+t(),e.lines.push(r),e}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 yt;return n.item=s.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==H.Percent&&n>100)throw new C(`Discount percent can not be more than 100%`);if(t==H.Flat&&n>e.subtotal)throw new C(`Discount amount can not be more than price`);return e.discount_calc_type=t,t==H.Flat?e.discount_amount=n:e.discount_percent=n,e}minusLineQuantity(e,t,n,r=!1){if(n<=0)throw new C(`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 C(`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=s.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}addLineQuantity(e,t,n){if(e.lines==null||e.lines.length<=0)return e;t.quantity+=n}minusModifierQuantity(e,t,n=0){if(!e||e.length<=0)return e;{n=n??0;let r=e.findIndex(e=>e.item_uid===t.item_uid&&e.price===t.price);return r<0||(e[r].quantity<=n?e.splice(r,1):e[r].quantity-=n),e}}changeModifierQuantity(e,t,n){if(!e||e.length<=0)return e;n=n??0;let r=e.findIndex(e=>e.item_uid===t.item_uid&&e.price===t.price);return r<0?e:(e[r].quantity+=n,e[r].quantity<=0&&e.splice(r,1),e)}addModifierQuantity(e,t,n=0){if(!e||e.length<=0)return e;{n=n??0;let r=e.findIndex(e=>e.item_uid===t.item_uid&&e.price===t.price);return r<0||(e[r].quantity+=n),e}}changeModifierPrice(e,t){return e&&(e.price=t,e)}overwriteNoteToLine(e,t){return t&&(e.remark=t),e}findOrCreateLine(e,t,n,r=0,i=[],a=``,o=!1,s,c){if(r=r??t.price,!e.lines||e.lines.length<=0||o)return this.createInvoiceLine(t,n,r,i,a);{let o=e.lines.filter(e=>e.item_uid===t.uid);if(!o||o.length<=0)return this.createInvoiceLine(t,n,r,i,a);if(s&&c){for(let e of o.filter(e=>e.is_combo_item))if(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(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 bt;return a.item=s.cloneDeep(e),a.item_uid=e.uid,a.quantity=t,a.point=e.minus_point,a.price=n??e.price,a.quantity=t,a.modifiers=r,a.remark=i,a}compareModifiers(e,t){if(e.length!==t.length)return!1;for(let n of e)if(!t.some(e=>e.item_uid===n.item_uid&&e.price===n.price&&e.quantity===n.quantity))return!1;return!0}compareLines(e,t){return!(e.remark!=t.remark||e.price!=t.price||e.is_take_out!=t.is_take_out||e.discount_calc_type!=t.discount_calc_type||e.discount_amount!=t.discount_amount||e.discount_percent!=t.discount_percent||!this.compareModifiers(e.modifiers,t.modifiers))}addComboItemToLine(e,t,n,r,i,a,o,s){let c=this.addItemToLine(e,t,n,r,o,s,!1,i,a);return c.is_combo_item=!0,c.combo_line_uid=i,c.combo_group_uid=a,c}removeAllComboItems(e,t,n=!1){if(!e.lines||e.lines.length==0)return[];let r=e.lines.filter(e=>e.combo_line_uid==t&&e.is_combo_item);return e.lines=s.differenceBy(e.lines,r,`uid`),n||e.deleted_lines.push(...r),r}duplicateComboLines(e,n){if(!n.is_combo)throw new C(`Line is not a combo`);let r=s.cloneDeep(n);return r.uid=S.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=s.cloneDeep(n);i.uid=S.InvoiceLine+t(),i.combo_line_uid=r.uid,i.is_duplicate=!0,e.lines.push(i)}),e}},Mr=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==w.outdatedInvoice)throw await this.saveOne(t.data),new C(t.error);if(t.error)throw new C(t.error);return t.data}async createInvoice(e,t,n){e.status=V.Open,e.ref_id||(e.ref_id=await this.getRefId()),e.call_num||(e.call_num=e.ref_id.slice(-3)),e.table_name=t.name,e.table_uid=t.uid,t.invoice_uid=e.uid,t.status=D.OPENED,this.sectionItemService.syncInvoiceData(t,e),this.addEmployeeToInvoice(e,n),e.created_at=new Date,e.created_at_timestamp=e.created_at.getTime();let r=(await this.configService.getDefaultOne()).config?.order?.datetime_format;e.humanized_created_at=F(e.created_at,r),t.invoice_created_at=new Date;let i=await this.createKitchenPrintJobs(e),a=await this.createLabelPrintJobs(e),o=await this.createOrderPrintJobs(e),s=this.sortPrintJobsByPrinterSequence([...i,...a,...o]);e.kitchen_print_job_uids||(e.kitchen_print_job_uids=[]),e.label_print_job_uids||(e.label_print_job_uids=[]);let c=e.kitchen_print_job_uids.length,l=e.label_print_job_uids.length,u=i.map(e=>e.uid),d=a.map(e=>e.uid);u.length>0&&e.kitchen_print_job_uids.push(u),d.length>0&&e.label_print_job_uids.push(d),await this.preprocessInvoice(e);let f={invoice:e,section_item:t};s.length>0&&(f.print_jobs=s);try{let e=await this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/${this.methodName}`,f);if(e.error==w.outdatedInvoice)throw await this.saveOne(e.data),f.invoice=e.data,new C(e.error);if(e.error==w.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),f.section_item=e.data,new C(e.error);return f}catch(t){throw e.kitchen_print_job_uids.length=c,e.label_print_job_uids.length=l,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.createLabelPrintJobs(e),o=await this.createOrderPrintJobs(e),s=this.sortPrintJobsByPrinterSequence([...r,...i,...a,...o]);e.kitchen_print_job_uids||(e.kitchen_print_job_uids=[]),e.label_print_job_uids||(e.label_print_job_uids=[]);let c=e.kitchen_print_job_uids.length,l=e.label_print_job_uids.length,u=r.map(e=>e.uid),d=a.map(e=>e.uid);u.length>0&&e.kitchen_print_job_uids.push(u),d.length>0&&e.label_print_job_uids.push(d),await this.preprocessInvoice(e);let f={invoice:e,section_item:t};s.length>0&&(f.print_jobs=s);try{let e=await this.http.patch(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/update_invoice`,f);if(e.error==w.outdatedInvoice)throw await this.saveOne(e.data),new C(`${e.error}, system has updated the data, please try again`);if(e.error==w.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),f.section_item=e.data,new C(`${e.error}, system has updated the data, please try again`);return f}catch(t){throw e.kitchen_print_job_uids.length=c,e.label_print_job_uids.length=l,t}}async cancelInvoice(e,t,n){if(e.id_in_server==0&&e.lines.length<=0)throw new C(`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=V.Void,t.invoice_uid=``,t.status=D.CLOSED,this.sectionItemService.reset(t),this.addEmployeeToInvoice(e,n);let r=await this.createReceiptPrintJob(e,I.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==w.outdatedInvoice)throw await this.saveOne(a.data),i.invoice=a.data,new C(a.error);if(a.error==w.outdatedSectionItem)throw await this.sectionItemService.saveOne(a.data),i.section_item=a.data,new C(a.error);return i}async checkInvoice(e,t,n){t.status=D.PAYMENT,this.addEmployeeToInvoice(e,n);let r=await this.createReceiptPrintJob(e,I.CheckPrinter),i=await this.createLabelPrintJobs(e),a=await this.createKitchenPrintJobs(e),o=await this.createOrderPrintJobs(e),s=[...i,...a,...o];r&&s.push(r);let c=this.sortPrintJobsByPrinterSequence(s);e.kitchen_print_job_uids||(e.kitchen_print_job_uids=[]),e.label_print_job_uids||(e.label_print_job_uids=[]);let l=e.kitchen_print_job_uids.length,u=e.label_print_job_uids.length,d=a.map(e=>e.uid),f=i.map(e=>e.uid);d.length>0&&e.kitchen_print_job_uids.push(d),f.length>0&&e.label_print_job_uids.push(f),await this.preprocessInvoice(e);let p={invoice:e,section_item:t};c.length>0&&(p.print_jobs=c);try{let e=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/check_invoice`,p);if(e.error==w.outdatedInvoice)throw await this.saveOne(e.data),p.invoice=e.data,new C(e.error);if(e.error==w.outdatedSectionItem)throw await this.sectionItemService.saveOne(e.data),p.section_item=e.data,new C(e.error);return p}catch(t){throw e.kitchen_print_job_uids.length=l,e.label_print_job_uids.length=u,t}}async switchInvoice(e,t,n,r){if(t.uid==n.uid)throw new C(`source and target table can not be the same`);if(t.status!=D.CLOSED)throw new C(`target table is occupied`);if(e.lines==null||e.lines.length<=0)throw new C(`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=D.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==w.outdatedInvoice)throw await this.saveOne(a.data),i.invoice=a.data,new C(a.error);if(a.error==w.outdatedSourceSectionItem)throw await this.sectionItemService.saveOne(a.data),i.source_section_item=a.data,new C(a.error);if(a.error==w.outdatedTargetSectionItem)throw await this.sectionItemService.saveOne(a.data),i.target_section_item=a.data,new C(a.error);return i}async payInvoice(e,t,n,r){e.status=V.Paid,t.invoice_uid=``,t.status=D.CLOSED,this.sectionItemService.reset(t),this.addEmployeeToInvoice(e,r),e.paid_at=new Date;let i=(await this.configService.getDefaultOne()).config,a=i?.order?.datetime_format;e.humanized_paid_at=F(e.paid_at,a),e.payment_has_cash=e.payments?.some(e=>e.payment_method?.is_cash===!0);let o=await this.getStockChangeList(e,!1),s=await this.createLabelPrintJobs(e),c=await this.createReceiptPrintJob(e,I.ReceiptPrinter),l=await this.createKitchenPrintJobs(e),u=await this.createCancelKitchenPrintJobs(e,e.deleted_lines),d=await this.createOrderPrintJobs(e),f=[...s,...l,...u,...d];c&&f.push(c);let p=this.sortPrintJobsByPrinterSequence(f);e.kitchen_print_job_uids||(e.kitchen_print_job_uids=[]),e.label_print_job_uids||(e.label_print_job_uids=[]);let m=e.kitchen_print_job_uids.length,ee=e.label_print_job_uids.length,h=l.map(e=>e.uid),g=s.map(e=>e.uid);h.length>0&&e.kitchen_print_job_uids.push(h),g.length>0&&e.label_print_job_uids.push(g),await this.preprocessInvoice(e);let _={invoice:e,section_item:t,till:n};p.length>0&&(_.print_jobs=p);try{let t=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/pay_invoice`,_);if(t.error==w.outdatedInvoice)throw await this.saveOne(t.data),_.invoice=t.data,new C(`${t.error}, system has updated the data and please try again`);if(t.error==w.outdatedSectionItem)throw await this.sectionItemService.saveOne(t.data),_.section_item=t.data,new C(`${t.error}, system has updated the data and please try again`);if(o.length>0&&await this.itemService.changeItemsStock(o),e.call_num&&i?.ods?.enabled){let t=new Dr;t.order_number=e.call_num,await this.orderDisplayService.addOne(t)}return _}catch(t){throw e.kitchen_print_job_uids.length=m,e.label_print_job_uids.length=ee,t}}async directPayInvoice(e,t,n,r,i,a=!1){e.status=V.Paid,n!=null&&this.addEmployeeToInvoice(e,n),e.paid_at=new Date;let o=(await this.configService.getDefaultOne()).config,s=o?.order?.datetime_format;e.humanized_paid_at=F(e.paid_at,s),e.created_at=new Date,e.created_at_timestamp=e.created_at.getTime(),e.humanized_created_at=F(e.created_at,s),e.ref_id||(e.ref_id=await this.getRefId()),e.call_num||(e.call_num=e.ref_id.slice(-3)),e.payment_has_cash=e.payments?.some(e=>e.payment_method?.is_cash===!0);let c=await this.getStockChangeList(e,!1),l=null,u=null;r&&r.type==I.KioskPrinter?(l=await this.createReceiptPrintJob(e,I.ReceiptPrinter),u=await this.createReceiptPrintJob(e,I.KioskPrinter,!1,0,r,i)):l=await this.createReceiptPrintJob(e,I.ReceiptPrinter,!1,0,r);let d=await this.createLabelPrintJobs(e),f=await this.createKitchenPrintJobs(e,a),p=await this.createOrderPrintJobs(e),m=[...d,...f,...p];l&&m.push(l),u&&m.push(u);let ee=this.sortPrintJobsByPrinterSequence(m),h=f.map(e=>e.uid),g=d.map(e=>e.uid);h.length>0&&(e.kitchen_print_job_uids=[h]),g.length>0&&(e.label_print_job_uids=[g]),await this.preprocessInvoice(e);let _={invoice:e,till:t};ee.length>0&&(_.print_jobs=ee);let v=await this.http.put(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/direct_pay_invoice`,_);if(v.error==w.outdatedInvoice)throw await this.saveOne(v.data),_.invoice=v.data,new C(v.error);if(c.length>0&&await this.itemService.changeItemsStock(c),e.call_num&&o?.ods?.enabled){let t=new Dr;t.order_number=e.call_num,await this.orderDisplayService.addOne(t)}return _}async voidInvoice(e,t,n,r){n&&(e.etc.void_reason=n);let i=e.status;e.status=V.Void,e.voided_at=new Date;let a=(await this.configService.getDefaultOne()).config?.order?.datetime_format;e.humanized_voided_at=F(e.voided_at,a),t&&(t.deleted_at=new Date),this.addEmployeeToInvoice(e,r);let o=(await this.configService.getDefaultOne()).config,s=await this.createReceiptPrintJob(e,I.ReceiptPrinter,!0),c=[];o.kitchen.print_cancel_whole_invoice&&(c=await this.createCancelKitchenPrintJobs(e,e.lines)||[]);let l=[...c];s&&l.push(s);let u={invoice:e,till:t};if(l.length>0&&(u.print_jobs=l),e.table_uid){let t=await this.sectionItemService.getOne(e.table_uid);t.status!=D.CLOSED&&(t.invoice_uid=``,t.status=D.CLOSED,u.section_item=t)}let d=[];i==V.Paid&&(d=await this.getStockChangeList(e));let f=await this.http.post(`api/v5/merchants/${this.options.merchant_uid}/${this.moduleName}/void_invoice`,u);if(f.error==w.outdatedInvoice)throw await this.saveOne(f.data),u.invoice=f.data,new C(f.error);return d.length>0&&await this.itemService.changeItemsStock(d),u}async duplicateInvoice(e,n){if(e.status!=V.Paid)throw new C(`invalid invoice status`);let r=s.cloneDeep(e);if(r.etc.is_duplicate=!0,r.etc.duplicated_from_uid=r.uid,r.uid=S.Invoice+t(),r.status=V.Open,r.ref_id=await this.getRefId(),this.addEmployeeToInvoice(r,n),r.lines)for(let e of r.lines)e.uid=S.InvoiceLine+t();if(r.payments)for(let e of r.payments)e.uid=S.Payment+t();return r}async reprintReceipt(e,n=!1){if(!e?.receipt_print_job_uid)throw new C(`The invoice does not have a receipt`);let r=await this.printJobService.getOne(e.receipt_print_job_uid);if(!r){let t=new p().addParam(`uid`,`EqualTo`,e.receipt_print_job_uid),n=await this.printJobService.autoquery(t);if(!n.results||n.results.length<=0)throw new C(`The invoice does not have a receipt`);r=n.results[0]}let i=await this.printerService.getOne(r.printer_uid);if(i||(i=await this.printerService.getDefaultReceiptPrinter()),!i)throw new C(`Receipt printer not found`);return r=this.printJobService.replacePrinter(r,i),r.uid=S.PrintJob+t(),r.save_only=n,r.status=Qe.Queued,r.print_times=1,r.printed=0,r.retries=0,await this.printJobService.addOne(r),r}async printLastKitchenSlips(e){let n=await this.getOne(e);if(!n)throw new C(`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 C(`No kitchen or label print found`);let o=new p().addParam(`uid`,`In`,a),s=await this.printJobService.autoquery(o);if(!s.results||s.results.length===0)throw new C(`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=S.PrintJob+t(),r.save_only=!1,r.status=Qe.Queued,r.print_times=1,r.printed=0,r.retries=0,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=U.AfterSubtotal,i=`custom`,a={}){if(e.discounts||(e.discounts=[]),t==H.Percent&&n>100)throw new C(`Discount percent can not be more than 100%`);let o=new W;return o.calc_type=t,o.calc_flow=r,o.name=i,o.name_translation=a,t==H.Flat?o.amount=n:o.percent=n,e.discounts.push(o),e}addCouponToInvoice(e,t,n=U.AfterSubtotal){e.discounts||(e.discounts=[]);let r=new W;if(r.calc_type=t.coupon.discount_calc_type==1?H.Flat:H.Percent,r.calc_flow=n,r.name=t.coupon.name,r.calc_type==H.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||s.intersection(r.applying_item_uids,e.lines.map(e=>e.item_uid)).length===0))throw new C(`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 C(`Customer object can not be null`);return e.customer_id=t.id,e.customer=s.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 C(`Source invoice has no nothing to merge`);if(t.lines.some(e=>e.quantity!=e.sent))throw new C(`Please send first before merging`);if(!await this.getOne(e.uid))throw new C(`Target invoice not found`);if(!await this.getOne(t.uid))throw new C(`Source invoice not found`);if(e?.id_in_server==0)throw new C(`Target invoice is not synced to server`);if(t?.id_in_server==0)throw new C(`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!=V.Paid)throw new C(`invalid invoice status`);if(!t||t.length<1)throw new C(`invalid options`);for(let n of t){let t=e.payments.find(e=>e.uid==n.source_payment.uid);if(!t)throw new C(`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=s.cloneDeep(n.target_payment_method),t.payment_method_history=s.cloneDeep(n.target_payment_method),t.payment_method_history.changed_at=new Date}return 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==I.ReceiptPrinter||t==I.CheckPrinter){let n=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,r=t==I.ReceiptPrinter?n?.receipt_printer_uid:n?.check_printer_uid;r&&(o=await this.printerService.getOne(r)),o||(o=t==I.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 C(`Print template not found`);t==I.ReceiptPrinter&&!s.config?.receipt?.enabled&&(n=!0);let l=await this.printTemplateService.renderPrintTemplate(e,s.config,c,{...new z,printer_name:o.name}),u=new R(o,l,n,r);return t!=I.ReceiptPrinter&&(u.printer_type=t),o.connection_type!=Xe.ETHERNET&&(u.connection_type=o.connection_type),t==I.ReceiptPrinter&&(e.receipt_print_job_uid=u.uid),a&&(u.device_uid_to_print=a),u}sortLinesByItemSequence(e){return s.chain(e||[]).groupBy(e=>e.is_combo_item?e.combo_line_uid:e.uid).map(e=>s.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()}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,I.KitchenPrinter),o=await this.printerService.getPrintersByUids(a);for(let t of o){let a=await this.printTemplateService.getOneByParams({uid:t.print_template_uid});if(!a)continue;let o=i.filter(e=>e.item.kitchen_printers_uids.includes(t.uid)),c=this.sortLinesByItemSequence(o),l=s.cloneDeep(e);if(t.kitchen_itemized_print)for(let e of c){l.lines=[e];let i=new R(t,await this.printTemplateService.renderPrintTemplate(l,n,a,{...new z,printer_name:t.name}),!1,t.print_times);r.push(i)}else{l.lines=c;let e=new R(t,await this.printTemplateService.renderPrintTemplate(l,n,a,{...new z,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,I.OrderPrinter),a=e.table_uid?await this.sectionItemService.getOne(e.table_uid):null,o=await this.printerService.getPrintersByUids(i);for(let i of o){if(a?.order_printer_uids?.length>0&&!a.order_printer_uids.includes(i.uid))continue;let o=await this.printTemplateService.getOneByParams({uid:i.print_template_uid});if(!o)continue;let c=r.filter(e=>e.item.order_printers_uids.includes(i.uid)),l=this.sortLinesByItemSequence(c),u=s.cloneDeep(e);u.lines=l;let d=new R(i,await this.printTemplateService.renderPrintTemplate(u,t,o,{...new z,printer_name:i.name}),!1,i.print_times);n.push(d)}return n}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,I.LabelPrinter);if(i.length==0||r.length==0)return[];let a=await this.printerService.getPrintersByUids(i),o=s.cloneDeep(e),c=r.length,l=1;for(let e of r){if(e.meta.total_index=c,e.meta.index=l,e.modifiers?.length&&e.item.modifiers?.length){let t=new Map(e.item.modifiers.map(e=>[e.uid,e.sequence??0]));e.modifiers.sort((e,n)=>(t.get(e.item_uid)??0)-(t.get(n.item_uid)??0))}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=f.compile(r.commands);o.lines=[i];let s=a({invoice:o,config:t}),c=new R(e,new P,!1,e.print_times);c.commands=s,n.push(c)}return n}filterLinesAndPrintersToPrint(e,t){let n;switch(t){case I.KitchenPrinter:n=`kitchen_printers_uids`;break;case I.OrderPrinter:n=`order_printers_uids`;break;case I.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=s.cloneDeep(a);if(e.quantity-=e.sent,t==I.LabelPrinter)for(let t=0;t<e.quantity;t++){let t=s.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=s.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)return[];let{lines:r,printerUids:i}=this.filterDeletedLinesForCancelPrint(t);if(r.length===0)return[];let a=await this.printerService.getPrintersByUids(i),o=[];for(let t of a){let i=await this.printTemplateService.getOneByParams({uid:t.print_template_uid});if(!i)continue;let a=r.filter(e=>e.item.kitchen_printers_uids.includes(t.uid)),c=this.sortLinesByItemSequence(a),l=s.cloneDeep(e);if(t.kitchen_itemized_print)for(let e of c){l.lines=[e];let r=new R(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);o.push(r)}else{l.lines=c;let e=new R(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);o.push(e)}}for(let t of e.deleted_lines)t.is_cancel_printed=!0;return o}sortPrintJobsByPrinterSequence(e){return e.sort((e,t)=>(e?.print_sequence??999)-(t?.print_sequence??999))}async preprocessInvoice(e){if(e.lines)for(let t of e.lines)t.sent=t.quantity;return e}addInvoiceCharge(e,t,n,r,i=U.AfterSubtotal){e.charges||(e.charges=[]);let a=new gt;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 getStockChangeList(e,t=!0){if(!e.lines||e.lines.length===0)return[];let n=t?1:-1,r=new Map;for(let t of e.lines){let e=r.get(t.item_uid)||new xe(t.item_uid);if(e.quantity+=t.quantity*n,t.modifiers&&t.modifiers.length>0)for(let r of t.modifiers){let i=e.modifiers.find(e=>e.item_uid===r.item_uid);i||(i={item_uid:r.item_uid,quantity:0},e.modifiers.push(i)),i.quantity+=t.quantity*r.quantity*n}r.set(t.item_uid,e)}return Array.from(r.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=s.cloneDeep(e),i=s.cloneDeep(n);i.quantity=1,r.lines=[i],t.push(r)}return t}},Nr=class extends Mr{},Pr=class extends G{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}},Fr=class extends G{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 m.compare(t,n.password))return!0;throw new C(`Password is incorrect`)}else throw new C(`User not found`)}catch(e){throw e instanceof C?e:new C(`Unexpected error, login failed`)}}async createEmployee(e){try{if(await this.getOne(e.uid))throw new C(`User already exists`);return e.password&&(e.password=await m.hash(e.password,12)),this.addOne(e)}catch(e){throw e instanceof C?e:new C(`Unexpected error, creating employee failed`)}}async changePassword(e){try{return await m.hash(e,12)}catch{throw new C(`Unexpected error, changing password failed`)}}},Ir=class extends G{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),async()=>await this.db.table(this.moduleName).where(`name`).anyOfIgnoreCase(e).or(`codename`).anyOfIgnoreCase(e).or(`barcode`).anyOfIgnoreCase(e).toArray())}async addModifierCategory(e,n){return n.uid=S.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 C(`Item does not have any modifier categories`);let n=e.modifier_categories.findIndex(e=>e.uid===t.uid);if(n===-1)throw new C(`Modifier category not found`);return e.modifier_categories[n]=t,e}async removeModifierCategory(e,t){if(!e.modifier_categories)throw e.modifier_categories=[],new C(`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=S.ItemModifier+t(),e.modifiers.push(n),e}async updateModifier(e,t){if(!e.modifiers)throw e.modifiers=[],new C(`Item does not have any modifiers`);let n=e.modifiers.findIndex(e=>e.uid===t.uid);if(n===-1)throw new C(`Modifier not found`);return e.modifiers[n]=t,e}async removeModifier(e,t){if(!e.modifiers)throw e.modifiers=[],new C(`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 C(`Item does not have any modifier categories`);if(!e.modifier_categories.find(e=>e.uid===n))throw new C(`Modifier category not found`);let r=e.modifiers.find(e=>e.uid===t);if(!r)throw new C(`Modifier not found`);return r.category_uid=n,e}async addImageAsync(e,t){let n=o(),r=this.getFileExtension(e);await this.http.post(`api/v5/merchants/`+this.options.merchant_uid+`/upload-image`,new tn({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 C(`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 C(`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 C(`Item not found`);let r=Number(n.stock);return n.stock=(isNaN(r)?0:r)+t,this.updateOne(n.id_in_server,n)}async changeItemsStock(e){let t=[];for(let n of e){let e=await this.getOne(n.item_uid);if(!e)continue;let r=Number(e.stock);e.stock=(isNaN(r)?0:r)+n.quantity;for(let t of n.modifiers){let n=e.modifiers?.find(e=>e.uid===t.item_uid);if(!n)continue;let r=Number(n.stock);n.stock=(isNaN(r)?0:r)+Number(t.quantity)}t.push(e)}await this.updateMany(t)}convertFileToBase64(e){return new Promise((t,n)=>{let r=new FileReader;r.onloadend=()=>{typeof r.result==`string`?t(r.result.split(`,`)[1]):n(Error(`Could not convert file to Base64.`))},r.onerror=()=>n(Error(`File reading failed.`)),r.readAsDataURL(e)})}getFileExtension(e){let t=e.name,n=t.lastIndexOf(`.`);return n===-1||n===t.length-1?``:t.slice(n+1)}async cloneItem(e){let n=s.cloneDeep(e);if(n.uid=S.Item+t(),n.id_in_server=0,!n.modifier_categories||n.modifier_categories.length===0)return n;let r=[],i=[];for(let e of n.modifier_categories){let t=n.modifiers?.filter(t=>t.category_uid===e.uid);if(!t||t.length===0)continue;let{modifierCategory:a,modifiers:o}=await this.cloneModifiers(e,t);r.push(a),i.push(...o)}return n.modifier_categories=r,n.modifiers=i,n}async cloneModifiers(e,n){let r=s.cloneDeep(e);r.uid=S.ItemModifierCategory+t();let i=[];for(let e of n){let n=s.cloneDeep(e);n.uid=S.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 C(`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.type!==k.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}},Lr=class extends G{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 C(`Category does not have any subcategories`);let n=e.subcategories.findIndex(e=>e.uid===t.uid);if(n===-1)throw new C(`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 C(`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}},Rr=class extends G{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 It,product:()=>new Ft,till:()=>new Lt,report:()=>new Rt,receipt:()=>new zt,kitchen:()=>new Bt,kds:()=>new Vt,label:()=>new Ht,order:()=>new Ut,payment:()=>new Gt,user:()=>new Kt,tax:()=>new qt,rounding:()=>new Xt,charges:()=>new Jt,currency:()=>new Yt,inventory:()=>new Zt,pax_config:()=>new Qt,gto:()=>new $t,cash_drawer:()=>new en,marketing:()=>new At})}async updateConfig(e,t){let n=await this.getDefaultOne();n||(n=new Ct);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 Ct);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=o(),n=Tn(e);return await this.http.post(`api/v5/merchants/`+this.options.merchant_uid+`/upload-image`,new tn({base64:await En(e),name:t,extension:n})),{file_url:`${this.options.base_url}images/${t}.${n}`,thumbnail_url:`${this.options.base_url}images/${t}.thumbnail.${n}`}}},zr=class extends G{constructor(e,t,n,r=`sections`,i=`section`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Br=class extends G{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||``}}},Vr=class extends G{constructor(e,t,n,r=`products`,i=`product`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Hr=class extends G{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 X(e,t,n)}async cashIn(e,t){let n=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status===T.Open).first();if(!n)throw new C(`No opening shift found`);let r=new _e;return r.amount=e,r.type=E.CashIn,r.user_uid=n.user_uid,r.shift_uid=n.uid,r.note=t,this.tillService.addOne(r)}async cashOut(e,t){let n=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status===T.Open).first();if(!n)throw new C(`No opening shift found`);let r=new _e;return r.amount=e,r.type=E.CashOut,r.user_uid=n.user_uid,r.shift_uid=n.uid,r.note=t,this.tillService.addOne(r)}async closeShift(e,t){let n=await this.db.table(this.moduleName).filter(e=>(e.deleted_at===null||e.deleted_at===void 0)&&e.status==T.Open).first();if(!n)throw new C(`No opening shift found`);return n.declared_amount=e,n.ended_at=new Date,n.user_uid=t,n.status=T.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==T.Open).first();if(r)throw new C(`shift is already opened shift at ${r.started_at}`);let i=new ge;if(i.started_at=new Date,i.user_uid=t,i.status=T.Open,await this.addOne(i),e>0){let r=new _e;r.amount=e,r.type=E.OpenDeposit,r.user_uid=t,r.amount=e,r.shift_uid=i.uid,r.note=n,await this.tillService.addOne(r)}return console.log(`open shift end`),i}},X=class extends G{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 _e;return a.shift_uid=t,a.user_uid=n,a.note=r,a.invoice_uid=i,a.amount=K(e.filter(e=>e.payment_method.is_cash).map(e=>e.tender_amount-e.change_amount).reduce((e,t)=>e+t,0)),a.type=E.CashInvoice,a}},Ur=class extends G{constructor(e,t,n,r=`payment_methods`,i=`payment_method`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}async syncStandardPaymentMethods(){try{let{data:e}=await this.http.get(`api/v5/merchants/`+this.options.merchant_uid+`/standard_payment_methods`),t=[];for(let n of e){let e=new at(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}},Wr=class extends G{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 nt;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=K(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=s.cloneDeep(n),e.payments.push(r),e}async removePayment(e,t){return e.payments=e.payments.filter(e=>e.uid!==t),e}},Gr=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 C(`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 C(`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}},Kr=class extends G{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 Nr(e,t,n,`invoices`,`invoice`),this.tillService=new X(e,t,n,`tills`,`till`),this.paymentService=new Wr(e,t,n,`payments`,`payment`),this.printerService=new wn(e,t,n,`printers`,`printer`),this.printTemplateService=new Yr(e,t,n,`print_templates`,`print_template`),this.printJobService=new qr(e,t,n,`print_jobs`,`print_job`),this.configService=new Rr(e,t,n,`configs`,`config`)}async syncStandardReports(){let e=await this.getDefaultOne();e||(e=new hn);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 C(`No default receipt printer found`);let n=await this.printTemplateService.getOneByParams({report_code_name:e.report_code_name});if(!n)throw new C(`No print template found`);let r=await this.configService.getDefaultOne(),i=await this.getReportData(e,r.config?.order?.datetime_format),a=new R(t,await this.printTemplateService.renderReportPrintTemplate(i,r.config,n),!1,e.copies);await this.printJobService.addOne(a)}async getReportData(e,t){let n=new gn;if(e.shift_uid){await this.db.table(`shifts`).where(`uid`).equals(e.shift_uid).and(e=>e.deleted_at==null||e.deleted_at==null).first(),n.drawer_summary.declared_amount=e.declared_amount;let t=await this.db.table(`tills`).where(`shift_uid`).equals(e.shift_uid).and(e=>e.deleted_at==null).toArray();n.drawer_summary.open_amount=K(t.filter(e=>e.type==E.OpenDeposit).reduce((e,t)=>e+t.amount,0)),n.drawer_summary.pay_in_total=K(t.filter(e=>e.type==E.CashIn).reduce((e,t)=>e+t.amount,0)),n.drawer_summary.cash_invoice_total=K(t.filter(e=>e.type==E.CashInvoice).reduce((e,t)=>e+t.amount,0)),n.drawer_summary.cash_invoice_count=t.filter(e=>e.type==E.CashInvoice).length,n.drawer_summary.pay_in_count=t.filter(e=>e.type==E.CashIn).length,n.drawer_summary.pay_out_total=K(t.filter(e=>e.type==E.CashOut).reduce((e,t)=>e+t.amount,0)),n.drawer_summary.pay_out_count=t.filter(e=>e.type==E.CashOut).length,n.drawer_summary.drawer_amount=K(n.drawer_summary.open_amount+n.drawer_summary.pay_in_total+n.drawer_summary.cash_invoice_total-n.drawer_summary.pay_out_total),n.drawer_summary.difference=K(n.drawer_summary.drawer_amount-n.drawer_summary.declared_amount)}n.start_datetime=new Date(e.start_datetime).toISOString(),n.end_datetime=new Date(e.end_datetime).toISOString(),n.humanized_start_datetime=F(new Date(e.start_datetime),t),n.humanized_end_datetime=F(new Date(e.end_datetime),t),n.humanized_printed_datetime=F(new Date,t);let r=new p().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),i=(await this.invoiceService.autoQuery(r,{timeout:6e5})).results||[];return this.processReportInvoicesData(n,i)}async processReportInvoicesData(e,t=[]){let n=new Map,r=new Map,i=await this.db.table(`categories`).toArray(),a=new Map(i.map(e=>[e.uid,e]));t.forEach(t=>{t.status==V.Paid&&(e.sales_summary.paid_invoice_total+=t.grand_total,e.sales_summary.sales_total+=t.grand_total,e.sales_summary.paid_invoice_count++,e.sales_summary.rounding_total+=t.rounding,e.sales_summary.tax_total+=t.tax,e.sales_summary.service_charge_total+=t.service_charge,e.sales_summary.discount_total+=t.discount_amount,t.add_credit>0&&(e.loyalty_program_summary.add_credit_total+=t.add_credit,e.loyalty_program_summary.add_credit_count++,e.loyalty_program_summary.topup_paid_count++),t.rewarded_credit>0&&(e.loyalty_program_summary.rewarded_credit_total+=t.rewarded_credit,e.loyalty_program_summary.rewarded_credit_count++),t.minus_credit>0&&(e.loyalty_program_summary.minus_credit_total+=t.minus_credit,e.loyalty_program_summary.minus_credit_count++),t.rewarded_point>0&&(e.loyalty_program_summary.rewarded_point_total+=t.rewarded_point,e.loyalty_program_summary.rewarded_point_count++),t.minus_point>0&&(e.loyalty_program_summary.minus_point_total+=t.minus_point,e.loyalty_program_summary.minus_point_count++),e.sales_summary.total_pax+=t.pax,t.pax>0&&(e.sales_summary.pax_sales_total+=t.grand_total),t.lines.forEach(t=>{t.item.add_credit>0&&(e.loyalty_program_summary.topup_paid_total+=t.subtotal);let i=this.generateItemKey(t),a=n.get(i);a?(a.quantity+=t.quantity,a.total_amount=K(a.total_amount+t.subtotal),t.modifiers&&t.modifiers.length>0&&t.modifiers.forEach(e=>{let t=e.item.name.trim(),n=r.get(t);n?(n.quantity+=e.quantity,n.total_amount=K(n.total_amount+e.price*e.quantity)):(n=new Sn,n.item=e.item,n.quantity=e.quantity,n.total_amount=K(e.price*e.quantity),r.set(t,n))})):(a=new xn,a.item=t.item,a.quantity=t.quantity,a.total_amount=K(t.subtotal),a.modifiers=[],t.modifiers&&t.modifiers.length>0&&t.modifiers.forEach(e=>{let t={item:e.item,quantity:e.quantity,total_amount:K(e.price*e.quantity)};a.modifiers.push(t);let n=e.item.name.trim(),i=r.get(n);i?(i.quantity+=e.quantity,i.total_amount=K(i.total_amount+e.price*e.quantity)):(i=new Sn,i.item=e.item,i.quantity=e.quantity,i.total_amount=K(e.price*e.quantity),r.set(n,i))}),n.set(i,a))}),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=K(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:K(t.tender_amount-t.change_amount)})})),t.is_sales_exclusive&&(e.sales_summary.foc_sales_total+=t.grand_total,e.sales_summary.foc_sales_count++),t.status==V.Void&&(e.sales_summary.void_invoice_total+=t.grand_total,e.sales_summary.void_invoice_count++)});let o=Array.from(n.values());o.sort((e,t)=>{let n=a.get(e.item.category_uid),r=a.get(t.item.category_uid),i=n?.sequence??999999,o=r?.sequence??999999;return i===o?(e.item.sequence??999999)-(t.item.sequence??999999):i-o}),e.item_sales_summary=o;let s=0,c=0,l=new Map;o.forEach(e=>{if(s+=e.total_amount,c+=e.quantity,!e.item.category_uid)return;let t=e.item.category_uid,n=l.get(t);n||(n=new Cn,n.category=a.get(e.item.category_uid)||null,l.set(t,n)),n.items.push(e),n.total_quantity+=e.quantity,n.total_amount+=e.total_amount}),e.item_sales_summary_total=K(s),e.item_sales_summary_total_count=c;let u=Array.from(l.values());u.sort((e,t)=>(e.category?.sequence??999999)-(t.category?.sequence??999999)),u.forEach(e=>{e.total_amount=K(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=u;let d=Array.from(r.values());d.sort((e,t)=>t.quantity===e.quantity?t.total_amount-e.total_amount:t.quantity-e.quantity),e.modifier_sales_summary=d;let f=0,p=0;return e.modifier_sales_summary.forEach(e=>{f+=e.total_amount,p+=e.quantity}),e.modifier_sales_summary_total=K(f),e.modifier_sales_summary_total_count=p,e.sales_summary.paid_invoice_total=K(e.sales_summary.paid_invoice_total),e.sales_summary.sales_total=K(e.sales_summary.sales_total),e.sales_summary.rounding_total=K(e.sales_summary.rounding_total),e.sales_summary.tax_total=K(e.sales_summary.tax_total),e.sales_summary.service_charge_total=K(e.sales_summary.service_charge_total),e.sales_summary.discount_total=K(e.sales_summary.discount_total),e.sales_summary.foc_sales_total=K(e.sales_summary.foc_sales_total),e.sales_summary.void_invoice_total=K(e.sales_summary.void_invoice_total),e.sales_summary.pax_sales_total=K(e.sales_summary.pax_sales_total),e.loyalty_program_summary.add_credit_total=K(e.loyalty_program_summary.add_credit_total),e.loyalty_program_summary.topup_paid_total=K(e.loyalty_program_summary.topup_paid_total),e.loyalty_program_summary.rewarded_credit_total=K(e.loyalty_program_summary.rewarded_credit_total),e.loyalty_program_summary.minus_credit_total=K(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}},qr=class extends G{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,e}},Jr=class extends G{constructor(e,t,n,r=`menus`,i=`menu`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Yr=class extends G{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=c.create({baseURL:`https://revopos-cdn.sgp1.digitaloceanspaces.com`,timeout:3e3})}async initialize(){if(!await this.getOneByParams({printer_type:I.ReceiptPrinter})){let e=new L;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=I.ReceiptPrinter,await this.addOne(e),console.log(`Default Receipt Template added`)}if(!await this.getOneByParams({printer_type:I.CheckPrinter})){let e=new L;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=I.CheckPrinter,await this.addOne(e),console.log(`Default Check Template added`)}if(!await this.getOneByParams({printer_type:I.OrderPrinter})){let e=new L;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=I.OrderPrinter,await this.addOne(e),console.log(`Default Order Template added`)}if(!await this.getOneByParams({printer_type:I.KitchenPrinter})){let e=new L;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=I.KitchenPrinter,await this.addOne(e),console.log(`Default Kitchen Template added`)}if(!await this.getOneByParams({printer_type:I.KioskPrinter})){let e=new L;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=I.KioskPrinter,await this.addOne(e),console.log(`Default Kiosk Template added`)}if(!await this.getOneByParams({printer_type:I.LabelPrinter})){let e=new L;e.commands=await this.getPrintTemplate(`tspl_cmds`),e.name=`Default Label Template`,e.printer_type=I.LabelPrinter,await this.addOne(e)}if(!await this.getOneByParams({printer_type:I.QrCodePrinter})){let e=new L;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=I.QrCodePrinter,await this.addOne(e)}if(!await this.getOneByParams({report_code_name:`sales_summary_report`})){let e=new L;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 L;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 L;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 L;e.name=`Modifier Sales Report`,e.body=await this.getPrintTemplate(`msrbt`),e.header=await this.getPrintTemplate(`msrht`),e.footer=await this.getPrintTemplate(`msrft`),e.report_code_name=`modifier_sales_report`,await this.addOne(e),console.log(`Modifier Sales Report Template added`)}}async renderPrintTemplate(e,t,n,r=new z){let i=new P;n.printer_type==I.KitchenPrinter||n.printer_type==I.OrderPrinter?i.codepage=n.codepage||this.getCodepageByCountryCode(t.kitchen.language):i.codepage=n.codepage||this.getCodepageByCountryCode(t.receipt.language);let a=new tt;return a.invoice=e,a.config=t,a.normalized_printed_at=F(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 z){let i=new P,a=new tt;return a.report_data=e,a.config=t,a.normalized_printed_at=F(a.printed_at,t?.order?.datetime_format),i.codepage=n.codepage||M.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 z){let r=new P;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 l.AES.decrypt(t.data,this.secretKey).toString(l.enc.Utf8)}getCodepageByCountryCode(e){let t={US:M.English,GR:M.Greek,DE:M.WesternEurope,LT:M.BalticRim,PL:M.CentralEurope,RU:M.Cyrillic,TR:M.Turkish,EU:M.MultilingualLatin1WithEuro,PT:M.Portuguese,IS:M.Icelandic,IL:M.Hebrew,CA:M.FrenchCanadian,EG:M.Arabic,NO:M.Nordic,BY:M.Russian,MK:M.ModernGreek,CN:M.SimplifiedChinese,KR:M.Korean,TW:M.TraditionalChinese,FR:M.WesternEuropeanLatin,AE:M.ArabicISO,JP:M.Japanese,CZ:M.CentralEuropeanLatinWindows,BG:M.CyrillicWindows,ES:M.WesternEuropeanLatinWindows,CY:M.GreekWindows,AZ:M.TurkishWindows,PS:M.HebrewWindows,SA:M.ArabicWindows,LV:M.BalticWindows,VN:M.Vietnamese};return e&&t[e.toUpperCase()]||t.CN}async renderPrintCommand(e,t){try{let n=new u,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=s.flatMap(i,e=>e),i=s.compact(i),i}catch(e){throw console.error(e),e}}},Xr=class extends G{constructor(e,t,n,r=`storages`,i=`storage`){super(),this.http=e,this.db=t,this.options=n,this.moduleName=r,this.methodName=i}},Zr=class extends G{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}};function Qr(e,t,n){let r=c.create({baseURL:e,timeout:2e4,headers:{"x-device-uid":t,Authorization:`Bearer ${n}`}});return r.interceptors.response.use(function(e){return e.data},function(e){return Promise.reject(e)}),r}const $r=new Map([[`Item`,Ir],[`Section`,zr],[`SectionItem`,Br],[`Category`,Lr],[`Config`,Rr],[`Shift`,Hr],[`Till`,X],[`Employee`,Fr],[`PaymentMethod`,Ur],[`Invoice`,Nr],[`Report`,Kr],[`Printer`,wn],[`PrintJob`,qr],[`PrintTemplate`,Yr],[`EmployeeRole`,Pr],[`OrderDisplay`,Or],[`Storage`,Xr],[`Menu`,Jr],[`StockLog`,Zr]]),Z=`uid, updated_at, created_at, deleted_at, _timestamp, id_in_server, created_at_timestamp`,Q=`${Z}, sequence`,ei=`${Q}, status`,ti=`${Z}, till_type, shift_uid, invoice_uid`,ni=`${Q}, payment_method_code, is_disabled`,ri=`${Z}, type, status, table_uid`,ii=`${Q}, name, barcode, codename`,ai=`${Z}, status, printer_type, connection_type, protocol, save_only, device_uid_to_print`,oi=`${Z}, name, printer_type`,si=`${Z}, order_number, status`,ci=`${Z}, model`,li={items:ii,sections:Q,section_items:Q,categories:Q,shifts:ei,tills:ti,employees:`${Z}, role_uid`,payment_methods:ni,invoices:ri,configs:Z,reports:Z,printers:Z,print_jobs:ai,print_templates:oi,employee_roles:`${Z}, name, is_default`,order_displays:si,storages:ci,menus:Z,stock_logs:`${Z}, entity_type, entity_uid, type`};var $=function(e){return e.DISCONNECTED=`disconnected`,e.CONNECTED=`connected`,e.ERROR=`error`,e}($||{}),ui=class e{constructor(e,t,n=!1){this.options=e,this.win=t,v(this,`mode`,void 0),v(this,`http`,void 0),v(this,`dataSource`,void 0),v(this,`status`,$.DISCONNECTED),this.mode=e.mode,this.http=Qr(e.base_url,e.device_uid,e.token),n||this.initializeDatabase(),j.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 i(this.options.database.name),this.dataSource.version(29).stores(li),this.status=$.CONNECTED}catch(e){this.status=$.ERROR,console.error(`Database connection error:`,e)}return this.dataSource}async dropDatabase(){await i.delete(this.options.database.name),await this.initializeDatabase()}clearTableData(e){return this.dataSource.table(e).clear()}async getService(e){if(this.status==$.ERROR)throw Error(`Database connection error`);for(;this.status==$.DISCONNECTED;)await new Promise(e=>setTimeout(e,100));try{return new e(this.http,this.dataSource,this.options)}catch(e){throw Error(`Service instantiation error: `+e?.message)}}async getServiceByName(e){if(this.status==$.ERROR)throw Error(`Database connection error`);for(;this.status==$.DISCONNECTED;)await new Promise(e=>setTimeout(e,100));try{let t=$r.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)}}};function di(e,t,n=`export.csv`){let r=mi(pi(e,t));return new Blob([``+r],{type:`text/csv;charset=utf-8;`})}function fi(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 pi(e,t){let n=[];for(let r of e){n.push({type:`category`,name:r.name,sku:``,price:void 0,stock:void 0,is_internal:r.is_internal,min_order:void 0,max_order:void 0,image_url:r.image_url||``,image_thumbnail_url:r.image_thumbnail_url||``,sequence:r.sequence});let e=t.filter(e=>e.category_uid===r.uid);for(let t of e){let e=t.type===k.Combo;if(n.push({type:e?`combo`:`product`,name:t.name,sku:t.sku||``,price:t.price,stock:fi(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}),e&&t.combo_groups&&t.combo_groups.length>0){for(let e of t.combo_groups)if(n.push({type:`combo_group`,name:e.name,sku:``,price:void 0,stock:void 0,is_internal:void 0,min_order:e.min_order,max_order:e.max_order,image_url:``,image_thumbnail_url:``,sequence:e.sequence}),e.combo_items&&e.combo_items.length>0)for(let t of e.combo_items)n.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(!e&&t.modifier_categories&&t.modifier_categories.length>0){for(let e of t.modifier_categories)if(n.push({type:`modifier_category`,name:e.name,sku:``,price:void 0,stock:void 0,is_internal:void 0,min_order:e.min_order,max_order:e.max_order,image_url:``,image_thumbnail_url:``,sequence:e.sequence}),t.modifiers&&t.modifiers.length>0){let r=t.modifiers.filter(t=>t.category_uid===e.uid);for(let e of r)n.push({type:`modifier`,name:e.name,sku:e.sku||``,price:e.price,stock:fi(e.stock),is_internal:e.is_internal,min_order:void 0,max_order:void 0,image_url:e.image_url||``,image_thumbnail_url:e.image_thumbnail_url||``,sequence:e.sequence})}}}}return n}function mi(e){let t=[[`Type`,`Name`,`SKU`,`Price`,`Stock`,`Is Internal`,`Min Order`,`Max Order`,`Image URL`,`Thumbnail URL`,`Sequence`,`Item UID`].join(`,`)];for(let n of e){let e=[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||``];t.push(e.join(`,`))}return t.join(`
|
|
2
2
|
`)}async function hi(e){return yi(_i(await e.text()))}const gi=[`category`,`product`,`modifier_category`,`modifier`,`combo`,`combo_group`,`combo_item`];function _i(e){let t=e.replace(/^\uFEFF/,``).replace(/\r\n/g,`
|
|
3
3
|
`).replace(/\r/g,`
|
|
4
4
|
`).trim().split(`
|
|
5
|
-
`);if(t.length===0)throw Error(`CSV file is empty`);let n=t[0].trim(),r=`Type,Name,SKU,Price,Stock,Is Internal,Min Order,Max Order,Image URL,Thumbnail URL,Sequence,Item UID`,i=n===`Type,Name,SKU,Price,Stock,Is Internal,Min Order,Max Order,Image URL,Thumbnail URL,Sequence`;if(n!==r&&!i)throw Error(`Invalid CSV header. Expected: ${r}\nReceived: ${n}`);let a=[],o=i?11:12;for(let e=1;e<t.length;e++){let n=t[e].trim();if(!n)continue;let r=vi(n);if(r.length!==o)throw Error(`Invalid CSV row at line ${e+1}: expected ${o} columns`);let[s,c,l,u,d,f,p,m,ee,h,g]=r,_=i?``:r[11];if(!s||!c.trim())throw Error(`Missing required fields at line ${e+1}`);if(!gi.includes(s))throw Error(`Invalid type "${s}" at line ${e+1}. Must be: ${gi.join(`, `)}`);let v;if(u&&u.trim()&&(v=parseFloat(u),isNaN(v)))throw Error(`Invalid price "${u}" at line ${e+1}`);let te;if(d&&d.trim()&&(te=parseFloat(d),isNaN(te)))throw Error(`Invalid stock "${d}" at line ${e+1}`);let y;if(f&&f.trim())if(f.trim()===`true`)y=!0;else if(f.trim()===`false`)y=!1;else throw Error(`Invalid is_internal "${f}" at line ${e+1}. Must be: true or false`);let b;if(p&&p.trim()&&(b=parseInt(p,10),isNaN(b)))throw Error(`Invalid min_order "${p}" at line ${e+1}`);let ne;if(m&&m.trim()&&(ne=parseInt(m,10),isNaN(ne)))throw Error(`Invalid max_order "${m}" at line ${e+1}`);let re;if(g&&g.trim()&&(re=parseInt(g,10),isNaN(re)))throw Error(`Invalid sequence "${g}" at line ${e+1}`);a.push({type:s,name:c.trim(),sku:l?.trim()||``,price:v,stock:te,is_internal:y,min_order:b,max_order:ne,image_url:ee?.trim()||``,image_thumbnail_url:h?.trim()||``,sequence:re,item_uid:_?.trim()||``})}return a}function vi(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 yi(e){let t=[],n=[],r=null,i=null,a=null,o=null,s=0;for(let c of e)if(c.type===`category`)r=new Te,r.name=c.name,r.is_internal=c.is_internal===void 0?!1:c.is_internal,r.sequence=c.sequence===void 0?s++:c.sequence,r.image_url=c.image_url||``,r.image_thumbnail_url=c.image_thumbnail_url||``,r.visibility=[],t.push(r),i=null,a=null,o=null;else if(c.type===`product`||c.type===`combo`){if(!r)throw Error(`${c.type===`combo`?`Combo`:`Product`} "${c.name}" found without a category`);i=new j,i.name=c.name,i.sku=c.sku||``,i.price=c.price||0,i.stock=c.stock===void 0?1e3:c.stock,i.is_internal=c.is_internal===void 0?!1:c.is_internal,i.sequence=c.sequence||0,i.image_url=c.image_url||``,i.image_thumbnail_url=c.image_thumbnail_url||``,i.category_uid=r.uid,i.type=c.type===`combo`?A.Combo:A.ByQuantity,i.modifier_categories=[],i.modifiers=[],i.combo_groups=[],n.push(i),a=null,o=null}else if(c.type===`combo_group`){if(!i||i.type!==A.Combo)throw Error(`Combo group "${c.name}" found without a combo product`);o=new Ae,o.name=c.name,o.min_order=c.min_order===void 0?1:c.min_order,o.max_order=c.max_order===void 0?1:c.max_order,o.sequence=c.sequence===void 0?i.combo_groups.length:c.sequence,i.combo_groups.push(o)}else if(c.type===`combo_item`){if(!o)throw Error(`Combo item "${c.name}" found without a combo group`);let e=new ke;e.item_uid=c.item_uid||``,e.price=c.price||0,e.sequence=c.sequence||0,e.combo_item=new j,e.combo_item.name=c.name,o.combo_items.push(e)}else if(c.type===`modifier_category`){if(!i)throw Error(`Modifier category "${c.name}" found without a product`);a=new we,a.name=c.name,a.min_order=c.min_order===void 0?0:c.min_order,a.max_order=c.max_order===void 0?0:c.max_order,a.sequence=c.sequence===void 0?i.modifier_categories.length:c.sequence,a.visibility=[],i.modifier_categories.push(a)}else if(c.type===`modifier`){if(!i)throw Error(`Modifier "${c.name}" found without a product`);let e=new De;e.name=c.name,e.sku=c.sku||``,e.price=c.price||0,e.stock=c.stock===void 0?0:c.stock,e.is_internal=c.is_internal===void 0?!1:c.is_internal,e.sequence=c.sequence||0,e.image_url=c.image_url||``,e.image_thumbnail_url=c.image_thumbnail_url||``,e.type=A.Modifier,e.category_uid=a?a.uid:i.category_uid,i.modifiers.push(e)}return{categories:t,products:n}}let bi=function(e){return e.None=``,e.Always=`always`,e}({}),xi=function(e){return e.Image=`image`,e.Video=`video`,e.Unsupported=`unsupported`,e}({}),Si=function(e){return e.CdsFullScreenImage=`cds_full_screen_image`,e.CdsHalfScreenImage=`cds_half_screen_image`,e}({});var Ci=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)}},wi=class extends S{constructor(...e){super(...e),v(this,`uid`,C.Storage+t()),v(this,`model`,void 0),v(this,`data`,void 0)}},Ti=class extends S{constructor(...e){super(...e),v(this,`uid`,C.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 Ei=function(e){return e.In=`IN`,e.Out=`OUT`,e.Adjust=`ADJUST`,e.Production=`PRODUCTION`,e}({}),Di=function(e){return e.Invoice=`invoice`,e.Purchase=`purchase`,e.Production=`production`,e.Stocktake=`stocktake`,e}({}),Oi=function(e){return e.Item=`item`,e.Material=`material`,e}({});var ki=class extends x{constructor(){super(),v(this,`entity_type`,Oi.Item),v(this,`entity_uid`,``),v(this,`type`,Ei.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`,C.StockLog+t())}};const Ai=[`#each`,`#if`,`#elseif`,`#else`,`#let`,`#merge`,`#concat`,`#include`,`#?`,`#flatten`];function ji(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];Ai.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`)&&Mi(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 Mi(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{te as Address,S as AppBaseModel,Ct as AppConfig,x as AppCoreModel,un as AppCoreService,le as AppExtraModel,dn as AppLocalService,Kr as AppMiscService,G as AppRemoteService,hn as AppReport,qr as AppReportService,ie as Applying,Si as AssetTags,xi as AssetType,on as Between,wt as Cache,W as CalcFlow,U as CalcType,Ot as CardPaymentCode,en as CashDrawerConfig,Te as Category,Cn as CategorySalesSummary,Lr as CategoryService,Ce as CategoryType,_t as Charge,Jt as ChargeConfig,N as Codepages,Ae as ComboGroup,ke as ComboGroupItem,bi as Condition,jt as Config,Rr as ConfigService,we as CoreCategory,De as CoreItem,ae as Coupon,se as CouponItemized,oe as CouponUsage,Tt as CrmConfig,Yt as CurrencyConfig,b as Customer,Dt as CustomerDisplaySystemConfig,Pt as DeployChannel,We as Device,Ke as DeviceType,mt as DiscountType,vn as DrawerSummary,M as ElectronSocket,St as Employee,ye as EmployeeRole,Pr as EmployeeRoleService,Fr as EmployeeService,T as ErrorMsgs,He as EscPosCompatibility,Fe as EscPosPrinter,tn as FileUploadRequest,$t as GTOConfig,It as GeneralConfig,an as In,rn as Include,Zt as InventoryConfig,xt as Invoice,ft as InvoiceAction,gt as InvoiceActivity,Ar as InvoiceBaseService,ht as InvoiceCharge,yt as InvoiceCoreLine,vt as InvoiceDiscount,bt as InvoiceLine,Mr as InvoiceOperationService,Nr as InvoiceService,H as InvoiceStatus,V as InvoiceType,j as Item,xn as ItemSalesSummary,Ir as ItemService,Vt as KdsConfig,kt as KioskSystemConfig,Bt as KitchenConfig,Ht as LabelConfig,jr as LineOperationService,Et as LoyaltyProgram,bn as LoyaltyProgramSummary,At as MarketingConfig,Ti as Menu,Jr as MenuService,Ci as Merchant,pe as MessageType,C as ModelPrefix,ue as ModelType,Sn as ModifierSalesSummary,Ge as Node,qe as NodePrinter,sn as Not,lt as Note,ct as NoteEntity,st as NoteGroup,ot as NoteGroupEntity,Nt as OnlineOrderConfig,Ut as OrderConfig,Dr as OrderDisplay,Or as OrderDisplayService,Y as OrderDisplayStatus,Wt as OrderDisplaySystemConfig,ut as OrderFlow,Qt as PaxConfig,tt as Payment,Gt as PaymentConfig,nt as PaymentMethod,rt as PaymentMethodHistory,Wr as PaymentMethodService,Gr as PaymentService,at as PaymentStatus,yn as PaymentSummary,Mt as PaynowMethod,Oe as Price,Ie as PrintAlign,ze as PrintBarcode,F as PrintCommand,Ve as PrintImage,z as PrintJob,X as PrintJobService,Ze as PrintJobStatus,Be as PrintQrcode,Re as PrintSize,Le as PrintStyle,R as PrintTemplate,Xe as PrintTemplateCore,Yr as PrintTemplateService,P as PrintType,$e as Printer,Ye as PrinterConnections,Je as PrinterProtocols,wn as PrinterService,Qe as PrinterStatus,L as PrinterType,k as ProductBase,Ft as ProductConfig,Vr as ProductService,A as ProductType,me as PushData,cn as Raw,zt as Receipt,B as RenderPrintTemplateOptions,mn as Report,pn as ReportCategory,Rt as ReportConfig,gn as ReportData,fn as ReportType,Xt as RoundingConfig,_n as SalesSummary,ve as Section,_e as SectionItem,Br as SectionItemService,O as SectionItemStatus,zr as SectionService,ui as ServiceFactory,de as ServiceMode,fe as ServiceOptions,he as Shift,Hr as ShiftService,E as ShiftStatus,it as StandardPaymentMethod,be as StockChange,ki as StockLog,Oi as StockLogEntityType,Di as StockLogRefType,Zr as StockLogService,Ei as StockLogType,wi as Storage,Xr as StorageService,Ee as Subcategory,Se as System,w as SystemError,qt as TaxConfig,dt as TaxMethod,et as TemplateData,ge as Till,Lt as TillConfig,Ur as TillService,D as TillType,pt as UomType,y as User,Kt as UserConfig,xe as Visibility,di as createCSVExport,li as dbSchemas,ln as filterByParams,I as humanizedData,hi as importFromCSV,Ue as normalizedDate,ce as transformer,ji as validateSTTemplate};
|
|
5
|
+
`);if(t.length===0)throw Error(`CSV file is empty`);let n=t[0].trim(),r=`Type,Name,SKU,Price,Stock,Is Internal,Min Order,Max Order,Image URL,Thumbnail URL,Sequence,Item UID`,i=n===`Type,Name,SKU,Price,Stock,Is Internal,Min Order,Max Order,Image URL,Thumbnail URL,Sequence`;if(n!==r&&!i)throw Error(`Invalid CSV header. Expected: ${r}\nReceived: ${n}`);let a=[],o=i?11:12;for(let e=1;e<t.length;e++){let n=t[e].trim();if(!n)continue;let r=vi(n);if(r.length!==o)throw Error(`Invalid CSV row at line ${e+1}: expected ${o} columns`);let[s,c,l,u,d,f,p,m,ee,h,g]=r,_=i?``:r[11];if(!s||!c.trim())throw Error(`Missing required fields at line ${e+1}`);if(!gi.includes(s))throw Error(`Invalid type "${s}" at line ${e+1}. Must be: ${gi.join(`, `)}`);let v;if(u&&u.trim()&&(v=parseFloat(u),isNaN(v)))throw Error(`Invalid price "${u}" at line ${e+1}`);let te;if(d&&d.trim()&&(te=parseFloat(d),isNaN(te)))throw Error(`Invalid stock "${d}" at line ${e+1}`);let y;if(f&&f.trim())if(f.trim()===`true`)y=!0;else if(f.trim()===`false`)y=!1;else throw Error(`Invalid is_internal "${f}" at line ${e+1}. Must be: true or false`);let ne;if(p&&p.trim()&&(ne=parseInt(p,10),isNaN(ne)))throw Error(`Invalid min_order "${p}" at line ${e+1}`);let re;if(m&&m.trim()&&(re=parseInt(m,10),isNaN(re)))throw Error(`Invalid max_order "${m}" at line ${e+1}`);let ie;if(g&&g.trim()&&(ie=parseInt(g,10),isNaN(ie)))throw Error(`Invalid sequence "${g}" at line ${e+1}`);a.push({type:s,name:c.trim(),sku:l?.trim()||``,price:v,stock:te,is_internal:y,min_order:ne,max_order:re,image_url:ee?.trim()||``,image_thumbnail_url:h?.trim()||``,sequence:ie,item_uid:_?.trim()||``})}return a}function vi(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 yi(e){let t=[],n=[],r=null,i=null,a=null,o=null,s=0;for(let c of e)if(c.type===`category`)r=new Ee,r.name=c.name,r.is_internal=c.is_internal===void 0?!1:c.is_internal,r.sequence=c.sequence===void 0?s++:c.sequence,r.image_url=c.image_url||``,r.image_thumbnail_url=c.image_thumbnail_url||``,r.visibility=[],t.push(r),i=null,a=null,o=null;else if(c.type===`product`||c.type===`combo`){if(!r)throw Error(`${c.type===`combo`?`Combo`:`Product`} "${c.name}" found without a category`);i=new A,i.name=c.name,i.sku=c.sku||``,i.price=c.price||0,i.stock=c.stock===void 0?1e3:c.stock,i.is_internal=c.is_internal===void 0?!1:c.is_internal,i.sequence=c.sequence||0,i.image_url=c.image_url||``,i.image_thumbnail_url=c.image_thumbnail_url||``,i.category_uid=r.uid,i.type=c.type===`combo`?k.Combo:k.ByQuantity,i.modifier_categories=[],i.modifiers=[],i.combo_groups=[],n.push(i),a=null,o=null}else if(c.type===`combo_group`){if(!i||i.type!==k.Combo)throw Error(`Combo group "${c.name}" found without a combo product`);o=new je,o.name=c.name,o.min_order=c.min_order===void 0?1:c.min_order,o.max_order=c.max_order===void 0?1:c.max_order,o.sequence=c.sequence===void 0?i.combo_groups.length:c.sequence,i.combo_groups.push(o)}else if(c.type===`combo_item`){if(!o)throw Error(`Combo item "${c.name}" found without a combo group`);let e=new Ae;e.item_uid=c.item_uid||``,e.price=c.price||0,e.sequence=c.sequence||0,e.combo_item=new A,e.combo_item.name=c.name,o.combo_items.push(e)}else if(c.type===`modifier_category`){if(!i)throw Error(`Modifier category "${c.name}" found without a product`);a=new Te,a.name=c.name,a.min_order=c.min_order===void 0?0:c.min_order,a.max_order=c.max_order===void 0?0:c.max_order,a.sequence=c.sequence===void 0?i.modifier_categories.length:c.sequence,a.visibility=[],i.modifier_categories.push(a)}else if(c.type===`modifier`){if(!i)throw Error(`Modifier "${c.name}" found without a product`);let e=new Oe;e.name=c.name,e.sku=c.sku||``,e.price=c.price||0,e.stock=c.stock===void 0?0:c.stock,e.is_internal=c.is_internal===void 0?!1:c.is_internal,e.sequence=c.sequence||0,e.image_url=c.image_url||``,e.image_thumbnail_url=c.image_thumbnail_url||``,e.type=k.Modifier,e.category_uid=a?a.uid:i.category_uid,i.modifiers.push(e)}return{categories:t,products:n}}let bi=function(e){return e.None=``,e.Always=`always`,e}({}),xi=function(e){return e.Image=`image`,e.Video=`video`,e.Unsupported=`unsupported`,e}({}),Si=function(e){return e.CdsFullScreenImage=`cds_full_screen_image`,e.CdsHalfScreenImage=`cds_half_screen_image`,e}({});var Ci=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)}},wi=class extends x{constructor(...e){super(...e),v(this,`uid`,S.Storage+t()),v(this,`model`,void 0),v(this,`data`,void 0)}},Ti=class extends x{constructor(...e){super(...e),v(this,`uid`,S.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 Ei=function(e){return e.In=`IN`,e.Out=`OUT`,e.Adjust=`ADJUST`,e.Production=`PRODUCTION`,e}({}),Di=function(e){return e.Invoice=`invoice`,e.Purchase=`purchase`,e.Production=`production`,e.Stocktake=`stocktake`,e}({}),Oi=function(e){return e.Item=`item`,e.Material=`material`,e}({});var ki=class extends b{constructor(){super(),v(this,`entity_type`,Oi.Item),v(this,`entity_uid`,``),v(this,`type`,Ei.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`,S.StockLog+t())}};const Ai=[`#each`,`#if`,`#elseif`,`#else`,`#let`,`#merge`,`#concat`,`#include`,`#?`,`#flatten`];function ji(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];Ai.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`)&&Mi(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 Mi(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{te as Address,x as AppBaseModel,Ct as AppConfig,b as AppCoreModel,un as AppCoreService,ue as AppExtraModel,dn as AppLocalService,Gr as AppMiscService,G as AppRemoteService,hn as AppReport,Kr as AppReportService,ae as Applying,Si as AssetTags,xi as AssetType,on as Between,wt as Cache,U as CalcFlow,H as CalcType,Ot as CardPaymentCode,en as CashDrawerConfig,Ee as Category,Cn as CategorySalesSummary,Lr as CategoryService,we as CategoryType,vt as Charge,Jt as ChargeConfig,M as Codepages,je as ComboGroup,Ae as ComboGroupItem,bi as Condition,jt as Config,Rr as ConfigService,Te as CoreCategory,Oe as CoreItem,oe as Coupon,ce as CouponItemized,se as CouponUsage,Tt as CrmConfig,Yt as CurrencyConfig,ne as Customer,Dt as CustomerDisplaySystemConfig,Pt as DeployChannel,Ge as Device,qe as DeviceType,ht as DiscountType,vn as DrawerSummary,j as ElectronSocket,St as Employee,be as EmployeeRole,Pr as EmployeeRoleService,Fr as EmployeeService,w as ErrorMsgs,Ue as EscPosCompatibility,Ie as EscPosPrinter,tn as FileUploadRequest,$t as GTOConfig,It as GeneralConfig,an as In,rn as Include,Zt as InventoryConfig,xt as Invoice,pt as InvoiceAction,_t as InvoiceActivity,Ar as InvoiceBaseService,gt as InvoiceCharge,yt as InvoiceCoreLine,W as InvoiceDiscount,bt as InvoiceLine,Mr as InvoiceOperationService,Nr as InvoiceService,V as InvoiceStatus,B as InvoiceType,A as Item,xn as ItemSalesSummary,Ir as ItemService,Vt as KdsConfig,kt as KioskSystemConfig,Bt as KitchenConfig,Ht as LabelConfig,jr as LineOperationService,Et as LoyaltyProgram,bn as LoyaltyProgramSummary,At as MarketingConfig,Ti as Menu,Jr as MenuService,Ci as Merchant,me as MessageType,S as ModelPrefix,de as ModelType,Sn as ModifierSalesSummary,Ke as Node,Je as NodePrinter,sn as Not,ut as Note,lt as NoteEntity,ct as NoteGroup,st as NoteGroupEntity,Nt as OnlineOrderConfig,Ut as OrderConfig,Dr as OrderDisplay,Or as OrderDisplayService,Y as OrderDisplayStatus,Wt as OrderDisplaySystemConfig,dt as OrderFlow,Qt as PaxConfig,nt as Payment,Gt as PaymentConfig,rt as PaymentMethod,it as PaymentMethodHistory,Ur as PaymentMethodService,Wr as PaymentService,ot as PaymentStatus,yn as PaymentSummary,Mt as PaynowMethod,ke as Price,Le as PrintAlign,Be as PrintBarcode,P as PrintCommand,He as PrintImage,R as PrintJob,qr as PrintJobService,Qe as PrintJobStatus,Ve as PrintQrcode,ze as PrintSize,Re as PrintStyle,L as PrintTemplate,Ze as PrintTemplateCore,Yr as PrintTemplateService,N as PrintType,et as Printer,Xe as PrinterConnections,Ye as PrinterProtocols,wn as PrinterService,$e as PrinterStatus,I as PrinterType,O as ProductBase,Ft as ProductConfig,Vr as ProductService,k as ProductType,he as PushData,cn as Raw,zt as Receipt,z as RenderPrintTemplateOptions,mn as Report,pn as ReportCategory,Rt as ReportConfig,gn as ReportData,fn as ReportType,Xt as RoundingConfig,_n as SalesSummary,ye as Section,ve as SectionItem,Br as SectionItemService,D as SectionItemStatus,zr as SectionService,ui as ServiceFactory,fe as ServiceMode,pe as ServiceOptions,ge as Shift,Hr as ShiftService,T as ShiftStatus,at as StandardPaymentMethod,xe as StockChange,ki as StockLog,Oi as StockLogEntityType,Di as StockLogRefType,Zr as StockLogService,Ei as StockLogType,wi as Storage,Xr as StorageService,De as Subcategory,Ce as System,C as SystemError,qt as TaxConfig,ft as TaxMethod,tt as TemplateData,_e as Till,Lt as TillConfig,X as TillService,E as TillType,mt as UomType,y as User,Kt as UserConfig,Se as Visibility,di as createCSVExport,li as dbSchemas,ln as filterByParams,F as humanizedData,hi as importFromCSV,We as normalizedDate,le as transformer,ji as validateSTTemplate};
|
|
6
6
|
//# sourceMappingURL=index.js.map
|