@tallyui/pos 3.17.0 → 3.18.0

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/dist/index.d.ts CHANGED
@@ -134,12 +134,22 @@ declare function csvFromCells(lines: readonly (readonly unknown[])[]): string;
134
134
  /** Header row from `columns`, then one line per row. */
135
135
  declare function toCsv<Row>(rows: readonly Row[], columns: readonly CsvColumn<Row>[]): string;
136
136
 
137
+ /** A store's own money format (WCPOS v2 General settings); a field left out keeps the locale's. */
138
+ interface CurrencyFormat {
139
+ position?: 'left' | 'right' | 'left_space' | 'right_space';
140
+ thousandSeparator?: string;
141
+ decimalSeparator?: string;
142
+ decimals?: number;
143
+ }
144
+
137
145
  interface CurrencyProviderProps {
138
146
  currencyCode: string;
139
147
  locale?: string;
148
+ /** The store's own money format; without it, money reads as Intl formats it for `locale`. */
149
+ format?: CurrencyFormat;
140
150
  children: ReactNode;
141
151
  }
142
- declare function CurrencyProvider({ currencyCode, locale, children }: CurrencyProviderProps): react_jsx_runtime.JSX.Element;
152
+ declare function CurrencyProvider({ currencyCode, locale, format, children }: CurrencyProviderProps): react_jsx_runtime.JSX.Element;
143
153
  declare function useCurrencyFormatter(): (money: Money) => string;
144
154
  declare function useCurrencyCode(): string;
145
155
 
@@ -3675,6 +3685,14 @@ declare function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscoun
3675
3685
  capabilities?: ServerCapabilities;
3676
3686
  /** The platform's discount codes (ADR-077 amendment 3), e.g. woocommerceDiscountCodes.createDiscountCodes(source); without them, applyCoupon refuses with COUPONS_UNSUPPORTED. */
3677
3687
  discountCodes?: SaleDiscountCodes<any>;
3688
+ /**
3689
+ * Put on every new sale, as v2's store setting `default_customer` (or the cashier, `default_customer_is_cashier`)
3690
+ * is on every new cart: the first sale and each one after complete, discard, park, newSale or a switch to New,
3691
+ * never a resumed one. The app resolves which customer. A cashier's change, Guest included, stays on that sale.
3692
+ * A change applies at once to an idle cart, else to the next new sale. One `setCustomer` would refuse is skipped
3693
+ * (the sale starts on guest, with no error).
3694
+ */
3695
+ defaultCustomer?: CustomerSummary | null;
3678
3696
  /** Where `park()` keeps parked carts; create it with `orderDraftSchema` */
3679
3697
  drafts?: RxCollection;
