Skip to content
Eduardo Santarosa
PT Português
All case studies

Own product

AuthSales, business management on a reusable foundation

My personal project, developed in the boilerplate repository: a multi-company SaaS connecting sales, POS, inventory, finance and services, with a foundation that other systems can also use.

Responsible for architecture and full stack development: API, interface, data modeling, business rules and validation infrastructure.

Multi-company and multi-store SaaS · optional modules · foundation published as packages

Conceptual illustrations with made-up data. They do not depict the real infrastructure.

The problem

A sale changes stock, creates receivables and may earn commission. A service order adds parts, technicians and equipment. Building these modules alone meant defining who can perform each operation, which store owns its effects and how to undo an action while preserving its history.

Half-done writes

An order with no audit entry, and no other system heard about it.

Another account's data

A user from Account A looking at an order from Account B.

Copied code

A fix made in one system never reaches the copies.

How it works

Product and reusable foundation

AuthSales is the business management application I develop in the boilerplate monorepo. It covers a company that sells products, provides services, manages stock and tracks finances. The same repository holds the reusable engine behind those operations: authentication, authorization, account and store context, CRUD, audit and asynchronous processing.

That separation carries through to the packages. Backend, frontend and shared types have their own contracts so another system can use the infrastructure and implement its domain. The business modules remain application code. The standalone consumer example exercises public package entrypoints instead of importing internal monorepo files. This lets the foundation change without forcing every consumer to follow its folder structure.

Within the product, system and registry form the account foundation. Commercial, finance, service orders and Service Desk have availability and access controlled by the module catalog. A technical dependency on a financial projection does not require the customer to subscribe to financial screens: a service order can maintain its receivables internally and remain useful as an independent module.

Consider a store that negotiates a quote, confirms the sale and receives part of the amount. Stock records the outgoing goods and the rest remains receivable. If the customer returns an item, the system must adjust debt, goods and commission release while retaining the source of each effect. Amounts and scenarios in this case study's examples are fictional.

Shared records, stores and access

Customers, suppliers, employees and carriers are shared records used by commercial documents. Products and services add units, variants, prices and classifications. Payment methods, categories and cost centers give financial entries context. A record can be shared within the account while being available for use only in selected stores.

This distinction keeps multi-company behavior from becoming a screen filter. A customer may exist in the account yet be unavailable for a sale in the active store; a product can share its master data while having different balances at each location. The server checks both ownership and availability in the document's context. Relations selected through pickers undergo the same checks when saved.

OperationContext carries the actor, account, store and other information resolved for that operation. Each resource declares a Data Scope policy, denied by default. Its authorized predicate accompanies reads, search, exports and writes. A known identifier or a companyId supplied by the browser cannot replace that authority, and a record from another account answers as not found.

Access to a screen also differs from permission to make an exception. Reading a sale does not grant permission to override a price, assign another seller or authorize credit. Reading a ticket does not grant unrestricted access to related customer and user data. The interface reflects those capabilities; the service still enforces them when a command arrives through another path.

Quotes and sales

A quote brings together the customer, products, services, discounts, freight and payment terms. Quotes and sales share a commercial document engine that centralizes calculations, installments, history, sharing and PDF. Each document declares its fields, situation catalogs and specific behavior. A calculation fix therefore does not need repeating across product and service screens.

The backend calculates totals and checks the terms: positive quantities, discounts within the permitted amount, and installments whose sum matches the document exactly. Conversion carries negotiated terms into the new sale. If the quote agreed on payment thirty days after issue and the sale takes place weeks later, the default policy shifts due dates by the gap between issue dates, preserving manually edited intervals as well.

Preparing a conversion opens a draft for review. Confirmation reads and locks the quote again in the transaction that creates the sale or service order, persists its source link, records history and schedules the event. The setting that offers conversion is separate from the one identifying the converted quote's destination situation. Persisted links and uniqueness constraints prevent concurrent confirmations from creating duplicate destinations.

For a sale, the DONE situation code defines economic effectiveness. Custom names and colors remain presentation. The sale adapter plans stock, receivable and commission effects; the responsible services apply them in the document's unit of work. A financial failure also rolls back that attempt's stock effects. Leaving the effective situation goes through the corresponding reversal.

A return considers what is still owed and what has already been received. For a R$120 sale with R$50 received and R$70 outstanding, an eligible R$100 return can offset the R$70 debt and create a R$30 refund obligation. The offset reduces debt without inventing a bank inflow or outflow; paying the refund has its own record. Concurrent returns are serialized through the source sale so the same received amount cannot fund two refunds.

POS and cash register closure

