# ProForma POS — Mobile Invoice, Barcode Scan & Stock Count (PHP + MySQL)

A mobile-ready web app (installable PWA) with a **PHP (PDO) + MySQL** backend:

- Products are retrieved from MySQL (table **`productlist`**) and cached
  locally for offline use.
- Proforma invoices are saved to MySQL (header + line items) when printed.
- Stocktake sessions are saved to MySQL, and committing a count updates
  product stock levels in the database.
- Barcode scanning with the phone camera (EAN-13/8, UPC-A/E, Code 128/39/93,
  ITF, Codabar, QR) and **58mm thermal receipt printing** for both the
  proforma invoice and the stock-count report.
- If the server is unreachable the app keeps working from its local cache;
  the header shows the connection status.

## Architecture

```
Browser (public/)  ── fetch /api ──>  PHP front controller (public/api/index.php)  ──>  MySQL
```

| Path | Purpose |
|------|---------|
| `public/` | Web root: the mobile app + the API |
| `public/api/index.php` | Front controller / router for all `/api/*` calls |
| `public/api/lib.php` | PDO connection + JSON helpers |
| `public/api/.htaccess` | Apache rewrite: sends `/api/*` to `index.php` |
| `public/router.php` | Router for PHP's built-in server (dev/testing) |
| `bin/init-db.php` | Creates the database + tables from `schema.sql` |
| `schema.sql` | Database + table definitions |
| `config.example.php` | Copy to `config.php` and set credentials |

## Requirements

- PHP 7.4+ (8.x recommended) with the **pdo_mysql** extension
- MySQL 5.7+/8.x or MariaDB 10.4+
- Apache with `mod_rewrite` (production) — or just PHP's built-in server (dev)

## Install on Ubuntu (Apache + mod_php)

```bash
# 1. packages
sudo apt-get update
sudo apt-get install -y apache2 mysql-server php libapache2-mod-php php-mysql
sudo a2enmod rewrite

# 2. database + user
sudo mysql <<'SQL'
CREATE DATABASE proforma_pos CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'proforma'@'localhost' IDENTIFIED BY 'a_strong_password';
GRANT ALL PRIVILEGES ON proforma_pos.* TO 'proforma'@'localhost';
FLUSH PRIVILEGES;
SQL

# 3. deploy the app
unzip proforma-app.zip
sudo mv proforma-app /opt/proforma-app
cd /opt/proforma-app
cp config.example.php config.php
sudo nano config.php        # set db_user/db_pass/db_name and (recommended) api_key

# 4. create the tables
php bin/init-db.php         # or:  mysql -u root -p < schema.sql

# 5. protect config.php
sudo chmod 640 config.php
sudo chown -R www-data:www-data /opt/proforma-app
```

Apache virtual host — point the **DocumentRoot at `public/`** and allow
`.htaccess` overrides. Create `/etc/apache2/sites-available/proforma.conf`:

```apache
<VirtualHost *:80>
    ServerName pos.yourdomain.com
    DocumentRoot /opt/proforma-app/public
    <Directory /opt/proforma-app/public>
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
```

```bash
sudo a2ensite proforma
sudo a2dissite 000-default        # optional
sudo systemctl reload apache2
```

> The camera scanner needs **HTTPS** (or localhost). For a real domain, add a
> certificate with `sudo apt-get install certbot python3-certbot-apache &&
> sudo certbot --apache`. On a LAN you can test over `http://SERVER_IP` from
> the server's own browser, but phones will block the camera without HTTPS.

## Quick local test (no Apache)

```bash
cp config.example.php config.php   # edit credentials
php bin/init-db.php
php -S 0.0.0.0:8080 -t public public/router.php
# open http://localhost:8080
```

## config.php keys

| Key | Meaning |
|-----|---------|
| `db_host` / `db_port` | MySQL host and port |
| `db_user` / `db_pass` | MySQL credentials |
| `db_name` | Database name (default `proforma_pos`) |
| `api_key` | Optional shared secret; if set, every `/api` request must send it in the `x-api-key` header |

Each key also falls back to an environment variable (`DB_HOST`, `DB_USER`, …)
if you prefer to set them in Apache/systemd instead of the file.

## Security notes (please read)

- **The API has no user accounts.** Anyone who can reach it can read/write
  data. For anything beyond a trusted LAN, set `api_key` in `config.php` (and
  enter the same key in the app's **Settings**), serve over **HTTPS**, and
  restrict access.
- `config.php` holds your DB password and lives **outside** the web root
  (`public/`), so it is not directly downloadable. Keep its permissions tight
  and never commit it.
- All SQL uses PDO prepared statements (no string concatenation).

## API endpoints

| Method & path | Description |
|---------------|-------------|
| `GET /api/products` (`?q=`) | List / search products |
| `POST /api/products` | Create or update one product (upsert) |
| `POST /api/products/import` | Bulk upsert (CSV/JSON import) |
| `DELETE /api/products/:barcode` | Delete a product |
| `POST /api/invoices` | Save a proforma invoice + items |
| `GET /api/invoices` / `GET /api/invoices/:id` | List / fetch invoices |
| `POST /api/stocktakes` | Save a stocktake (`commit:true` also updates stock) |
| `GET /api/stocktakes` | List stocktake sessions |
| `GET /api/settings` / `PUT /api/settings` | Business/receipt settings |
| `GET /api/health` | DB connectivity check |

## Using the app

- **Settings (⚙️):** business name, address, phone, currency, receipt footer.
  Leave **Server API URL** blank when the app is served from the same site
  (same origin); set it to e.g. `https://host/api` only if you host the
  frontend separately. Enter the **API key** here if you set one.
- **Products:** add/edit items (saved to MySQL) or import the sample CSV.
- **Invoice:** scan/enter barcodes, adjust qty/price, discount & tax, then
  **Print Proforma (58mm)** — this also saves the invoice to MySQL.
- **Stock:** each scan increments the counted qty for that barcode. **Save to
  Stock** stores the stocktake in MySQL and updates product stock levels.
  **Print Count (58mm)** prints the report.

## Printing to a 58mm thermal printer

Tap a Print button. The receipt is laid out at exactly **58mm** width via CSS
`@page`, so it fits standard 58mm thermal paper.

### On a desktop / USB printer

In the print dialog choose your thermal printer, set paper size to **58mm /
Roll** and margins to **None**.

### On the Android device's local printer

Tapping a Print button calls the browser's print function, which opens the
**Android system print dialog** — from there you can pick any printer the
phone can reach (Wi‑Fi/Cloud printers, or *Save as PDF*).

Most **58mm Bluetooth/USB thermal printers are not recognised by Android's
built-in print framework**, so to print straight to one from the app install a
thermal *print service* that adds the printer to Android, for example:

- **RawBT print service** (free, Google Play) — pairs the Bluetooth/USB 58mm
  printer, then appears as a printer inside Chrome's print dialog. Set its
  paper width to 58mm (384 dots) in the RawBT settings.
- Or the printer manufacturer's own Android print-service/SDK app.

With such a service installed: open the app in Chrome → tap **Print** → in the
print dialog choose the thermal printer (e.g. *RawBT*) → Print. No cable to a
PC is needed; it prints on the local printer connected to the phone.

> Tip: for the cleanest thermal output in RawBT, set margins to 0 and choose
> the 58mm profile.