3680
3698
  /**
@@ -4453,4 +4471,4 @@ declare function reportOrderFromPosOrder(order: PosOrder, join?: LineJoin): Repo
4453
4471
  declare function reportOrderFromStoreOrder(order: StoreOrder, join?: LineJoin): ReportOrder;
4454
4472
  declare function reportRefundFromPosRefund(refund: PosRefund): ReportRefund | undefined;
4455
4473
 
4456
- export { APP_SETTING_DEFINITIONS, type Actor, type AddLineInput, type AppSettingCollection, type AppSettingDefinition, type AppSettingDoc, type AppSettingKey, type AppSettings, type AppliedDiscount, type ApprovalNeeded, type BackendNotFound, type BasketLine, type BroadcastChannelLike, COUPONS_UNSUPPORTED, CartError, type CartQuantityLine, type CashMovement, type CashMovementCollection, type CashierState, type CatalogueEntry, type CatalogueGridColumns, type CatalogueView, type CatalogueViewAction, type CatalogueViewState, type ChargeInput, type ChargeLine, type Closure, type ClosureApprovalStatus, type ClosureCollection, type ClosureContext, type ClosureScope, type CollectInput, type CollectOutcome, type CollectResult, type CommandTransport, type Correction, type CsvColumn, CurrencyProvider, type CurrencyProviderProps, type CustomerSummary, DATE_PRESETS, DEFAULT_APP_SETTINGS, DEFAULT_CATALOGUE_VIEW_STATE, DEFAULT_COOLDOWN_MS, DEFAULT_MIN_SCAN_CHARS, DEFAULT_RECEIPT_TEMPLATES, DEFAULT_WEDGE_SETTINGS, DISCOUNTS_UNSUPPORTED, DISPLAY_ACTIONS, DISPLAY_CHANNEL, DISPLAY_PROTOCOL_VERSION, DISPLAY_TEMPLATE, type DatePreset, type DayPoint, type DayRange, type DecodeRefusal, type DecodeResult, type Discount, type DisplayAction, type DisplayCart, type DisplayClock, type DisplayConfig, type DisplayEnvelope, type DisplayLine, type DisplayLink, type DisplayPayloads, type DisplayPayment, type DisplayState, type DisplayTemplate, type DisplayTotals, type DisplayTransport, type DisplayView, type DriverAvailability, type DriverCapabilities, type DriverStatus, type DriverStatusSource, ESCPOS_CODE_PAGES, type EarlierRefund, type EncodeEscPosOptions, type EscPosBuilder, type EscPosSink, type EscPosTransportOptions, type FeeLine, type FinalizeOptions, type FloatSuggestion, type GroupRow, HELLO_RETRY_MS, type HandoverSlipData, type HandoverSlipInput, type HttpTransportOptions, type LedgerRow, type LineItem, type LineJoin, type LineTaxLine, type LogActor, type LogEntry, type LogLevel, type LogMeta, type LogPreset, type LogPresetFilters, type LogSink, type LogSyncRecord, type Logger, MAX_MESSAGE_BYTES, MAX_TENDER_MINOR, MICROS_PER_MINOR, type Margin, type Movement$1 as Movement, type MovementType, type NoteDelivery, type OpenSale, type Order, type OrderBuilder, type OrderBuilderOptions, OrderContentMismatchError, type OrderCoupon, type OrderCouponContext, type OrderManager, type OrderManagerOptions, type OrderOutbox, type OrderOutboxOptions, type OrderRefundOutcome, type OrderTaxTotals, type OrderTransportContext, type OutboxCounts, type OutboxHealth, type OutboxState, PAPER_COLUMNS, PAYMENT_IN_MOTION, PRINTER_PROFILES_COLLECTION, PRODUCT_SORT_FIELDS, type ParkedOrderSummary, type Payment, type PaymentDriver, type PaymentDriverRegistry, type PaymentLegStatus, type PaymentMethod, type PaymentPhase, type PaymentRow, type PaymentTransport, type PlanLeg, type PosOrder, type PosOrderCoupon, type PosOrderLine, type PosOrderLocalWarning, PosOrderOpenClosedError, type PosOrderPayment, type PosOrderServerFailures, type PosOrderSyncStatus, type PosRefund, type PosRefundCollection, type PosRefundStatus, type PricedRefund, type PricedRefundLine, PrintError, type PrintErrorCode, type PrintJob, type PrintJobKind, type PrintQueue, type PrintQueueOptions, type PrintQueueState, type PrintTransport, type PrinterProfile, type PrinterProfileCollection, type ProductSort, type ProductSortValue, RECEIPT_SCHEMA_VERSION, REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS, REOPENABLE_CODES, type RateTaxLine, type ReaderInfo, type ReceiptConfig, type ReceiptData, type ReceiptFiscal, type ReceiptLineItem, type ReceiptNode, type ReceiptPaper, type ReceiptRegister, type ReceiptSoftware, type ReceiptTemplateData, type ReceiptTemplateLine, type ReceiptTemplateOptions, type ReceiptTemplateRow, type RecordedFigures, RefundAnswerPendingError, type RefundableLine, type RefundableOrderLine, RegisterApprovalRequiredError, type RegisterBucket, RegisterCloseIncompleteError, type RegisterCommand, type RegisterCommandCollection, type RegisterCounters, type RegisterDocument, type RegisterFact, type RegisterHost, RegisterIdInvalidError, RegisterMovementAmountError, RegisterMovementReasonError, RegisterMovementStrandedError, RegisterNeedsUpgradeError, type RegisterOutbox, type RegisterOutboxOptions, RegisterReapproveError, type RegisterSession, RegisterSessionAlreadyOpenError, RegisterSessionClosedError, type RegisterSessionCollection, RegisterSessionConflictError, RegisterSessionOpenClosedError, RegisterSessionRequiredError, type RegisterStore, RegisterTakeOverError, RegisterTenderInProgressError, type RenderReceiptOptions, type RenderSanitizeOptions, type ReopenRefusal, ReopenRefusedOrderError, type ReportCategory, type ReportLine, type ReportOrder, type ReportPayment, type ReportRefund, type ReportTax, type Repository, type ResolveStoreSettingsOptions, SALE_IN_TENDER, SALE_PARTLY_PAID, SALE_SAVING, SIMULATED_PROVIDER, SIMULATED_TIMING, SYSTEM_PRINTER_ID, SYSTEM_PRINT_TIMING, type SaleDiscountCodes, type SaleDiscountState, type SaleStage, type SalesFigures, type SalesFiguresInput, type SalesTotals, type SanitizeHtmlOptions, type ScanOfferResult, type ScanRejectReason, type ScanSession, type ScanSessionOptions, type SentOrder, type ShippingLine, type SimulatedDriverOptions, type SimulatedReaderId, type SplitTab, type StoreDay, type StoreSettingsResolution, type StoreSettingsState, type StuckRecord, type SwitchKind, type SwitchWarning, type SwitchWarningInput, type SwitchWarnings, type SyncRecordOutcome, type SystemPrintTransportOptions, TAX_ROUNDING_MIXED_NOTE, type TaxContext, type TaxLineInput, TaxProvider, type TaxProviderProps, type TaxRateMap, type TaxRow, type TenderAction, type TenderKey, type TenderLineId, type TenderPlan, type TenderRounding, type TenderState, type TenderView, type TenderVoid, type ThermalNode, type TraceKey, type TransportOutcome, UI_SCALES, UI_THEMES, type UiScale, type UiTheme, UnsupportedOrderVersionError, type UseBarcodeScannerOptions, type UseOrderOutboxOptions, type UseOrderOutboxResult, type UseOutboxHealthOptions, type UseOutboxHealthResult, type UseRegisterOutboxOptions, type UseRegisterOutboxResult, type UseRegisterSessionOptions, WEDGE_END_OF_SCAN_MS, type WedgeDetector, type WedgeDetectorOptions, type WedgeReplayResult, type WedgeSettings, type WedgeState, abandonSession, activePlan, addEntryToCart, addPosOrderCollection, addPrinterProfileCollection, addRegisterSessionCollection, adoptRegisterResults, advancePerpetual, allocateOrderDiscount, appSettingCollection, appSettingSchema, appSettings$, appliedMinor, backToSelling, bindRegister, buildClosureDocument, buildReceiptData, buildReceiptDataFromPosOrder, buildReceiptDataFromStoreOrder, buildXReportDocument, callbackSink, can, canMoveLeg, canVoidLeg, capturedMinor, cartQuantities, cashMovementSchema, catalogueEntries, catalogueViewReducer, changeMinor, clampClosureScope, closeNeedsApproval, closeSession, closureApprovalStatus, closureCommand, closureSchema, closureVariance, comparisonRange, computeOrderTax, consoleSink, countVariance, countsTowardPaid, createBackendNotFound, createBroadcastDisplayTransport, createDisplayLink, createEscPosTransport, createHttpCommandTransport, createLogger, createOrderBuilder, createOrderManager, createOrderOutbox, createPaymentDriverRegistry, createPrintQueue, createRegisterOutbox, createRepository, createScanSession, createSimulatedDriver, createSystemPrintTransport, createWedgeDetector, createWedgeState, csvCell, csvFromCells, daysOf, decode as decodeDisplayMessage, denominationTotal, denominations, deriveExpected, deriveSettled, deriveStuckRecords, displayCart, displayReducer, driverForMethod, encode as encodeDisplayMessage, encodeEscPos, ensureRegister, escpos, evenSplitShareMinor, exportCsv, finalizeOrder, findEntryByCode, foldWedgeKey, formatClosureDate, getBoundRegisterId, getDeviceId, handoverSlip, hasActor, hasValidRetailCheckDigit, inCategory, inMotionMinor, inRange, initTenderState, initialDisplayState, initialTenderState, isInMotion, isKnownSessionStatus, isLiveAtStore, isPartlyPaid, isRegisterRequeueable, isReopened, isRequeueable, isServerDecimal, labelKeys, legStatus, listCategories, makeEnvelope, marginOf, matchesPresetFilters, messageBytes, minorToDecimal, mintClosureNumber, mintUuid, movementCommand, movementFieldError, needsAttention, nextSaleCounter, normalizeAmount, normalizeCatalogueViewState, normalizeRetailCode, noteDelivery, observeRegister$, openSales, openSession, openSessionSelector, orderDraftSchema, outboxLogger, overThreshold, parkedOrderSummaries$, parseMinor, parseXml, planLegs, posOrderCollection, posOrderSchema, posOrdersLogger, posRefundCollection, posRefundSchema, presetFilters, presetRange, priceRefund, printerProfileCollection, printerProfileSchema, productCategories, productSortValue, quickTenderedAmounts, ratePpmFromPercent, readAppSettings, readBoundRegister, readRegister, reapproveClosure, receiptTemplateData, reconcileRegisterCommands, recordMovement, recordRegisterFact, refundableLines, registerCommandCollection, registerCommandSchema, registerCommandsLogger, registerFactsLogger, registerSessionCollection, registerSessionSchema, registerSessionsLogger, renderHtml, renderLogiclessTemplate, renderReceiptHtml, renderReceiptTemplate, renderThermalPreview, reopenRefusedOrder, replacedOrderIds, replayWedgeDetector, reportOrderFromPosOrder, reportOrderFromStoreOrder, reportRefundFromPosRefund, requireOpenSession, resolveAppSettings, resolveGridColumns, resolveStoreSettings, restoreOrderDraft, retailCodeTwin, roundMicrosToMinor, roundedDue, saleLogger, salesFigures, sameSale, sanitizeHtml, searchProducts, selectClosureRows, sendOrderRefund, sessionOpenCommand, sessionTransitionCommand, sortProducts, stampSession, startCounting, stockOverlay$, stockOverlayAsOf$, stripBoundary, submitOrderRefund, suggestFloat, summarizeOutboxHealth, switchWarnings, takeOverSession, taxFiguresForBasket, taxLinesByRate, taxLogger, taxMicros, taxProviderProps, tenderReducer, tenderRounding, tenderVoidCollection, tenderVoidSchema, toCsv, toOrderCreateEnvelope, toPrintError, unbindRegister, useAppSettings, useBarcodeScanner, useCashier, useCurrencyCode, useCurrencyFormatter, useCustomerDisplay, useOrderOutbox, useOutboxHealth, useParkedSales, useRegisterOutbox, useRegisterSession, useSale, useStoreSettings, useTax, uuidv7, validAmount, varianceText, variantPriceLabel, voidMovement, watchOutboxHealth, withPricingContext, index as woocommerceDiscountCodes, writeAppSetting, writeClosure, writeOrderDraft };
4474
+ export { APP_SETTING_DEFINITIONS, type Actor, type AddLineInput, type AppSettingCollection, type AppSettingDefinition, type AppSettingDoc, type AppSettingKey, type AppSettings, type AppliedDiscount, type ApprovalNeeded, type BackendNotFound, type BasketLine, type BroadcastChannelLike, COUPONS_UNSUPPORTED, CartError, type CartQuantityLine, type CashMovement, type CashMovementCollection, type CashierState, type CatalogueEntry, type CatalogueGridColumns, type CatalogueView, type CatalogueViewAction, type CatalogueViewState, type ChargeInput, type ChargeLine, type Closure, type ClosureApprovalStatus, type ClosureCollection, type ClosureContext, type ClosureScope, type CollectInput, type CollectOutcome, type CollectResult, type CommandTransport, type Correction, type CsvColumn, type CurrencyFormat, CurrencyProvider, type CurrencyProviderProps, type CustomerSummary, DATE_PRESETS, DEFAULT_APP_SETTINGS, DEFAULT_CATALOGUE_VIEW_STATE, DEFAULT_COOLDOWN_MS, DEFAULT_MIN_SCAN_CHARS, DEFAULT_RECEIPT_TEMPLATES, DEFAULT_WEDGE_SETTINGS, DISCOUNTS_UNSUPPORTED, DISPLAY_ACTIONS, DISPLAY_CHANNEL, DISPLAY_PROTOCOL_VERSION, DISPLAY_TEMPLATE, type DatePreset, type DayPoint, type DayRange, type DecodeRefusal, type DecodeResult, type Discount, type DisplayAction, type DisplayCart, type DisplayClock, type DisplayConfig, type DisplayEnvelope, type DisplayLine, type DisplayLink, type DisplayPayloads, type DisplayPayment, type DisplayState, type DisplayTemplate, type DisplayTotals, type DisplayTransport, type DisplayView, type DriverAvailability, type DriverCapabilities, type DriverStatus, type DriverStatusSource, ESCPOS_CODE_PAGES, type EarlierRefund, type EncodeEscPosOptions, type EscPosBuilder, type EscPosSink, type EscPosTransportOptions, type FeeLine, type FinalizeOptions, type FloatSuggestion, type GroupRow, HELLO_RETRY_MS, type HandoverSlipData, type HandoverSlipInput, type HttpTransportOptions, type LedgerRow, type LineItem, type LineJoin, type LineTaxLine, type LogActor, type LogEntry, type LogLevel, type LogMeta, type LogPreset, type LogPresetFilters, type LogSink, type LogSyncRecord, type Logger, MAX_MESSAGE_BYTES, MAX_TENDER_MINOR, MICROS_PER_MINOR, type Margin, type Movement$1 as Movement, type MovementType, type NoteDelivery, type OpenSale, type Order, type OrderBuilder, type OrderBuilderOptions, OrderContentMismatchError, type OrderCoupon, type OrderCouponContext, type OrderManager, type OrderManagerOptions, type OrderOutbox, type OrderOutboxOptions, type OrderRefundOutcome, type OrderTaxTotals, type OrderTransportContext, type OutboxCounts, type OutboxHealth, type OutboxState, PAPER_COLUMNS, PAYMENT_IN_MOTION, PRINTER_PROFILES_COLLECTION, PRODUCT_SORT_FIELDS, type ParkedOrderSummary, type Payment, type PaymentDriver, type PaymentDriverRegistry, type PaymentLegStatus, type PaymentMethod, type PaymentPhase, type PaymentRow, type PaymentTransport, type PlanLeg, type PosOrder, type PosOrderCoupon, type PosOrderLine, type PosOrderLocalWarning, PosOrderOpenClosedError, type PosOrderPayment, type PosOrderServerFailures, type PosOrderSyncStatus, type PosRefund, type PosRefundCollection, type PosRefundStatus, type PricedRefund, type PricedRefundLine, PrintError, type PrintErrorCode, type PrintJob, type PrintJobKind, type PrintQueue, type PrintQueueOptions, type PrintQueueState, type PrintTransport, type PrinterProfile, type PrinterProfileCollection, type ProductSort, type ProductSortValue, RECEIPT_SCHEMA_VERSION, REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS, REOPENABLE_CODES, type RateTaxLine, type ReaderInfo, type ReceiptConfig, type ReceiptData, type ReceiptFiscal, type ReceiptLineItem, type ReceiptNode, type ReceiptPaper, type ReceiptRegister, type ReceiptSoftware, type ReceiptTemplateData, type ReceiptTemplateLine, type ReceiptTemplateOptions, type ReceiptTemplateRow, type RecordedFigures, RefundAnswerPendingError, type RefundableLine, type RefundableOrderLine, RegisterApprovalRequiredError, type RegisterBucket, RegisterCloseIncompleteError, type RegisterCommand, type RegisterCommandCollection, type RegisterCounters, type RegisterDocument, type RegisterFact, type RegisterHost, RegisterIdInvalidError, RegisterMovementAmountError, RegisterMovementReasonError, RegisterMovementStrandedError, RegisterNeedsUpgradeError, type RegisterOutbox, type RegisterOutboxOptions, RegisterReapproveError, type RegisterSession, RegisterSessionAlreadyOpenError, RegisterSessionClosedError, type RegisterSessionCollection, RegisterSessionConflictError, RegisterSessionOpenClosedError, RegisterSessionRequiredError, type RegisterStore, RegisterTakeOverError, RegisterTenderInProgressError, type RenderReceiptOptions, type RenderSanitizeOptions, type ReopenRefusal, ReopenRefusedOrderError, type ReportCategory, type ReportLine, type ReportOrder, type ReportPayment, type ReportRefund, type ReportTax, type Repository, type ResolveStoreSettingsOptions, SALE_IN_TENDER, SALE_PARTLY_PAID, SALE_SAVING, SIMULATED_PROVIDER, SIMULATED_TIMING, SYSTEM_PRINTER_ID, SYSTEM_PRINT_TIMING, type SaleDiscountCodes, type SaleDiscountState, type SaleStage, type SalesFigures, type SalesFiguresInput, type SalesTotals, type SanitizeHtmlOptions, type ScanOfferResult, type ScanRejectReason, type ScanSession, type ScanSessionOptions, type SentOrder, type ShippingLine, type SimulatedDriverOptions, type SimulatedReaderId, type SplitTab, type StoreDay, type StoreSettingsResolution, type StoreSettingsState, type StuckRecord, type SwitchKind, type SwitchWarning, type SwitchWarningInput, type SwitchWarnings, type SyncRecordOutcome, type SystemPrintTransportOptions, TAX_ROUNDING_MIXED_NOTE, type TaxContext, type TaxLineInput, TaxProvider, type TaxProviderProps, type TaxRateMap, type TaxRow, type TenderAction, type TenderKey, type TenderLineId, type TenderPlan, type TenderRounding, type TenderState, type TenderView, type TenderVoid, type ThermalNode, type TraceKey, type TransportOutcome, UI_SCALES, UI_THEMES, type UiScale, type UiTheme, UnsupportedOrderVersionError, type UseBarcodeScannerOptions, type UseOrderOutboxOptions, type UseOrderOutboxResult, type UseOutboxHealthOptions, type UseOutboxHealthResult, type UseRegisterOutboxOptions, type UseRegisterOutboxResult, type UseRegisterSessionOptions, WEDGE_END_OF_SCAN_MS, type WedgeDetector, type WedgeDetectorOptions, type WedgeReplayResult, type WedgeSettings, type WedgeState, abandonSession, activePlan, addEntryToCart, addPosOrderCollection, addPrinterProfileCollection, addRegisterSessionCollection, adoptRegisterResults, advancePerpetual, allocateOrderDiscount, appSettingCollection, appSettingSchema, appSettings$, appliedMinor, backToSelling, bindRegister, buildClosureDocument, buildReceiptData, buildReceiptDataFromPosOrder, buildReceiptDataFromStoreOrder, buildXReportDocument, callbackSink, can, canMoveLeg, canVoidLeg, capturedMinor, cartQuantities, cashMovementSchema, catalogueEntries, catalogueViewReducer, changeMinor, clampClosureScope, closeNeedsApproval, closeSession, closureApprovalStatus, closureCommand, closureSchema, closureVariance, comparisonRange, computeOrderTax, consoleSink, countVariance, countsTowardPaid, createBackendNotFound, createBroadcastDisplayTransport, createDisplayLink, createEscPosTransport, createHttpCommandTransport, createLogger, createOrderBuilder, createOrderManager, createOrderOutbox, createPaymentDriverRegistry, createPrintQueue, createRegisterOutbox, createRepository, createScanSession, createSimulatedDriver, createSystemPrintTransport, createWedgeDetector, createWedgeState, csvCell, csvFromCells, daysOf, decode as decodeDisplayMessage, denominationTotal, denominations, deriveExpected, deriveSettled, deriveStuckRecords, displayCart, displayReducer, driverForMethod, encode as encodeDisplayMessage, encodeEscPos, ensureRegister, escpos, evenSplitShareMinor, exportCsv, finalizeOrder, findEntryByCode, foldWedgeKey, formatClosureDate, getBoundRegisterId, getDeviceId, handoverSlip, hasActor, hasValidRetailCheckDigit, inCategory, inMotionMinor, inRange, initTenderState, initialDisplayState, initialTenderState, isInMotion, isKnownSessionStatus, isLiveAtStore, isPartlyPaid, isRegisterRequeueable, isReopened, isRequeueable, isServerDecimal, labelKeys, legStatus, listCategories, makeEnvelope, marginOf, matchesPresetFilters, messageBytes, minorToDecimal, mintClosureNumber, mintUuid, movementCommand, movementFieldError, needsAttention, nextSaleCounter, normalizeAmount, normalizeCatalogueViewState, normalizeRetailCode, noteDelivery, observeRegister$, openSales, openSession, openSessionSelector, orderDraftSchema, outboxLogger, overThreshold, parkedOrderSummaries$, parseMinor, parseXml, planLegs, posOrderCollection, posOrderSchema, posOrdersLogger, posRefundCollection, posRefundSchema, presetFilters, presetRange, priceRefund, printerProfileCollection, printerProfileSchema, productCategories, productSortValue, quickTenderedAmounts, ratePpmFromPercent, readAppSettings, readBoundRegister, readRegister, reapproveClosure, receiptTemplateData, reconcileRegisterCommands, recordMovement, recordRegisterFact, refundableLines, registerCommandCollection, registerCommandSchema, registerCommandsLogger, registerFactsLogger, registerSessionCollection, registerSessionSchema, registerSessionsLogger, renderHtml, renderLogiclessTemplate, renderReceiptHtml, renderReceiptTemplate, renderThermalPreview, reopenRefusedOrder, replacedOrderIds, replayWedgeDetector, reportOrderFromPosOrder, reportOrderFromStoreOrder, reportRefundFromPosRefund, requireOpenSession, resolveAppSettings, resolveGridColumns, resolveStoreSettings, restoreOrderDraft, retailCodeTwin, roundMicrosToMinor, roundedDue, saleLogger, salesFigures, sameSale, sanitizeHtml, searchProducts, selectClosureRows, sendOrderRefund, sessionOpenCommand, sessionTransitionCommand, sortProducts, stampSession, startCounting, stockOverlay$, stockOverlayAsOf$, stripBoundary, submitOrderRefund, suggestFloat, summarizeOutboxHealth, switchWarnings, takeOverSession, taxFiguresForBasket, taxLinesByRate, taxLogger, taxMicros, taxProviderProps, tenderReducer, tenderRounding, tenderVoidCollection, tenderVoidSchema, toCsv, toOrderCreateEnvelope, toPrintError, unbindRegister, useAppSettings, useBarcodeScanner, useCashier, useCurrencyCode, useCurrencyFormatter, useCustomerDisplay, useOrderOutbox, useOutboxHealth, useParkedSales, useRegisterOutbox, useRegisterSession, useSale, useStoreSettings, useTax, uuidv7, validAmount, varianceText, variantPriceLabel, voidMovement, watchOutboxHealth, withPricingContext, index as woocommerceDiscountCodes, writeAppSetting, writeClosure, writeOrderDraft };
package/dist/index.js CHANGED
@@ -126,10 +126,41 @@ function toCsv(rows, columns) {
126
126
  // src/currency/currency-provider.tsx
127
127
  import { createContext, useContext, useMemo, useCallback } from "react";
128
128
  import { formatMoney } from "@tallyui/core";
129
+
130
+ // src/currency/format-money-with.ts
131
+ import { minorUnitDigits } from "@tallyui/core";
132
+ function formatMoneyWith(money, format2, locale) {
133
+ if (money.currency === "XXX") return void 0;
134
+ const minor2 = minorUnitDigits(money.currency);
135
+ const decimals = format2.decimals ?? minor2;
136
+ const abs = Math.abs(money.amount);
137
+ const major = decimals >= minor2 ? abs / 10 ** minor2 : Math.round(abs / 10 ** (minor2 - decimals)) / 10 ** decimals;
138
+ let parts;
139
+ try {
140
+ parts = new Intl.NumberFormat(locale, {
141
+ style: "currency",
142
+ currency: money.currency,
143
+ minimumFractionDigits: decimals,
144
+ maximumFractionDigits: decimals
145
+ }).formatToParts(major);
146
+ } catch {
147
+ return void 0;
148
+ }
149
+ const text2 = (...types) => parts.filter((p) => types.includes(p.type)).map((p) => p.value).join("");
150
+ const { position, thousandSeparator, decimalSeparator } = format2;
151
+ const integer = thousandSeparator === void 0 ? text2("integer", "group") : text2("integer").replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
152
+ const number = integer + (decimals > 0 ? (decimalSeparator ?? text2("decimal")) + text2("fraction") : "");
153
+ const symbol = text2("currency");
154
+ const left = position ? position.startsWith("left") : parts.findIndex((p) => p.type === "currency") < parts.findIndex((p) => p.type === "integer");
155
+ const gap = position ? position.endsWith("_space") ? " " : "" : text2("literal");
156
+ return (money.amount < 0 && major > 0 ? "-" : "") + (left ? symbol + gap + number : number + gap + symbol);
157
+ }
158
+
159
+ // src/currency/currency-provider.tsx
129
160
  import { jsx } from "react/jsx-runtime";
130
161
  var CurrencyCtx = createContext(null);
131
- function CurrencyProvider({ currencyCode, locale, children }) {
132
- const value = useMemo(() => ({ currencyCode, locale }), [currencyCode, locale]);
162
+ function CurrencyProvider({ currencyCode, locale, format: format2, children }) {
163
+ const value = useMemo(() => ({ currencyCode, locale, format: format2 }), [currencyCode, locale, format2]);
133
164
  return /* @__PURE__ */ jsx(CurrencyCtx.Provider, { value, children });