POS concentrates counter sales: items, seller, discounts, payments and receipt within an open register. It uses the platform's commercial and financial services. Price overrides, discounts and assigning another seller require specific capabilities, and the server checks the preview's prices and totals.

Checkout coordinates the sale, stock, receivables, settlements and register movements in one transaction. The idempotency key identifies the intent: repeating the same operation returns its persisted result; reusing the key with different content conflicts. If communication fails after commit, a retry does not create another sale. The receipt describes internally recorded payments without claiming that a card or PIX payment was processed externally.

Credit limits use the customer's outstanding balance within the account and store. Consider a R$500 limit, R$450 already used, and a new R$100 sale with R$80 received during checkout: the remaining R$20 takes exposure to R$470. The service locks the customer and checks exposure after receipts in that transaction. If the limit must be exceeded, policy may require the credit authorization capability and an audited reason.

Closure can use a blind count: public responses for an open register omit expected balance and movements. Once a count is supplied, the server calculates the comparison by payment method. A discrepancy may require confirmation and, depending on account policy, specific approval. Confirmation is bound to the count, actor, store and movements considered; a movement after the preview requires another review.

Opening with R$100, a R$50 sale and a R$20 withdrawal gives an expected R$130. Counting R$125 records a R$5 shortage and closes at R$125. The closure snapshot preserves totals, payment methods, operator, policy and any approver. CLOSED is terminal in the current flow, and sales or reversals cannot append register movements afterward. Payment methods represent the consolidated register, including internal receipts classified as cash, PIX or card.

Purchasing and cost calculation

Purchasing brings together supplier quotations and acquisition documents, with products, services, situations and payables. The applied situation determines a purchase's effects. Confirming incoming goods coordinates stock and finance; a document that has not taken effect must not increase available stock or appear as money already spent.

Master cost follows an account rule: retain the value, use the latest purchase cost or calculate a weighted average. Ten units at R$10 plus ten incoming units at R$14 gives an average of R$12, while the latest-purchase rule gives R$14. The calculation uses stock before the incoming movement and the same decimal arithmetic as the preview.

When the rule retains cost and there is a significant divergence, the operator can review products and choose how to handle that purchase. Preview values are protected: the service requires cost-view permission before exposing them. Confirmation is signed and bound to the command, context and presented numbers. Changed conditions invalidate the earlier decision instead of silently applying a choice made for another situation.

Incoming stock, cost updates, obligations and audit share the document transaction. Cancellation offsets the purchase postings but does not restore an old master cost: later purchases may have updated it. Historical movements preserve their source and cost; the master record represents the current value. This separation prevents a late cancellation from rewriting subsequent cost calculation.

Stock, transfers and inventory counts

Stock keeps a ledger of incoming, outgoing and reversing movements per store. A simple product has its own balance bucket; a product with variants has a balance per SKU. Sale units can differ from stock units, so conversion happens before availability is compared or a movement is recorded. Every line retains the source explaining its contribution to the balance.

The insufficient-availability policy can allow, block or require confirmation. The server aggregates demand for the same product or SKU and considers physical balance and reservations. Warning confirmation presents the shortage and projected balance and requires acceptance bound to that operation. The decision is checked again under a lock; a balance supplied by the browser cannot prove availability. Acceptance and movements are audited in the same transaction.

A transfer requires authority in both stores and records the movement pair together. If a box equals ten units and the source holds twelve, transferring two boxes requires twenty and is refused. Completion freezes converted quantity and cost. Cancellation produces movements opposite to the original pair while retaining subsequent sales. A transfer creates no payable or receivable because the goods still belong to the same account.

Inventory counts have draft, counted and completed stages. Counting captures system balance, unit and cost and computes the difference from the quantity found. If the system held ten and the count found eight, the difference is fixed at minus two. If a sale of two occurs before completion, balance reaches eight; applying the recorded difference takes it to six, preserving both the sale and the physical discrepancy.

Capture uses a consistent transactional read, including products with no balance row yet. Completion turns nonzero differences into movements; repeating the command does not post everything again. Reopening a completed count offsets movements from the earlier completion and requires a reason. Manual adjustment remains a separate operation: the operator enters how much to add or remove, while an inventory count records how much was found.

Finance and payment history

Finance organizes payables and receivables, installments, bank accounts, cash registers, payment methods, categories and cost centers. Each financial entry represents an obligation with amount, origin, accrual date and due date. Settlements form a separate history of money applied to the obligation. Cash and accrual reports answer different questions and use these sources according to their meaning.

