Shefa (شفى) — Core Technical Document
Nov 14, 2026 · @Elias
Overview
Shefa is a self-hosted platform for managing the pharmaceutical and medical system in Syria, organised by city. It starts with medicines and the pharmacy, then expands to doctors and medical centres. The first phase (MVP) covers three parties: the pharmacy, the drug warehouse, and the patient.
The document has two parts: Part One defines the roles and business logic, and Part Two defines the architecture and technologies.
Approved decisions
| Decision | Approved |
|---|---|
| MVP scope | Pharmacy + warehouse + patient. Doctors, pharmaceutical companies, medical centres and delivery are later phases |
| Offline operation | Only the pharmacy point-of-sale screen works offline and syncs later. All other screens are online |
| Drug catalogue | A central catalogue managed by the platform; organizations suggest missing items |
| Patient identity | Mobile number + a permanent Shefa ID. The national ID number is optional, for verification |
| Access to the medical record | With temporary permission from the patient via a QR or code, and every access is logged |
| Architecture | Modular Monolith that can be split later |
| Technologies | NestJS for the backend, React for the web, PostgreSQL for the database, Flutter for mobile in a later phase |
| Hosting | Fully self-hosted, with no dependency on managed cloud services |
Part One: Roles and Business Logic
Identity, Roles and Permissions
Each person has one account and one Shefa ID, and roles are granted through memberships that link the account to an organization and a role. The same person can be a patient, a pharmacist in one pharmacy, and a manager in another, and switches between these contexts after logging in.
Core concepts
- User: the person. Logs in with a mobile number and an OTP code; staff also have a password.
- Organization: a pharmacy, warehouse, pharmaceutical company, medical centre, or clinic. It belongs to one city and has a geographic location.
- Membership: user + organization + role. An organization can have more than one manager and more than one pharmacist.
- Permission: a fine-grained grant such as
inventory.adjustorpricing.bulk_update. Roles are ready-made sets of permissions, and the manager can customise them.
Roles
| Scope | Role | Main capabilities | Phase |
|---|---|---|---|
| Platform | System administrator | Full access: system settings, platform team accounts and their roles, cities, disabling any account or organization, the audit log | MVP |
| Platform | Operations manager | Oversees organization verification and city supervisors, tracks operating metrics, resolves disputes between organizations, public announcements | MVP |
| Platform | Support manager | Manages the support team and ticket assignment, approves sensitive actions, support quality reports | MVP |
| Platform | Support agent | Answers tickets, helps organizations with setup, restores account access. Does not change financial or inventory data | MVP |
| Platform | Drug catalogue supervisor | Adds items, reviews suggestions, and merges duplicates | MVP |
| Platform | City supervisor | Verifies organizations and reviews their licences within their city | MVP |
| Pharmacy | Pharmacy manager | Everything: staff, prices, purchasing, accounts, approving stock counts, statistics | MVP |
| Pharmacy | Pharmacist | All types of sales, receiving goods, stock counts, viewing a patient's record with their permission | MVP |
| Pharmacy | Trainee / assistant | Sells non-restricted items and counts during stock counts. Cannot change prices and cannot see purchase prices or patient records | MVP |
| Warehouse | Warehouse manager | Everything within the warehouse and its sub-stores | MVP |
| Warehouse | Storekeeper | Receiving, order preparation, transfers between stores, stock counts | MVP |
| Warehouse | Warehouse sales rep | Visits pharmacies, presents offers and takes orders, collects payments, delivers medicines from their custody | MVP |
| Warehouse | Accountant | Invoices, payments, account statements | MVP |
| Pharmaceutical company | Company manager | Scientific offices, reps and their territories, distribution plans, reports | Later |
| Pharmaceutical company | Scientific office keeper | Sample stock in the office, issuing samples to reps, stock counts | Later |
| Pharmaceutical company | Medical rep | Collects samples from the scientific office and distributes them free of charge to doctors on regular rounds | Later |
| Patient | Patient | Their record, reminders, the map, granting and revoking access permissions | MVP |
| Patient | Dependent | A profile for a child or elderly person managed by the guardian account holder | MVP |
| Clinic | Doctor, secretary | The record with permission, prescriptions, appointments. The secretary handles appointments only | Later |
| Medical centre | Centre manager, on-duty doctor | Services and shifts | Later |
| Delivery | Delivery driver | Home delivery of medicines and services | Later |
Organization verification
- The organization owner registers, enters the details and location, and uploads a photo of the licence.
- The city supervisor reviews it and approves or rejects it with a reason.
- After approval, the organization appears on the map and in the warehouse catalogue.
Permission to access the medical record
- The patient generates a QR or a short code from their app, and the pharmacist or doctor scans it.
- The permission has a scope (medicines and allergies only, or the full record) and a duration that expires automatically. Proposed: 30 minutes for a pharmacist, and a duration chosen by the patient for the treating doctor.
- The patient sees a list of who viewed their record and when, and can revoke any permission at any time.
- Trainees and secretaries do not receive medical record permissions.
Platform Administration: System, Operations and Support
The platform team has three levels with separate permissions: the system administrator owns settings and permissions, the operations manager owns the day-to-day workflow of organizations, and the support manager owns the relationship with users. None of them reads a medical record, and everything they do is written to the audit log.
System administrator
- Creates platform team accounts and assigns their roles, and is the only one who can grant the system administrator role to someone else.
- Manages general system settings: cities and governorates, organization types, default alert values, message templates, keys for external services.
- Disables or reactivates any account or organization, with a recorded reason.
- Views the full audit log and the system and monitoring status.
- Their account is protected by mandatory two-step verification, and the number of system administrators is limited and reviewed periodically.
Operations manager
- Oversees city supervisors and drug catalogue supervisors, and approves or reviews their decisions when they are disputed.
- Tracks the verification queue for new organizations and the waiting time in it.
- Sees an operations dashboard: active organizations per city, orders between warehouses and pharmacies, organizations that have stopped using the platform, pending catalogue suggestions.
- Rules on disputes between two organizations, such as a disagreement over receiving an order or over an unconfirmed payment, and for this sees only the two parties' documents related to the dispute.
- Publishes public announcements and alerts to organizations or to a specific city.
- Sees aggregated figures, and does not see an organization's prices or detailed sales outside an open dispute.
Support
- Every user or organization opens a ticket from inside the app; it is classified by type and priority and assigned to a support agent.
- The support agent sees basic account data, the organization's status and the ticket history, and restores account access after verifying the owner.
- Impersonation: to inspect a problem inside an organization, support requests an assistance session that the organization manager approves. The session is read-only by default, time-limited, fully logged, and visible to the organization in its log.
- Support does not correct financial or inventory data directly: it is raised as a correction request that the support manager approves, and the organization carries it out or it is carried out through a documented reversing transaction.
- The support manager assigns tickets, tracks response and resolution times, and escalates to the operations manager or the technical team.
Separation of permissions
| Action | System administrator | Operations manager | Support manager | Support agent |
|---|---|---|---|---|
| Manage the platform team and its roles | Yes | No | No | No |
| System settings | Yes | No | No | No |
| Verify or suspend an organization | Yes | Yes | No | No |
| Rule on a dispute between two organizations | Yes | Yes | No | No |
| Manage and assign tickets | Yes | View | Yes | Own tickets only |
| Restore account access | Yes | No | Yes | Yes |
| Assistance session inside an organization with its approval | Yes | No | Yes | Yes |
| Approve a data correction request | Yes | Yes | Yes | No |
| Read a patient's medical record | No | No | No | No |
Central Drug Catalogue
The catalogue is a single reference for the whole platform, and every stock entry, offer and prescription points to an item in it. This is what makes it possible to search for a medicine across pharmacies, suggest alternatives, and detect interactions.
Structure
- Active ingredient: the scientific name and the therapeutic classification (ATC).
- Manufacturer: a central table; each pharmacy specifies the companies it deals with.
- Product: the brand name (Arabic and English), the company, the dosage form, the strength, the pack size, the sub-units of sale (box, strip, tablet), and one or more barcodes.
- Composition: links the product to its active ingredients with the concentration of each ingredient.
- Dispensing restrictions: over the counter, by prescription, by stamped prescription, or controlled (narcotic or psychotropic).
- Type: medicine, medical supply, medical device, supplement, cosmetic.
Alternatives and interactions
- Alternatives are calculated automatically: products with the same active ingredient, strength and dosage form.
- Interactions are stored between active ingredients with a severity level and a warning text. In the MVP the table is ready and the alert is simple when data is available; the smart engine is a later phase.
Suggesting a missing item
- The pharmacy or warehouse cannot find the item, so it suggests it with its name, barcode and company.
- The system creates a temporary item private to the organization, which it can use immediately without waiting.
- The catalogue supervisor approves it, merges it with an existing item, or rejects it.
- On approval or merge, all transactions on the temporary item move to the central item. The temporary item does not appear in patient search before that.
Prices
The catalogue holds an optional reference price (the official price, if there is one). The actual selling price and the purchase price are stored separately for each organization.
The Pharmacy
The pharmacy is the centre of the system: it manages its stock at the batch level, sells, buys from warehouses, and appears to patients on the map.
Profile and public visibility
- Geographic location, address, phone, and information about the responsible pharmacist.
- Opening and closing hours for each day, with exceptions for holidays.
- An on-call schedule (nights and holidays) by date, shown to patients as an "on-call pharmacy".
- Services defined by the pharmacist: blood pressure measurement, blood sugar measurement, injections, and others, with an optional price.
- Control over what is shown: the patient sees "available" or "not available" without quantities, and the pharmacist can hide items or categories. Controlled items are never shown to the public.
Inventory
- Every quantity is linked to a batch: batch number, expiry date, purchase price, source.
- Sales draw from the earliest-expiring stock first (FEFO), and selling expired stock is blocked.
- Selling by the box or by sub-unit (strip, tablet) with automatic quantity conversion.
- A minimum level for each item, an alert when stock falls below it, and a shortages list that turns into a purchase order with one click.
- Expiry alerts 90, 60 and 30 days ahead (configurable), and a disposal or return procedure for expired stock.
- Every change in quantity is recorded as a transaction that cannot be edited or deleted: purchase, sale, return, stock count adjustment, disposal. The balance is the sum of the transactions.
- Import of the initial stock from an Excel file when starting to use the system.
Sales
- Add items by barcode or by searching the brand name or active ingredient, with suggestions of available alternatives.
- Optional link to a patient via their Shefa ID or QR, so the dispensing is added to their record automatically.
- An item restricted to prescription requires pharmacist confirmation and a link to the prescription. A controlled item is entered in a special register with the patient's name, the doctor's name and the quantity.
- Substituting a prescribed medicine with an alternative is recorded with the reason and appears in the patient's record.
- Discounts, returns, credit sales with a customer debt ledger, and closing the shift with cash drawer reconciliation.
- Printing receipts and barcode labels.
- The point-of-sale screen works offline (details in the synchronisation section).
Purchasing and accounts with warehouses
- Browse the catalogue of every warehouse in the city: items, prices, offers, availability, and comparison of an item's price across warehouses.
- A purchase order to one or more warehouses, with tracking of its status.
- Receiving with matching: quantities, batches, expiry dates. Discrepancies are recorded and reported to the warehouse.
- Returns to the warehouse, and purchases from a source outside the system by manual entry.
- An account statement with each warehouse: invoices, financial payments, returns, and the balance due.
Pricing
- Immediate update by a percentage on all items, a company, a category, or a selected group.
- Preview of the new prices before applying them, with a rounding rule.
- A log of every price change: who changed it, when, and the previous value, with the ability to undo the last bulk update.
- The permission belongs to the manager by default and can be granted to the pharmacist.
Stock count and review
- Open a full or partial stock count (shelf, company, category).
- Count by barcode from more than one device at the same time.
- The system shows the differences between the counted and recorded stock by quantity and value.
- The manager approves, and adjustment transactions are created with the reason.
Staff shifts
A calendar in which the manager assigns the shifts of pharmacists and assistants, and each employee sees their own shifts. Sales are attributed to the employee and the shift.
Statistics
- Sales and profit by day, item, company, and employee.
- Best sellers, slow movers, and the stock turnover rate.
- Current stock value, and the value of what will expire within 90 days.
- Number of patients per medicine and per active ingredient, and chronic-medication patients expected to return this month.
- Unmet demand: medicines patients in the area searched for that were not available.
- Debt owed to warehouses and customer debts.
The Drug Warehouse
The warehouse sells to pharmacies only, and uses the same inventory engine as the pharmacy, with sub-stores, offers and running accounts added. It is a different party from the manufacturing pharmaceutical company; the company has its own section after this one.
Inventory
- A main warehouse and sub-stores, each store with its own balance, with documented transfers between stores.
- Batches, expiry dates, FEFO, expiry alerts and minimum levels, as in the pharmacy.
- Entering goods received from pharmaceutical companies manually or from an Excel file.
- Periodic stock counts with the same counting and approval cycle.
Catalogue and offers
- The warehouse decides what it shows to pharmacies: the item, the price, the minimum order, and the availability status.
- Quantity offers: a percentage discount, or a bonus such as 10 + 2.
- Package: several items in fixed quantities for a single price.
- Each offer has a validity period, an optional limited total quantity, and optional targeting of specific pharmacies or cities.
- A notification to pharmacies when a new offer is published, and clearance offers for items close to expiry.
Order cycle
- Draft: the pharmacy builds the cart from the catalogue or from the shortages list.
- Sent: the order reaches the warehouse.
- Confirmed: the warehouse confirms fully or partially, and the quantities are reserved. Or it rejects with a reason.
- Prepared: the storekeeper prepares the order and assigns the batches, and the invoice is issued.
- Dispatched: the goods have left the warehouse.
- Received: the pharmacy matches and receives, and the stock enters its inventory with its batches and dates without re-entry.
- Closed: after settling any discrepancies or returns.
Accounts and payments
- One running account between each warehouse and each pharmacy, which both parties see with the same figures.
- An invoice increases the debt. A financial payment (cash or transfer) and a medicine payment (returned goods) decrease it.
- A payment is recorded by one party and confirmed by the other; the system only records and does not execute electronic payments.
- A credit limit for each pharmacy set by the warehouse, and an alert when it is exceeded.
- Account statement by period, debt ageing, and PDF and Excel export.
Warehouse sales rep
The rep represents the warehouse in the field: visits pharmacies, presents offers, takes orders, collects money, and delivers medicines. Everything they do is recorded on the pharmacy's same running account, so there is no side ledger.
- Rounds: each rep has a list of pharmacies and a territory, and a periodic visit plan. A visit is recorded with the time, location and outcome.
- Offers and orders: the rep presents the warehouse's current offers and creates the order on behalf of the pharmacy from their mobile, and the pharmacy confirms it from its account or with a confirmation code.
- Medicine custody: the rep receives a quantity from the warehouse, which moves to a mobile store in their name, and then delivers from it to pharmacies. Each delivery issues an invoice and enters the pharmacy's stock with its batches, and whatever is not delivered returns to the warehouse with matching.
- Collection: the rep records the payment they received and issues a receipt, and the pharmacy confirms it. The amount remains cash in the rep's custody until they hand it over to the accountant and it is reconciled.
- Returns: the rep receives the return from the pharmacy, and it enters their custody and then the warehouse.
- Oversight: for each rep, the manager sees their medicine and cash custody, their visits, sales, and collections. A custody shortfall found at reconciliation is charged to the rep.
Statistics
Sales by pharmacy, item and city, offer performance, outstanding debt, slow movers, and the value of what will expire soon. The warehouse does not see the pharmacies' sales or stock.
The Pharmaceutical Company and the Scientific Office
The pharmaceutical company is a party independent of the warehouse: it does not sell to pharmacies through the system, and its role here is to promote its medicines by distributing free samples to doctors. It comes in with the doctor phase because distribution needs doctor accounts.
The scientific office
- The company has one or more scientific offices, each office in a city, and it is a small store for samples only.
- Sample stock is managed by the same inventory engine: batches, expiry dates, alerts, stock counts. A sample is an item from the central catalogue marked "free sample, not for sale".
- Samples do not appear to patients and do not enter any pharmacy's stock, and the system blocks selling them.
The medical rep
- The office keeper issues a quantity of samples to the rep, which moves into the rep's custody.
- The rep visits doctors within their territory and specialties according to a periodic visit plan set by the company.
- On each visit the rep records the doctor and the samples delivered and their quantities, and the doctor confirms receipt from their account or with a code.
- Whatever remains in custody is carried over to the next round or returned to the office with matching.
What the company sees
- Doctor coverage: who was visited and when, and who was not visited within the cycle.
- Samples distributed by item, rep, city and specialty, and each rep's custody.
- The company does not see patient records or the prescriptions of a specific doctor. Any statistics on the prescribing of its medicines are aggregated without names, and whether to offer them is an open decision.
The doctor's boundaries
The doctor decides whether they receive reps and at what times, and sees the log of samples they have received. Giving a sample to a patient is optionally recorded in the patient's record as a medicine dispensed by the doctor.
The Patient
The patient owns their medical record and controls who sees it, and uses the system for three things in the MVP: tracking their medicines, finding a medicine, and finding the nearest pharmacy.
Account and ID
- Registration with a mobile number and an OTP code. The national ID number is optional, for account verification.
- A permanent Shefa ID that does not change when the mobile number changes, short and easy to dictate, with a check digit, and shown as a QR in the app.
- Dependents: the account holder creates profiles for their children or for elderly people, each profile with its own Shefa ID.
- Profile without the app: the pharmacist creates a profile for a patient with their mobile number, and the patient claims it later when they register with the same number.
The medical record in the MVP
- Chronic diseases and allergies, entered by the patient.
- Current medicines: the medicine from the catalogue, the dose, the times, the start and end dates.
- Prescriptions: a photo uploaded by the patient in the MVP, which becomes digital from the doctor in the next phase.
- Dispensing history: added automatically when a pharmacy sells to the patient after scanning their ID, with any substitution recorded.
- The record structure is designed from now on to accept doctor visits, procedures and reports later without rebuilding.
Reminders
- A dose reminder at its time, with "taken" or "skipped" confirmation and an adherence log.
- A repurchase reminder: calculated from the dispensed quantity and the daily dose, and alerts a few days before the medicine runs out.
- In the Flutter app, reminders are scheduled locally on the device so they work without internet. Before the app is released, they work through web notifications, which are less reliable.
Map and search
- Nearby pharmacies sorted by distance, with "open now" and "on-call" filters.
- Searching for a medicine shows the pharmacies where it is available, and suggests alternatives if it is not available.
- Pharmacy page: the items shown, medical devices and supplies, services, opening hours, phone.
- Medicine reservation request: the patient requests and the pharmacist confirms and reserves the quantity for a set period.
Emergency
- One button that shows the nearest pharmacies open or on call right now, with direct calling and directions.
- The patient can send the name of the needed medicine to nearby pharmacies, and the first to confirm availability is shown to them.
- The screen shows emergency numbers and makes clear that the service is not a substitute for an ambulance.
Doctor, Medical Centre and Delivery (Later Phases)
These roles are outside the MVP, but the data and permissions model is built from now on to accommodate them.
The doctor
- Views the patient's record only with their permission: diseases, visits, surgical procedures, medicines with their quantities and times, and any medicine substitution, in chronological order.
- The names of other doctors are not shown. Only the specialty and the date are shown, and the hiding is enforced in the API, not in the UI.
- A unified report form for all specialties (the visit): complaint, diagnosis coded with ICD-10, procedures, prescription, attachments. Specialty-specific fields are added as a flexible template on top of the unified part.
- The digital prescription is stored in the system and printed for stamping, and carries a QR that the pharmacist verifies. The pharmacist dispenses against it, and it is marked as fully or partially dispensed.
- An appointments calendar with patient names; clicking an appointment opens the record if permission exists.
- The patient sees the available times and books. The secretary manages appointments and the queue without any access to the medical record.
The medical centre or clinic
- Appears on the map with its list of services and their schedules.
- A doctor takes shifts in more than one centre with the same account.
- The centre manager manages shifts from a calendar identical to the pharmacy's on-call calendar; it is the same module.
Delivery and smart interactions
- A delivery driver role for medicines and home services, built on top of the medicine reservation request that exists in the MVP.
- A drug interaction and recommendation engine that reads the patient's current medicines and warns the doctor when prescribing and the pharmacist when dispensing. It is connected as a separate module behind a stable interface, and the final decision belongs to the doctor or pharmacist.
Phase Roadmap
The phases are ordered so that each depends on the one before it, and the timelines are set once the team size is known.
- Foundation: identity and roles, cities, organizations and verification, the drug catalogue and its admin panel, the platform team console (system, operations and support), infrastructure and deployment.
- MVP — Pharmacy: inventory, sales with offline support, pricing, stock counts, on-call shifts, statistics.
- MVP — Warehouse: inventory and sub-stores, catalogue and offers, the order cycle, accounts and payments, the field warehouse sales rep.
- MVP — Patient: account and ID, the basic record, map and search, emergency, reminders, access permissions.
- Mobile and doctor: the Flutter app for patients, then the doctor and secretary, the digital prescription, appointment booking, then pharmaceutical companies, scientific offices and sample distribution.
- Medical centre: services and doctor shifts.
- Expansion: home delivery, the interactions and recommendations engine.
Phases 2 and 3 are built together because they share the inventory engine. Phase 4 starts once the system holds real stock for pharmacies in at least one city; otherwise the patient searches and finds nothing.
Part Two: Architecture and Technologies
Overall Architecture and Modules
The system is a single NestJS application deployed as one unit, divided internally into modules, each of which owns its data and its interface. This gives operational simplicity now, and allows any module to be split into an independent service later without a rewrite.
flowchart TB
web["React web app (PWA)"]
mobile["Flutter mobile app (later)"]
admin["Platform admin console"]
proxy["Caddy reverse proxy: TLS, REST /v1, WebSocket"]
web --> proxy
mobile --> proxy
admin --> proxy
subgraph mono["NestJS modular monolith (one deployable)"]
direction TB
identity
organizations
catalog
inventory
sales["sales (POS)"]
procurement
accounting
patients
notifications
search["search and map"]
analytics
audit["audit and sync"]
backoffice
bus["Public interfaces + domain events (outbox)"]
worker["Background worker: reminders, expiry alerts, reports"]
end
proxy --> mono
mono --> pg[("PostgreSQL + PostGIS: one schema per module, RLS")]
mono --> redis[("Redis: cache, BullMQ job queues")]
mono --> s3[("S3-compatible storage: prescriptions, licences, files")]
All clients pass through a single gateway to a single application, and the modules inside it do not share tables. Later-phase modules (clinical, appointments, samples, delivery) are added alongside these without changing them.
Module rules
- Each module owns its tables within its own schema in PostgreSQL, and no module reads another module's tables directly.
- Communication between modules happens only through a declared public interface or through Domain Events.
- An event is written to an outbox table within the same database transaction and then published, so it is not lost on an outage or restart.
- An automated check rule in the CI blocks imports from inside another module.
- Inside each module there are four layers: API, use cases, domain, infrastructure.
Modules
| Module | Responsibility | Phase |
|---|---|---|
| identity | Accounts, OTP, sessions, memberships, roles and permissions | MVP |
| organizations | Organizations, cities, verification, opening hours, on-call schedules, staff shifts, services | MVP |
| catalog | The drug catalogue, active ingredients, companies, barcodes, suggestions, interactions | MVP |
| inventory | Batches, stock transactions, sub-stores and rep custody, stock counts, shortage and expiry alerts. Shared between the pharmacy and the warehouse | MVP |
| sales | Sales, returns, shifts, customer debts, pricing | MVP |
| procurement | Warehouse catalogues, offers, orders, receiving, rep rounds and visits | MVP |
| accounting | Running accounts between organizations, invoices, payments, account statements | MVP |
| patients | Patient profile, medical record, medicines and doses, access permissions and their log | MVP |
| notifications | Notifications, SMS, scheduled reminders | MVP |
| search | Geographic search, medicine availability, emergency | MVP |
| analytics | Statistics and reports, built from events into aggregate tables | MVP |
| audit | The immutable audit log | MVP |
| sync | Receiving and reconciling offline sales operations | MVP |
| clinical | Visits, unified reports, the digital prescription | Later |
| appointments | Appointments, booking and the queue | Later |
| delivery | Home delivery | Later |
| samples | Scientific offices, sample issuing, doctor visits, coverage reports. Depends on inventory for stock and custody | Later |
| backoffice | Platform team console: tickets, assistance sessions, disputes, correction requests, announcements, the operations dashboard | MVP |
Multi-tenancy
- One shared database, and every operational row carries
organization_id. - Isolation in two layers: permission checks in the application, and Row-Level Security in PostgreSQL as a safety net if the code makes a mistake.
- The catalogue and cities are shared data. The patient's record belongs to the patient, not the organization, and access to it is only through permissions.
Interfaces
- REST documented with OpenAPI under
/v1, and the same API serves the web and the Flutter app. - WebSocket for live events: a new order for the warehouse, an availability confirmation in an emergency, alerts.
- Every sensitive write operation carries an idempotency key, so resending on a weak network does not repeat the operation.
Scaling path
- One or two servers with Docker Compose.
- Separate the worker, and add a PostgreSQL read replica for reports and search.
- More than one API instance behind the load balancer, since the application keeps no state in memory.
- Extract a module into an independent service when there is a real need; the first two candidates are search and notifications.
Technology Stack
All components are open source and run on our servers, and the common language is TypeScript in the backend and the web. Versions are pinned to the latest LTS when implementation starts.
| Layer | Choice | Reason |
|---|---|---|
| Backend | NestJS on Node.js LTS | Required, and its module system suits the modular architecture |
| Database | PostgreSQL with PostGIS and pg_trgm | Required. PostGIS for distance search, and pg_trgm for fuzzy search on Arabic and English names |
| Data access | Drizzle ORM with SQL migration files | Close to SQL, so it works easily with RLS, PostGIS and multiple schemas. Alternative: Prisma |
| Cache and queues | Redis with BullMQ | Background jobs: reminders, expiry alerts, reports, outbox publishing |
| Search | PostgreSQL in the MVP | Enough for the initial volume. Meilisearch is added if search needs higher speed |
| Files | S3-compatible storage (Garage, SeaweedFS or MinIO) | Prescription photos, licences and attachments. Final choice after reviewing the licence and maintenance status |
| Web | React + TypeScript + Vite | Required. One app with spaces for each role, or two apps: organizations and patient |
| Web data state | TanStack Query | Caching and retries suited to a weak network |
| User interface | Tailwind CSS with shadcn/ui components | Full RTL support for Arabic, with a translation structure ready for a second language |
| Offline | PWA with a Service Worker and IndexedDB via Dexie | The point-of-sale screen works offline without installing software |
| Maps | MapLibre GL with self-hosted OpenStreetMap tiles | No dependency on an external map provider and no paid API keys |
| Mobile | Flutter, later phase | Required. Consumes the same API, and its client is generated from OpenAPI |
| Authentication | OTP via SMS, short-lived JWT with a rotating refresh token, Argon2 for passwords | Implemented inside the system without an external identity provider |
| Real time | WebSocket via a NestJS Gateway | Live in-app notifications |
| Printing and files | Server-side PDF generation with an engine that supports Arabic, and browser printing for receipts | Invoices, account statements, prescriptions, barcode labels |
| Code repository | Monorepo with pnpm workspaces | Backend, web and the shared types package in one place |
| Testing | Vitest or Jest, Testcontainers, Playwright | Tests on a real PostgreSQL, and testing the point-of-sale screen with the network cut |
| Containers | Docker with Docker Compose | Simple deployment that suits a small team. Kubernetes is not needed at the start |
| Gateway | Caddy | Automatic TLS and short configuration. Alternative: Nginx |
| CI/CD | Self-hosted Gitea or GitLab with runners | Code, build and deployment on our servers |
| Monitoring | Prometheus, Grafana, Loki, and GlitchTip for errors | Metrics, logs and error tracking without external services |
Three services cannot be fully self-hosted and need a decision: the SMS gateway, mobile push notifications, and publishing the app to the stores. They are listed in the open questions.
Core Data Model
The model is built on three records that are not modified after they are written: stock transactions, financial entries, and the audit log. Balances are derived from them, so every figure in the system can be explained and reviewed.
Entities by module
| Module | Main tables |
|---|---|
| identity | users, memberships, roles, permissions, sessions, otp_codes |
| organizations | governorates, cities, organizations, working_hours, duty_shifts, staff_shifts, services |
| catalog | substances, manufacturers, products, product_substances, barcodes, product_proposals, interactions |
| inventory | storage_locations, stock_items, batches, stock_movements, stocktakes, stocktake_lines |
| sales | sales, sale_lines, returns, cash_sessions, customer_debts, price_changes, controlled_register |
| procurement | listings, offers, offer_items, orders, order_lines, receipts, rep_routes, rep_visits |
| accounting | accounts, invoices, payments, ledger_entries, cash_custody |
| patients | patients, conditions, allergies, medications, dose_schedules, prescriptions, dispensings, access_grants, access_logs |
| notifications | devices, notifications, reminders |
| audit and sync | audit_log, outbox, client_operations |
| samples (later) | territories, visit_plans, doctor_visits, sample_handouts |
| backoffice | tickets, ticket_messages, support_sessions, disputes, correction_requests, announcements |
Key relationships
stock_itemslinks an organization to a product: selling price, minimum level, public visibility.batcheshold the batch, expiry, purchase price and quantity for each store.stock_movementsis one row per quantity change: type, batch, quantity as positive or negative, source document, employee. The stored batch quantity is updated in the same transaction.- A pharmacy receiving a warehouse order creates an outgoing transaction at the warehouse and an incoming transaction at the pharmacy with the same batch data.
accountsis one account per (warehouse, pharmacy) pair.ledger_entriesis one entry per invoice, payment or return, and the balance is their sum.patientsis separate fromusers: a profile can exist without an account (a dependent, or a profile created by a pharmacist) and be linked to an account later. The Shefa ID is a unique column in it.access_grants: the patient, the grantee (a membership), the scope, the expiry time, the revocation time. Every read of the record writes a row toaccess_logs.
A rep's custody, whether a warehouse sales rep or a medical rep, is a storage_location of type "mobile" linked to their membership. Issuing to them, delivering from it and returning are all ordinary stock transactions, so it needs no special logic and appears in stock counts. Collected cash is recorded in cash_custody until it is handed over.
Conventions
- Keys are UUID v7, which allows the point-of-sale screen to generate operation IDs offline.
- Amounts are
numericwith a currency column, and floating-point numbers are not used. Quantities are stored in the smallest unit of sale as an integer. - Times are stored in UTC and displayed in Damascus time.
- Geographic location is a
geographycolumn with a GiST index. stock_movements,audit_logandaccess_logsare partitioned monthly because they grow fastest.- Deletion is logical (soft delete) for reference data, and financial and inventory records are corrected with a reversing transaction, not by deletion.
Offline Sales and Synchronisation
The pharmacy point-of-sale screen keeps working when the internet is down, and the server accepts every sale made offline without rejecting it. The sale really happened and the medicine has left the shelf, so the system records what happened and then flags conflicts for review.
What works offline and what does not
| Operation | Offline |
|---|---|
| Sales, returns, barcode scanning and receipt printing | Yes |
| Searching the pharmacy's items, prices and alternatives | Yes, from the local copy |
| Closing the shift | Yes, and it is approved after synchronisation |
| Opening a patient record | No |
| Purchasing, receiving, stock counts and price changes | No |
Mechanism
- When online, the device stores in IndexedDB a copy of the pharmacy's items, their batches and prices, and updates it with differences only.
- Every sale is written immediately to a local queue with an ID generated by the device, along with the device ID, the employee and the local time. The write happens before the receipt is printed, so a power cut does not lose an operation.
- When the connection returns, the queue is sent in order to the sync module. The ID prevents the operation from being recorded twice, however many times it is resent.
- The server turns each operation into stock transactions and returns the reconciliation result, then the device pulls the updated copy.
Reconciliation rules
- Price: the price at which the item was actually sold is used, even if it changed on the server during the outage.
- Batch: if the batch chosen by the device has run out, the server draws from the next batch according to FEFO and records this.
- Negative balance: allowed temporarily. The item is flagged and appears in a discrepancy report that the manager reviews and settles with a partial stock count.
- More than one device: each device sells from its own copy, and conflicts between them are resolved with the same rules during synchronisation.
- Restricted items: sold offline with the prescription details entered manually, and flagged for review.
Limits and security
- The session stays valid offline, with a PIN lock for each employee.
- After a maximum period without synchronisation (proposed: 72 hours), the screen stops selling until it connects.
- The UI always shows the connection status and the number of unsynchronised operations.
- The local copy does not contain patient data, nor purchase prices for those who do not have permission to see them.
Security and Privacy
The system holds health data, so the rule is that no one reads a patient's record without a valid permission from them, and every read leaves a trace that the patient can see.
- Isolation: operation-level permissions in the application, and Row-Level Security in the database for every table that carries
organization_id. - Medical record: access only through
access_grants, with a scope and a duration, and an immutable read log. The system administrator and the operations and support teams do not read records from the admin console. - Encryption: TLS for every connection, disk encryption on the servers, and additional field-level encryption for the most sensitive data (national ID number, diagnoses).
- Authentication: rate limiting for OTP requests and login attempts, device-bound sessions that can be terminated, and two-step verification for organization managers and platform supervisors.
- Audit: every price change, stock adjustment, payment or permission change is written to
audit_logwith the actor, the time and the previous value. - Files: prescription and licence photos are served with short-lived signed links, not public links.
- Patient rights: exporting their record, revoking permissions, and requesting deletion of their account within what the law allows.
- Operations: secrets outside the code, server access with SSH keys only, encrypted backups, and regular security updates for containers and packages.
Infrastructure and Operations
We start with two servers and a separate backup site, and everything is deployed with Docker Compose from a single repository.
Initial layout
| Server | What runs on it |
|---|---|
| Application | Caddy, API container, worker container, static web files, Redis, map tile server |
| Data | PostgreSQL, file storage |
| Backup | A geographically different site: database and file backups and the WAL archive |
| Tools | Git, CI and monitoring, on a small separate server or alongside the application server at first |
Backup and recovery
- pgBackRest: a daily full backup and continuous WAL archiving, allowing recovery to any point in time.
- Proposed target: data loss of no more than 15 minutes, and service restored within 4 hours.
- A real monthly restore test on a staging environment, because a backup that has not been tested cannot be relied on.
- A read replica is added in the next step and can serve as a fallback if the main server fails.
Deployment and environments
- Three environments: local development, staging, production.
- CI pipeline: type checks and module boundary checks, tests, image builds, deployment to staging, then deployment to production with manual confirmation.
- Migrations are compatible with the previous version of the code, so deployment does not stop the service and rollback is possible.
- An old PWA version on an offline device stays compatible with the API, so the sync endpoint carries a version number and supports the previous version.
Weak network
- Response compression, pagination, and small responses with only the required fields.
- UI files are cached in the browser, so the second load fetches nothing from the network.
- Images are compressed on the device before upload.
- Automatic retries are safe because write operations carry an idempotency key.
Monitoring
Alerts for service downtime, a full disk, backup failure, a job queue backlog, and a rise in the error rate or response time.
Assumptions and Open Questions
The document was built on the following assumptions without them being asked, and the questions after them need an answer before implementation starts.
Assumptions
- The system records payments and does not execute electronic payments.
- The UI is Arabic RTL first, and the translation structure is ready for English.
- The patient uses a responsive web interface (PWA) in the MVP until the Flutter app is released.
- The patient sees medicine availability without quantities.
- The warehouse does not see pharmacies' stock or sales.
- The warehouse sales rep is in the MVP. Pharmaceutical companies and scientific offices come in with the doctor phase, and the company does not sell through the system.
- One shared database for all cities and organizations.
Open questions
- Currency: are prices in Syrian pounds only, or are purchase prices stored in US dollars with an exchange rate? The answer changes pricing, accounts and reports.
- SMS gateway: which provider is available for sending OTPs inside Syria, and is WhatsApp an acceptable alternative?
- Mobile notifications: are the usual push services and app store publishing available to users in Syria? If not, we need a self-hosted alternative and direct APK distribution.
- Hosting location: servers inside Syria or outside it? This affects speed, reliability and the legal status of health data.
- Drug catalogue source: is there an official or syndicate list of registered medicines and their barcodes that we can start from, or is the catalogue built manually with the first pharmacies?
- Legal requirements: what do the Ministry of Health and the Pharmacists Syndicate require for the controlled medicines register, the stamped prescription, and the storage of health data? This needs review by a specialist.
- Official pricing: is there a binding official price for medicines, and is the pharmacy allowed to exceed it?
- Business model: a monthly subscription for organizations, a commission on orders, or free at first? This determines whether we need a subscriptions module.
- Pharmacy prices for the patient: does the patient see the price of the medicine at each pharmacy, or only availability?
- Hardware: what barcode scanners and receipt printers do pharmacies have, and is the main usage on a computer, tablet or mobile?
- Team and timeline: the number of developers and the target date for the first launch, to turn the phase roadmap into a schedule.
- Pharmaceutical companies: do they come in with the doctor phase as we assumed, or before it? And will the company sell to warehouses through the system later?
- Prescribing data for companies: is the company given aggregated statistics without names on the prescribing of its medicines, or never?
- Rep delivery: does the warehouse sales rep deliver medicines from their custody directly without a prior order, or is delivery always against a confirmed order?