134
165
  }
135
166
  function useCurrencyFormatter() {
@@ -137,9 +168,10 @@ function useCurrencyFormatter() {
137
168
  if (!ctx) {
138
169
  throw new Error("useCurrencyFormatter() must be used within a <CurrencyProvider>");
139
170
  }
171
+ const { locale, format: format2 } = ctx;
140
172
  return useCallback(
141
- (money) => formatMoney(money, ctx.locale) ?? `${money.amount} ${money.currency}`,
142
- [ctx.locale]
173
+ (money) => (format2 ? formatMoneyWith(money, format2, locale) : formatMoney(money, locale)) ?? `${money.amount} ${money.currency}`,
174
+ [locale, format2]
143
175
  );
144
176
  }
145
177
  function useCurrencyCode() {
@@ -151,9 +183,9 @@ function useCurrencyCode() {
151
183
  }
152
184
 
153
185
  // src/order/woocommerce-tax.ts
154
- import { minorUnitDigits, woocommerceTax, woocommerceCoupons } from "@tallyui/core";
186
+ import { minorUnitDigits as minorUnitDigits2, woocommerceTax, woocommerceCoupons } from "@tallyui/core";
155
187
  function woocommerceLine(amountMinor, rates, inclusive, currency, roundAtSubtotal, pricesIncludeTax = inclusive) {
156
- const dp = minorUnitDigits(currency), factor = 10 ** dp;
188
+ const dp = minorUnitDigits2(currency), factor = 10 ** dp;
157
189
  const precision = woocommerceTax.getRoundingPrecision(dp);
158
190
  const input = {
159
191
  amount: amountMinor / factor,
@@ -189,7 +221,7 @@ function lineAmounts(net, taxes, taxLines, dp, roundAtSubtotal, pricesIncludeTax
189
221
  };
190
222
  }
191
223
  function woocommerceCouponReplay(lines, codes, context, getTaxRates, currency, roundAtSubtotal, pricesIncludeTax) {
192
- const dp = minorUnitDigits(currency), factor = 10 ** dp;
224
+ const dp = minorUnitDigits2(currency), factor = 10 ** dp;
193
225
  const inputLines = lines.filter((line) => line.unitPriceMinor >= 0);
194
226
  const lineItems = inputLines.map((line) => {
195
227
  const productId = Number(line.productId), variationId = Number(line.variantId);
@@ -253,7 +285,7 @@ function woocommerceCouponReplay(lines, codes, context, getTaxRates, currency, r
253
285
  };
254
286
  }
255
287
  function woocommerceTotals(lines, fees, shipping, currency, roundAtSubtotal, inclusive) {
256
- const dp = minorUnitDigits(currency), factor = 10 ** dp;
288
+ const dp = minorUnitDigits2(currency), factor = 10 ** dp;
257
289
  const net = (line) => Number(line.netMicros) / (factor * 1e6);
258
290
  const productNet = lines.reduce((sum2, line) => sum2 + (roundAtSubtotal ? net(line) : woocommerceTax.roundHalfUp(net(line), dp)), 0);
259
291
  const amount = productNet + fees.reduce((sum2, line) => sum2 + net(line), 0) + shipping.reduce((sum2, line) => sum2 + woocommerceTax.roundHalfUp(net(line), dp), 0);
@@ -1823,7 +1855,7 @@ function buildReceiptData(order, config) {
1823
1855
  }
1824
1856
 
1825
1857
  // src/receipt/reprint.ts
1826
- import { minorUnitDigits as minorUnitDigits2, woocommerceTax as woocommerceTax4 } from "@tallyui/core";
1858
+ import { minorUnitDigits as minorUnitDigits3, woocommerceTax as woocommerceTax4 } from "@tallyui/core";
1827
1859
 
1828
1860
  // src/pos-order/note-delivery.ts
1829
1861
  function noteDelivery(order) {
@@ -1853,7 +1885,7 @@ var sum = (amounts) => amounts.reduce((total, amount) => total + amount, 0);
1853
1885
  function buildReceiptDataFromPosOrder(order, config) {
1854
1886
  const { header, ...blocks } = reprintBlocks(config, order.customer);
1855
1887
  const { display, taxRounding: rounding } = order;
1856
- const dp = minorUnitDigits2(order.currency), factor = 10 ** dp;
1888
+ const dp = minorUnitDigits3(order.currency), factor = 10 ** dp;
1857
1889
  const wooGrossMinor = (line, roundAtSubtotal) => {
1858
1890
  const tax = line.taxLines.reduce((sum2, row) => sum2 + (roundAtSubtotal ? Number(row.taxMicros) / (factor * 1e6) : woocommerceTax4.roundTaxTotal(Number(row.taxMicros) / (factor * 1e6), dp, order.pricesIncludeTax)), 0);
1859
1891
  return Math.round(woocommerceTax4.roundHalfUp(Number(line.netMicros) / (factor * 1e6) + tax, dp) * factor);
@@ -3555,7 +3587,7 @@ import { useEffect as useEffect8, useLayoutEffect, useRef as useRef4, useState a
3555
3587
  import { paymentMethodOf } from "@tallyui/core";
3556
3588
 
3557
3589
  // src/pos-order/finalize.ts
3558
- import { minorUnitDigits as minorUnitDigits3, ORDER_NOTE_MAX } from "@tallyui/core";
3590
+ import { minorUnitDigits as minorUnitDigits4, ORDER_NOTE_MAX } from "@tallyui/core";
3559
3591
 
3560
3592
  // src/outbox/logger.ts
3561
3593
  var outboxLogger = createLogger("outbox");
@@ -3762,7 +3794,7 @@ function finalizeOrder(order, options = {}) {
3762
3794
  }
3763
3795
  display = {
3764
3796
  currency: order.currency,
3765
- exponent: minorUnitDigits3(order.currency),
3797
+ exponent: minorUnitDigits4(order.currency),
3766
3798
  ...order.display,
3767
3799
  ...fees?.length ? { fees: order.display.fees.map((row, i) => ({ ...row, id: fees[i].id })) } : {},
3768
3800
  ...shipping?.length ? { shipping: order.display.shipping.map((row, i) => ({ ...row, id: shipping[i].id })) } : {},
@@ -7452,7 +7484,18 @@ var HUNG_SAVE_CHECK_MS = 5e3;
7452
7484
  function useSale(settings, opts) {
7453
7485
  const taxContext = useTax();
7454
7486
  const madeWith = useRef4({ taxContext, currency: settings.currency });
7455
- const [rendered, setBuilder] = useState7(() => createOrderBuilder({ currency: settings.currency, taxContext }));
7487
+ function defaulted() {
7488
+ const customer = opts.defaultCustomer ?? null;
7489
+ return customer && !customerRefusal(customer) ? customer : null;
7490
+ }
7491
+ const defaultKey = opts.defaultCustomer ? JSON.stringify([opts.defaultCustomer.id, opts.defaultCustomer.name, opts.defaultCustomer.email]) : "";
7492
+ const defaultSeen = useRef4(defaultKey);
7493
+ const [rendered, setBuilder] = useState7(() => {
7494
+ const first = createOrderBuilder({ currency: settings.currency, taxContext });
7495
+ const customer = defaulted();
7496
+ if (customer) first.setCustomer(customer);
7497
+ return first;
7498
+ });
7456
7499
  const builderNow = useRef4(rendered);
7457
7500
  const applied = useRef4(/* @__PURE__ */ new Map());
7458
7501
  const appliedWith = useRef4(null);
@@ -7496,7 +7539,7 @@ function useSale(settings, opts) {
7496
7539
  if (active) setError(SALE_SAVING);
7497
7540
  return active;
7498
7541
  }
7499
- function resetSale(customer, restored) {
7542
+ function resetSale(customer = defaulted(), restored) {
7500
7543
  if (inFlight.current && !pending.current) return setError(SALE_SAVING);
7501
7544
  if (pending.current && confirmed.current !== pending.current) {
7502
7545
  if (inFlight.current) checkStored(pending.current);
@@ -7528,7 +7571,9 @@ function useSale(settings, opts) {
7528
7571
  useLayoutEffect(() => {
7529
7572
  const live = builderNow.current.getSnapshot();
7530
7573
  const liveIdle = stageNow.current.kind === "cart" && !live.lineItems.length && !live.fees?.length && !live.shipping?.length && !inFlight.current && !pending.current;
7531
- if (liveIdle && (madeWith.current.taxContext !== taxContext || madeWith.current.currency !== settings.currency)) resetSale(live.customer ?? null);
7574
+ const newDefault = defaultSeen.current !== defaultKey;
7575
+ defaultSeen.current = defaultKey;
7576
+ if (liveIdle && (newDefault || madeWith.current.taxContext !== taxContext || madeWith.current.currency !== settings.currency)) resetSale(newDefault ? void 0 : live.customer ?? null);
7532
7577
  });
7533
7578
  useEffect8(() => () => {
7534
7579
  clearHungSaveTimer();
@@ -7967,7 +8012,7 @@ function useSale(settings, opts) {
7967
8012
  * updates or requeues `pos_orders` itself.
7968
8013
  */
7969
8014
  newSale() {
7970
- resetSale(null);
8015
+ resetSale();
7971
8016
  },
7972
8017
  /** Parks the cart in `drafts`; resolves to a refusal message, or null once parked. */
7973
8018
  async park() {
@@ -7979,7 +8024,7 @@ function useSale(settings, opts) {
7979
8024
  if (!snapshot.lineItems.length && !snapshot.fees?.length && !snapshot.shipping?.length) return "There is nothing to park";
7980
8025
  await writeOrderDraft(opts.drafts, snapshot);
7981
8026
  if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return "The sale changed while it was being parked; park it again";
7982
- resetSale(null);
8027
+ resetSale();
7983
8028
  return null;
7984
8029
  },
7985
8030
  /** Resumes a draft into an empty cart; resolves to a refusal message, or null once resumed. */
@@ -8062,7 +8107,7 @@ function useSale(settings, opts) {
8062
8107
  await writeOrderDraft(opts.drafts, snapshot);
8063
8108
  if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return "The sale changed while it was being parked; park it again";
8064
8109
  }
8065
- resetSale(null);
8110
+ resetSale();
8066
8111
  return draftId === null ? null : result.resume(draftId);
8067
8112
  },
8068
8113
  /** Discards the current sale (nothing is parked) and starts an empty one; refused while saving, once a leg of an unfinished sale took or holds money, or in the tender stage. */
@@ -8071,7 +8116,7 @@ function useSale(settings, opts) {
8071
8116
  const { payments } = builderNow.current.getSnapshot();
8072
8117
  if (stageNow.current.kind !== "receipt" && (capturedMinor(payments) > 0 || payments.some(isInMotion))) return SALE_PARTLY_PAID;
8073
8118
  if (stageNow.current.kind === "tender") return SALE_IN_TENDER;
8074
- resetSale(null);
8119
+ resetSale();
8075
8120
  return null;
8076
8121
  },
8077
8122
  /**
@@ -8127,10 +8172,10 @@ __export(woocommerce_exports, {
8127
8172
  });
8128
8173
 
8129
8174
  // src/sale/woocommerce/discount-codes.ts
8130
- import { minorUnitDigits as minorUnitDigits5, woocommerceCoupons as woocommerceCoupons3 } from "@tallyui/core";
8175
+ import { minorUnitDigits as minorUnitDigits6, woocommerceCoupons as woocommerceCoupons3 } from "@tallyui/core";
8131
8176
 
8132
8177
  // src/sale/woocommerce/coupons.ts
8133
- import { minorUnitDigits as minorUnitDigits4 } from "@tallyui/core";
8178
+ import { minorUnitDigits as minorUnitDigits5 } from "@tallyui/core";
8134
8179
  function couponRefusal(code, rejection) {
8135
8180
  switch (rejection.code) {
8136
8181
  case "already_applied":
@@ -8158,7 +8203,7 @@ function couponRefusal(code, rejection) {
8158
8203
  }
8159
8204
  }
8160
8205
  function couponLineItems(lines, currency, categories) {
8161
- const digits = minorUnitDigits4(currency), factor = 10 ** digits;
8206
+ const digits = minorUnitDigits5(currency), factor = 10 ** digits;
8162
8207
  return lines.flatMap((line, lineIndex) => {
8163
8208
  if (line.unitPriceMinor < 0) return [];
8164
8209
  const id2 = Number(line.productId), product_id = !line.custom && Number.isSafeInteger(id2) && id2 >= 0 ? id2 : 0;
@@ -8194,7 +8239,7 @@ function createDiscountCodes(source) {
8194
8239
  lineItems: couponLineItems(snapshot.lineItems, snapshot.currency, sale.categories),
8195
8240
  appliedCoupons: [...sale.accepted.keys()],
8196
8241
  appliedCouponsWithIndividualUse: [...sale.accepted].filter(([, value]) => value.individual_use).map(([key]) => key),
8197
- cartSubtotal: snapshot.display.subtotalMinor / 10 ** minorUnitDigits5(snapshot.currency),
8242
+ cartSubtotal: snapshot.display.subtotalMinor / 10 ** minorUnitDigits6(snapshot.currency),
8198
8243
  customerEmail: snapshot.customer?.email ?? "",
8199
8244
  customerId: wooCustomerId(snapshot.customer),
8200
8245
  now: Date.now()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/pos",
3
- "version": "3.17.0",
3
+ "version": "3.18.0",
4
4
  "type": "module",
5
5
  "description": "Shared POS business logic for Tally UI — tax, orders, payments, discounts, receipts",
6
6
  "main": "./dist/index.js",
@@ -34,20 +34,20 @@
34
34
  "mustache": "^4.2.0"
35
35
  },
36
36
  "peerDependencies": {
37
- "@tallyui/core": "^3.17.0",
37
+ "@tallyui/core": "^3.18.0",
38
38
  "react": ">=18",
39
39
  "rxdb": "~17.5.0",
40
40
  "rxjs": ">=7"
41
41
  },
42
42
  "devDependencies": {
43
- "@tallyui/core": "3.17.0",
43
+ "@tallyui/core": "3.18.0",
44
44
  "@types/react": ">=18",
45
45
  "react": "^19.2.4",
46
46
  "rxdb": "17.5.0",
47
47
  "rxjs": "7.8.2",
48
- "@tallyui/connector-medusa": "3.17.0",
49
- "@tallyui/connector-woocommerce": "3.17.0",
50
- "@tallyui/database": "3.17.0"
48
+ "@tallyui/connector-medusa": "3.18.0",
49
+ "@tallyui/connector-woocommerce": "3.18.0",
50
+ "@tallyui/database": "3.18.0"
51
51
  },
52
52
  "scripts": {
53
53
  "build": "tsup",
@@ -1,10 +1,12 @@
1
1
  import { createContext, useContext, useMemo, useCallback } from 'react';
2
2
  import type { ReactNode } from 'react';
3
3
  import { formatMoney, type Money } from '@tallyui/core';
4
+ import { formatMoneyWith, type CurrencyFormat } from './format-money-with';
4
5
 
5
6
  interface CurrencyContext {
6
7
  currencyCode: string;
7
8
  locale?: string;
9
+ format?: CurrencyFormat;
8
10
  }
9
11
 
10
12
  const CurrencyCtx = createContext<CurrencyContext | null>(null);
@@ -12,11 +14,13 @@ const CurrencyCtx = createContext<CurrencyContext | null>(null);
12
14
  export interface CurrencyProviderProps {
13
15
  currencyCode: string;
14
16
  locale?: string;
17
+ /** The store's own money format; without it, money reads as Intl formats it for `locale`. */
18
+ format?: CurrencyFormat;
15
19
  children: ReactNode;
16
20
  }
17
21
 
18
- export function CurrencyProvider({ currencyCode, locale, children }: CurrencyProviderProps) {
19
- const value = useMemo(() => ({ currencyCode, locale }), [currencyCode, locale]);
22
+ export function CurrencyProvider({ currencyCode, locale, format, children }: CurrencyProviderProps) {
23
+ const value = useMemo(() => ({ currencyCode, locale, format }), [currencyCode, locale, format]);
20
24
  return <CurrencyCtx.Provider value={value}>{children}</CurrencyCtx.Provider>;
21
25
  }
22
26
 
@@ -25,9 +29,12 @@ export function useCurrencyFormatter(): (money: Money) => string {
25
29
  if (!ctx) {
26
30
  throw new Error('useCurrencyFormatter() must be used within a <CurrencyProvider>');
27
31
  }
32
+ const { locale, format } = ctx;
28
33
  return useCallback(
29
- (money: Money) => formatMoney(money, ctx.locale) ?? `${money.amount} ${money.currency}`,
30
- [ctx.locale],
34
+ (money: Money) =>
35
+ (format ? formatMoneyWith(money, format, locale) : formatMoney(money, locale)) ??
36
+ `${money.amount} ${money.currency}`,
37
+ [locale, format],
31
38
  );
32
39
  }
33
40
 
@@ -0,0 +1,45 @@
1
+ import { minorUnitDigits, type Money } from '@tallyui/core';
2
+
3
+ /** A store's own money format (WCPOS v2 General settings); a field left out keeps the locale's. */
4
+ export interface CurrencyFormat {
5
+ position?: 'left' | 'right' | 'left_space' | 'right_space';
6
+ thousandSeparator?: string;
7
+ decimalSeparator?: string;
8
+ decimals?: number;
9
+ }
10
+
11
+ /**
12
+ * Money in a store's format, ported from WCPOS v2 (MIT): the position map of
13
+ * `packages/core/src/screens/main/hooks/use-currency-format.tsx` and the separators and places
14
+ * of `use-number-format.ts`. As there, the places are always shown, the integer is grouped every
15
+ * three digits, and a minus leads the symbol. The symbol is Intl's for the currency and locale.
16
+ * Returns undefined for 'XXX' or a code Intl refuses, so callers can fall back.
17
+ */
18
+ export function formatMoneyWith(money: Money, format: CurrencyFormat, locale?: string): string | undefined {
19
+ if (money.currency === 'XXX') return undefined;
20
+ const minor = minorUnitDigits(money.currency);
21
+ const decimals = format.decimals ?? minor;
22
+ const abs = Math.abs(money.amount);
23
+ // Fewer places round whole minor units half away from zero, so -12.50 and 12.50 read alike.
24
+ const major = decimals >= minor ? abs / 10 ** minor : Math.round(abs / 10 ** (minor - decimals)) / 10 ** decimals;
25
+ let parts: Intl.NumberFormatPart[];
26
+ try {
27
+ parts = new Intl.NumberFormat(locale, {
28
+ style: 'currency', currency: money.currency, minimumFractionDigits: decimals, maximumFractionDigits: decimals,
29
+ }).formatToParts(major);
30
+ } catch {
31
+ return undefined;
32
+ }
33
+ const text = (...types: string[]) => parts.filter((p) => types.includes(p.type)).map((p) => p.value).join('');
34
+ const { position, thousandSeparator, decimalSeparator } = format;
35
+ const integer = thousandSeparator === undefined
36
+ ? text('integer', 'group')
37
+ : text('integer').replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
38
+ const number = integer + (decimals > 0 ? (decimalSeparator ?? text('decimal')) + text('fraction') : '');
39
+ const symbol = text('currency');
40
+ const left = position
41
+ ? position.startsWith('left')
42
+ : parts.findIndex((p) => p.type === 'currency') < parts.findIndex((p) => p.type === 'integer');
43
+ const gap = position ? (position.endsWith('_space') ? ' ' : '') : text('literal');
44
+ return (money.amount < 0 && major > 0 ? '-' : '') + (left ? symbol + gap + number : number + gap + symbol);
45
+ }
@@ -1,2 +1,3 @@
1
1
  export { CurrencyProvider, useCurrencyFormatter, useCurrencyCode } from './currency-provider';
2
2
  export type { CurrencyProviderProps } from './currency-provider';
3
+ export type { CurrencyFormat } from './format-money-with';
package/src/index.ts CHANGED
@@ -10,7 +10,7 @@ export type { CsvColumn } from './csv';
10
10
 
11
11
  // Currency
12
12
  export { CurrencyProvider, useCurrencyFormatter, useCurrencyCode } from './currency';
13
- export type { CurrencyProviderProps } from './currency';
13
+ export type { CurrencyFormat, CurrencyProviderProps } from './currency';
14
14
 
15
15
  // Tax
16
16
  export { TaxProvider, useTax, taxLogger } from './tax';
@@ -47,6 +47,14 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
47
47
  registerId: string; cashierRef: string; capabilities?: ServerCapabilities;
48
48
  /** The platform's discount codes (ADR-077 amendment 3), e.g. woocommerceDiscountCodes.createDiscountCodes(source); without them, applyCoupon refuses with COUPONS_UNSUPPORTED. */
49
49
  discountCodes?: SaleDiscountCodes<any>;
50
+ /**
51
+ * Put on every new sale, as v2's store setting `default_customer` (or the cashier, `default_customer_is_cashier`)
52
+ * is on every new cart: the first sale and each one after complete, discard, park, newSale or a switch to New,
53
+ * never a resumed one. The app resolves which customer. A cashier's change, Guest included, stays on that sale.
54
+ * A change applies at once to an idle cart, else to the next new sale. One `setCustomer` would refuse is skipped
55
+ * (the sale starts on guest, with no error).
56
+ */
57
+ defaultCustomer?: CustomerSummary | null;
50
58
  /** Where `park()` keeps parked carts; create it with `orderDraftSchema` */
51
59
  drafts?: RxCollection;
52
60
  /**
@@ -75,7 +83,19 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
75
83
  }) {
76
84
  const taxContext = useTax();
77
85
  const madeWith = useRef({ taxContext, currency: settings.currency });
78
- const [rendered, setBuilder] = useState(() => createOrderBuilder({ currency: settings.currency, taxContext }));
86
+ // The default customer for a new sale, unless the server would refuse it: then the sale starts on guest.
87
+ function defaulted(): CustomerSummary | null {
88
+ const customer = opts.defaultCustomer ?? null;
89
+ return customer && !customerRefusal(customer) ? customer : null;
90
+ }
91
+ const defaultKey = opts.defaultCustomer ? JSON.stringify([opts.defaultCustomer.id, opts.defaultCustomer.name, opts.defaultCustomer.email]) : '';
92
+ const defaultSeen = useRef(defaultKey);
93
+ const [rendered, setBuilder] = useState(() => {
94
+ const first = createOrderBuilder({ currency: settings.currency, taxContext });
95
+ const customer = defaulted();
96
+ if (customer) first.setCustomer(customer);
97
+ return first;
98
+ });
79
99
  // The live builder, which every mutator reads (#301): newSale() sets it before setBuilder(next) renders, so a
80
100
  // call from an older render never reaches a discarded builder. The state only moves the `order` subscription.
81
101
  const builderNow = useRef(rendered);
@@ -136,8 +156,8 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
136
156
  if (active) setError(SALE_SAVING);
137
157
  return active;
138
158
  }
139
- // newSale()'s body (see its doc comment for the guards): `newSale()` is `resetSale(null)`.
140
- function resetSale(customer: CustomerSummary | null, restored?: OrderBuilder) {
159
+ // newSale()'s body (see its doc comment for the guards): `newSale()` is `resetSale()`, on the default customer.
160
+ function resetSale(customer: CustomerSummary | null = defaulted(), restored?: OrderBuilder) {
141
161
  if (inFlight.current && !pending.current) return setError(SALE_SAVING);
142
162
  if (pending.current && confirmed.current !== pending.current) {
143
163
  if (inFlight.current) checkStored(pending.current);
@@ -170,10 +190,13 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
170
190
  const idle = stage.kind === 'cart' && !order.lineItems.length && !order.fees?.length && !order.shipping?.length;
171
191
  // A layout effect, on live idleness (#301): it runs inside the settings' commit, before any tap can be handled, and
172
192
  // the rendered `idle` would miss a line added since this render (it would then be dropped with the old builder).
193
+ // A new default customer starts a new sale on it at once when idle, as v2 seeds its new cart again; never held pending.
173
194
  useLayoutEffect(() => {
174
195
  const live = builderNow.current.getSnapshot();
175
196
  const liveIdle = stageNow.current.kind === 'cart' && !live.lineItems.length && !live.fees?.length && !live.shipping?.length && !inFlight.current && !pending.current;
176
- if (liveIdle && (madeWith.current.taxContext !== taxContext || madeWith.current.currency !== settings.currency)) resetSale(live.customer ?? null);
197
+ const newDefault = defaultSeen.current !== defaultKey;
198
+ defaultSeen.current = defaultKey;
199
+ if (liveIdle && (newDefault || madeWith.current.taxContext !== taxContext || madeWith.current.currency !== settings.currency)) resetSale(newDefault ? undefined : live.customer ?? null);
177
200
  });
178
201
  // A screen that unmounts (medusapos: Sign out) mid-save must still leave a trace of the loss.
179
202
  useEffect(() => () => {
@@ -572,7 +595,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
572
595
  * clears the screen, never the record (the Front desk, 2026-09-25). `newSale()` never deletes,
573
596
  * updates or requeues `pos_orders` itself.
574
597
  */
575
- newSale() { resetSale(null); },
598
+ newSale() { resetSale(); },
576
599
  /** Parks the cart in `drafts`; resolves to a refusal message, or null once parked. */
577
600
  async park(): Promise<string | null> {
578
601
  if (locked()) return SALE_SAVING;
@@ -583,7 +606,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
583
606
  if (!snapshot.lineItems.length && !snapshot.fees?.length && !snapshot.shipping?.length) return 'There is nothing to park';
584
607
  await writeOrderDraft(opts.drafts, snapshot);
585
608
  if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return 'The sale changed while it was being parked; park it again';
586
- resetSale(null);
609
+ resetSale();
587
610
  return null;
588
611
  },
589
612
  /** Resumes a draft into an empty cart; resolves to a refusal message, or null once resumed. */
@@ -662,7 +685,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
662
685
  await writeOrderDraft(opts.drafts, snapshot);
663
686
  if (builderNow.current !== builder || builder.getSnapshot() !== snapshot) return 'The sale changed while it was being parked; park it again';
664
687
  }
665
- resetSale(null);
688
+ resetSale();
666
689
  return draftId === null ? null : result.resume(draftId);
667
690
  },
668
691
  /** Discards the current sale (nothing is parked) and starts an empty one; refused while saving, once a leg of an unfinished sale took or holds money, or in the tender stage. */
@@ -671,7 +694,7 @@ export function useSale(settings: Pick<StoreSettings, 'currency' | 'calcDiscount
671
694
  const { payments } = builderNow.current.getSnapshot();
672
695
  if (stageNow.current.kind !== 'receipt' && (capturedMinor(payments) > 0 || payments.some(isInMotion))) return SALE_PARTLY_PAID;
673
696
  if (stageNow.current.kind === 'tender') return SALE_IN_TENDER;
674
- resetSale(null);
697
+ resetSale();
675
698
  return null;
676
699
  },
677
700
  /**