A R$120 receivable can receive R$50 and retain R$70 outstanding. Interest, fines and discounts belong to the settlement: applying R$50 of principal with a R$5 discount moves R$45 and reduces outstanding principal by R$50. Calculations use exact cents; adjustments do not rewrite the original obligation. The operator can review suggested charges before confirming.

Settlement locks the financial entry before calculating balance and updates the bank account in the same unit of work. Two requests trying to apply R$70 to a R$100 receivable cannot consume the same available balance. The idempotency key and normalized content identify the operation; repeating the key with another amount conflicts. Paid or partially paid status is a projection of persisted events.

Reopening undoes receipts through reversal events and restores the open balance. Cancellation declares that the obligation is no longer owed. A manual entry with active money applied must be reopened first; an entry generated by a sale, purchase or service order retains its source document's authority over cancellation. Permission to settle in Finance does not transfer that authority.

Each materialized installment has its own financial entry and history. A plan with settlements cannot be rebuilt by erasing what happened. Generated entries pass through FinancialPostingService and retain source keys, including installment identity. Synchronization can therefore find the same entry and preserve historical descriptions and events instead of creating another obligation on retry.

Service orders and equipment

A service order organizes technical work with customer, equipment, parts, services, technicians and payment terms. It can originate from a quote and follow an account-defined situation catalog. Each situation declares whether editing is allowed, parts are reserved or moved, and financial entries are generated. A visual stage such as waiting for parts can carry a different consequence from completed work according to explicit configuration.

The engine interprets situation actions during a transition and calculates the difference between previous and new states. Parts and receivable effects use canonical stock and finance services. The server checks permissions and resource availability. The transition screen receives an explanation of effects, including receipts that would need reversal, before executing the command.

Equipment history derives from occurrences in the customer's service orders within the authorized store. A normalized serial number groups equivalent spellings; without one, name, brand and model form the identity. The customer is part of that identity: the same serial text under two customers does not merge their histories. Choosing a suggestion copies data into the new occurrence while preserving earlier text, including cancelled orders.

The aging report distinguishes time since opening from time in the current situation. An order opened twelve days ago and moved to a new stage today has twelve opening days and zero in that situation. The calculation reads transition history with an explicit opening fallback, rather than a generic last-edit timestamp. When an order contains several pieces of equipment, parts and service totals remain order totals, without allocating costs that item rows do not identify per piece of equipment.

Contracts, billing and renewal

Contracts maintain term, situation, recurrence rules, billing generation and termination. Configuration defines when to produce a cycle and its effects, such as a sale or receivable. Pausing billing, terminating a contract and renewing its term are distinct decisions; processing does not infer one merely because a date arrived.

Cycles use persisted outbox events and an identity per contract and sequence. On execution, the worker reads and locks the contract again, compares expected due date and sequence, and checks its current situation. An event scheduled before an edit cannot bill according to the old version. Redelivery finds an already processed cycle, and source keys on its documents prevent duplication.

Renewal preserves the historical start and calculates the new end from the previous end. Month arithmetic handles civil dates and month ends: in a non-leap year, a January 31 end can advance to February 28. Scheduling considers the store's business day and timezone. Automatic events use a system identity so the trail does not attribute a future renewal to someone who only edited the contract months earlier.

If a worker was stopped, the durable event still exists for processing. Execution continues to check eligibility and may find a suspended, terminated or already renewed contract. Cycle tests need to inspect generated documents and receivables, the next-billing pointer and retry behavior. The existence of this internal flow does not mean a gateway is charging the customer externally.

Seller and technician commissions

Sales and service orders share a commission ledger per line and beneficiary. A sale considers its seller; a service order considers its technicians. Posting freezes the net base, percentage, percentage source and release rule. Document discount is allocated across lines; freight and other additions stay outside the commissionable base. A later master-data change does not recalculate the past.

Commission can be released on financial generation, full payment of the first or last installment, or proportionally to principal received. Under the proportional rule, a R$100 base at 10% accrues R$10; if half the eligible principal was received, R$5 is released. Reversing that receipt makes the share pending again. Offsetting debt through a return does not count as money received.

Reconciliation runs inside the document transaction and records accruals and reversals with unique keys per source, line, beneficiary and cycle. Release is derived from settlements, avoiding a second balance that could become stale. With several technicians, a deterministic rule splits the base and allocates remaining cents. Even the absence of a usable percentage is frozen as policy so a future master-data edit cannot create retroactive commission.

A converted quote cannot earn commission simultaneously through two legacy destinations. Reconciliation uses a per-quote lock when deciding between documents. Reports group by beneficiary, document, product or service, respect account, store and currency, and support export. The module tracks entitlement and release; commission payment and payroll remain outside this control.

Service Desk and support history

Service Desk organizes tickets, assignees, categories, channels, comments and custom fields. A ticket can link a customer available in the store or record a manual requester. Channel and direction are separate: phone describes the medium; inbound or outbound describes who initiated contact. The center presents indicators and tickets within the authorized scope.

The account creates situation names and colors mapped to open, in progress, waiting for customer, resolved and closed behaviors. Moving between situations with the same behavior still records history without inventing another start or resolution. A situation referenced by tickets or history retains its behavior. Start, resolve and reopen actions retain defined destinations.

A transition carries the expected state and conflicts if another operator already changed the ticket. Creation and changes append immutable events in the same transaction. Requester contact is a snapshot: editing another field does not silently replace the recipient because the customer record changed. Internal notes and history observations remain internal; sending a public reply after resolution requires reopening the ticket.

Permission to edit a ticket does not grant every comment permission. The service locks the parent and persisted comments before classifying created, changed or removed content and enforcing the corresponding capability. The center summary uses an explicit field selection so complete relations cannot bring data from other resources. Concurrency tests observe competition for records and check that transitions and edits cannot leave inappropriate public content after closure.

Shared screens and extensions

Forms, tables, filters, pickers and actions are composed through shared metadata and contracts. Each module registers fields and adds interfaces for operations needing more context, such as converting a quote, closing a register or counting stock. Common infrastructure handles state, presentation and contract execution; commercial decisions stay in the domain that owns them.

Imports, exports, PDF, email, translation and themes share common paths. Contextual help, hints, checklists and tours use declared programs filtered by session modules and permissions. The same user can receive different guidance in two accounts or stores because the authorized context changed. The interface does not need a second copy of access rules to decide which actions to offer.

The extension SDK declares versioned manifests, contributions, commands and events. Validators check identifiers, dependencies, configuration and content. Event publication uses the existing unit of work and outbox; account and actor come from server context. The contract does not authorize loading arbitrary code or turn an extension declaration into a complete runtime.

The CRUD evolution preserved public signatures for over a hundred services while separating reads, field policy and scope. To investigate a commercial command, audit connects actor, transition and planned effects with records actually changed in stock and finance. A replay without effects creates no further success evidence. Domain tests, PostgreSQL integration tests and browser journeys check those boundaries; that infrastructure does not replace running and assessing each delivery's scenarios.

Outcome

AuthSales brings commercial operations and their stock, financial and service effects onto shared infrastructure. Other systems can use the foundation, and the CRUD evolution preserved the public signatures of over a hundred services.

Technical details

Decisions

  • One transaction for the document's effects

    CrudUnitOfWork coordinates writes, audit, idempotency and outbox. Sale, purchase and service order adapters plan effects; stock and finance retain ownership of their postings. A failure rolls back the whole operation.

  • Authorization inside business rules

    OperationContext and Data Scope resolve account, store and actor on the server. Sensitive commands check authorization and state again under a lock, covering calls that do not pass through the screen.

  • History through offsetting entries

    Settlements, stock movements and commissions preserve the original facts. Reversing or cancelling appends records linked to their source, so the system can reconstruct what happened and recognize a replay.

  • Explicit money, quantity and time semantics

    Financial calculations use decimals and exact cents; quantities respect units and conversions. Instants, civil dates, local times and durations have distinct contracts, so due dates and recurrence do not change with the process timezone.

  • Asynchronous work after commit

    Persisted outbox events drive subsequent effects and scheduled cycles. Email and PDF queues use existing infrastructure. Each consumer must recognize redelivery; a queue alone does not guarantee a single execution.

  • Validation beyond the HTTP response

    The repository has domain tests, PostgreSQL integration tests and Playwright journeys. Criteria include persisted balances, financial entries, history and isolation alongside API responses. Concurrency scenarios check what happens when two commands compete for the same record.

A real problem

Cancelling through a situation left the receivable open

The situation dialog wrote through a different path from document editing. Cancelling a sale there could leave its receivable open. The architectural fix routed these commands through the same unit of work and posting boundary, with a document lock, transactional effects and an audit of the records actually changed.

Limits and next steps

  • The current catalog includes commercial, finance, service orders and Service Desk. Fiscal is at pre-issuance, without validated transmission; projects, training, industrial, maintenance, facilities, quality, salon and document management remain outside the current launch.
  • External integration infrastructure and the SDK describe contracts. They do not, by themselves, represent operational bank connectors, payment gateway billing or fiscal issuance.
  • Commission tracking calculates and monitors entitlements and release; commission payments and payroll remain outside this module.
Next case studyPicking and checking orders on the warehouse floor without losing track