Production
This commit is contained in:
@@ -0,0 +1,189 @@
|
|||||||
|
db-1 |
|
||||||
|
db-1 | PostgreSQL Database directory appears to contain a database; Skipping initialization
|
||||||
|
db-1 |
|
||||||
|
db-1 | 2026-09-20 05:16:57.152 UTC [1] LOG: starting PostgreSQL 16.15 on x86_64-pc-linux-musl, compiled by gcc (Alpine 15.2.0) 15.2.0, 64-bit
|
||||||
|
db-1 | 2026-09-20 05:16:57.152 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
|
||||||
|
db-1 | 2026-09-20 05:16:57.152 UTC [1] LOG: listening on IPv6 address "::", port 5432
|
||||||
|
db-1 | 2026-09-20 05:16:57.155 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
|
||||||
|
db-1 | 2026-09-20 05:16:57.168 UTC [29] LOG: database system was shut down at 2026-09-20 05:16:55 UTC
|
||||||
|
db-1 | 2026-09-20 05:16:57.180 UTC [1] LOG: database system is ready to accept connections
|
||||||
|
db-1 | 2026-09-20 05:17:03.978 UTC [39] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:17:03.978 UTC [39] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:17:08.432 UTC [48] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:17:08.432 UTC [48] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:17:12.951 UTC [57] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:17:12.951 UTC [57] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:17:17.458 UTC [65] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:17:17.458 UTC [65] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:17:21.947 UTC [66] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:17:21.947 UTC [66] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:17:26.331 UTC [74] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:17:26.331 UTC [74] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:17:30.747 UTC [83] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:17:30.747 UTC [83] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:17:35.138 UTC [90] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:17:35.138 UTC [90] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:17:39.636 UTC [98] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:17:39.636 UTC [98] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:17:44.035 UTC [107] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:17:44.035 UTC [107] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:17:48.411 UTC [115] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:17:48.411 UTC [115] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:17:52.721 UTC [116] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:17:52.721 UTC [116] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:17:57.257 UTC [125] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:17:57.257 UTC [125] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:18:01.900 UTC [133] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:18:01.900 UTC [133] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:18:06.319 UTC [141] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:18:06.319 UTC [141] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:18:08.113 UTC [149] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:18:08.113 UTC [149] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:18:12.666 UTC [151] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:18:12.666 UTC [151] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:18:17.184 UTC [159] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:18:17.184 UTC [159] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:18:21.706 UTC [167] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:18:21.706 UTC [167] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:18:26.211 UTC [175] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:18:26.211 UTC [175] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:18:30.708 UTC [184] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:18:30.708 UTC [184] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:18:35.184 UTC [192] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:18:35.184 UTC [192] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:18:39.738 UTC [199] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:18:39.738 UTC [199] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:18:44.293 UTC [208] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:18:44.293 UTC [208] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:18:48.925 UTC [216] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:18:48.925 UTC [216] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:18:53.406 UTC [217] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:18:53.406 UTC [217] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:18:58.007 UTC [225] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:18:58.007 UTC [225] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:19:02.969 UTC [234] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:19:02.969 UTC [234] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:19:07.554 UTC [242] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:19:07.554 UTC [242] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:19:12.083 UTC [249] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:19:12.083 UTC [249] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:19:14.060 UTC [258] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:19:14.060 UTC [258] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:19:18.491 UTC [259] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:19:18.491 UTC [259] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:19:23.016 UTC [267] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:19:23.016 UTC [267] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:19:27.632 UTC [276] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:19:27.632 UTC [276] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:19:32.147 UTC [284] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:19:32.147 UTC [284] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:19:36.600 UTC [292] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:19:36.600 UTC [292] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:19:41.020 UTC [299] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:19:41.020 UTC [299] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:19:45.624 UTC [308] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:19:45.624 UTC [308] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:19:50.089 UTC [316] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:19:50.089 UTC [316] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:19:54.570 UTC [317] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:19:54.570 UTC [317] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:19:59.098 UTC [326] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:19:59.098 UTC [326] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:20:04.277 UTC [334] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:20:04.277 UTC [334] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:20:08.934 UTC [342] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:20:08.934 UTC [342] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:20:13.495 UTC [351] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:20:13.495 UTC [351] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:20:18.039 UTC [360] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:20:18.039 UTC [360] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:20:19.980 UTC [361] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:20:19.980 UTC [361] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:20:24.501 UTC [368] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:20:24.501 UTC [368] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:20:29.097 UTC [377] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:20:29.097 UTC [377] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:20:33.618 UTC [384] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:20:33.618 UTC [384] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:20:38.088 UTC [391] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:20:38.088 UTC [391] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:20:42.608 UTC [400] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:20:42.608 UTC [400] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:20:47.153 UTC [407] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:20:47.153 UTC [407] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:20:51.566 UTC [414] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:20:51.566 UTC [414] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:20:56.011 UTC [422] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:20:56.011 UTC [422] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:21:00.533 UTC [424] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:21:00.533 UTC [424] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:21:04.927 UTC [432] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:21:04.927 UTC [432] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:21:09.385 UTC [440] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:21:09.385 UTC [440] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:21:13.801 UTC [448] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:21:13.801 UTC [448] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:21:18.263 UTC [455] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:21:18.263 UTC [455] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:21:22.685 UTC [463] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:21:22.685 UTC [463] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:21:24.557 UTC [464] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:21:24.557 UTC [464] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:21:29.007 UTC [473] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:21:29.007 UTC [473] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:21:33.429 UTC [481] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:21:33.429 UTC [481] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:21:37.901 UTC [488] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:21:37.901 UTC [488] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:21:42.449 UTC [497] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:21:42.449 UTC [497] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:21:47.008 UTC [504] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:21:47.008 UTC [504] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:21:51.513 UTC [505] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:21:51.513 UTC [505] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:21:56.017 UTC [512] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:21:56.017 UTC [512] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:21:57.266 UTC [27] LOG: checkpoint starting: time
|
||||||
|
db-1 | 2026-09-20 05:21:57.282 UTC [27] LOG: checkpoint complete: wrote 3 buffers (0.0%); 0 WAL file(s) added, 0 removed, 0 recycled; write=0.006 s, sync=0.002 s, total=0.017 s; sync files=2, longest=0.001 s, average=0.001 s; distance=0 kB, estimate=0 kB; lsn=0/2FAD240, redo lsn=0/2FAD208
|
||||||
|
db-1 | 2026-09-20 05:22:00.528 UTC [521] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:22:00.528 UTC [521] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:22:05.322 UTC [528] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:22:05.322 UTC [528] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:22:09.877 UTC [536] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:22:09.877 UTC [536] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:22:14.407 UTC [546] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:22:14.407 UTC [546] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:22:18.960 UTC [554] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:22:18.960 UTC [554] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:22:23.616 UTC [562] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:22:23.616 UTC [562] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:22:28.170 UTC [571] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:22:28.170 UTC [571] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:22:30.183 UTC [572] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:22:30.183 UTC [572] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:22:34.947 UTC [580] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:22:34.947 UTC [580] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:22:39.534 UTC [588] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:22:39.534 UTC [588] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:22:44.011 UTC [597] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:22:44.011 UTC [597] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:22:48.506 UTC [605] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:22:48.506 UTC [605] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:22:52.937 UTC [613] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:22:52.937 UTC [613] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:22:57.483 UTC [615] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:22:57.483 UTC [615] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:23:02.188 UTC [623] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:23:02.188 UTC [623] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:23:06.771 UTC [631] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:23:06.771 UTC [631] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:23:11.318 UTC [639] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:23:11.318 UTC [639] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:23:15.871 UTC [647] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:23:15.871 UTC [647] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:23:20.308 UTC [655] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:23:20.308 UTC [655] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:23:24.775 UTC [664] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:23:24.775 UTC [664] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
|
db-1 | 2026-09-20 05:23:29.185 UTC [672] FATAL: password authentication failed for user "pharma"
|
||||||
|
db-1 | 2026-09-20 05:23:29.185 UTC [672] DETAIL: Connection matched file "/var/lib/postgresql/data/pg_hba.conf" line 128: "host all all all scram-sha-256"
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
.env
|
||||||
|
.venv
|
||||||
|
venv
|
||||||
|
web
|
||||||
|
tests
|
||||||
|
storage
|
||||||
|
*.pdf
|
||||||
|
*.csv
|
||||||
|
openapi.json
|
||||||
|
README.md
|
||||||
|
Makefile
|
||||||
|
docker-compose*.yml
|
||||||
|
Dockerfile
|
||||||
|
.dockerignore
|
||||||
|
**/__pycache__
|
||||||
|
**/*.py[cod]
|
||||||
|
*.egg-info
|
||||||
|
.pytest_cache
|
||||||
|
.ruff_cache
|
||||||
|
.coverage
|
||||||
|
htmlcov
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# Copy to .env — it is git-ignored, never commit it.
|
||||||
|
# These defaults are for local development. On a server run `make deploy` — it fixes the
|
||||||
|
# production values and free ports for you (see README, "Quick start with Docker").
|
||||||
|
|
||||||
|
DATABASE_URL=postgresql+asyncpg://pharma:pharma@127.0.0.1:5432/pharma
|
||||||
|
SECRET_KEY=replace-with-a-64-char-random-string
|
||||||
|
ENVIRONMENT=development
|
||||||
|
DEBUG=true
|
||||||
|
PDF_STORAGE_PATH=./storage/pdf
|
||||||
|
|
||||||
|
# --- Docker Compose (database container; must match DATABASE_URL above) ------
|
||||||
|
POSTGRES_USER=pharma
|
||||||
|
POSTGRES_PASSWORD=pharma
|
||||||
|
POSTGRES_DB=pharma
|
||||||
|
|
||||||
|
# --- Production ---------------------------------------------------------------
|
||||||
|
# Change these before deploying with `docker compose up -d --build`:
|
||||||
|
# ENVIRONMENT=production
|
||||||
|
# DEBUG=false
|
||||||
|
# POSTGRES_PASSWORD=<strong password>
|
||||||
|
# SECRET_KEY=<64+ random chars: python -c "import secrets; print(secrets.token_urlsafe(64))">
|
||||||
|
# DOMAIN=<public host name> (localhost = local TLS)
|
||||||
|
# CORS_ORIGINS=["https://celtic.upskalor.com","https://www.celtic.upskalor.com","http://localhost:5173","http://localhost:3000"]
|
||||||
|
# A production start refuses a placeholder or under-32-character SECRET_KEY.
|
||||||
|
#
|
||||||
|
# Behind an existing reverse proxy that already owns ports 80/443? Serve plain HTTP on
|
||||||
|
# another host port and let that proxy terminate TLS:
|
||||||
|
# DOMAIN=:80
|
||||||
|
# HTTP_PORT=2000
|
||||||
|
# HTTPS_PORT=2443
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*.egg-info/
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
.env
|
||||||
|
.pytest_cache/
|
||||||
|
.ruff_cache/
|
||||||
|
storage/
|
||||||
|
*.pdf
|
||||||
|
.coverage
|
||||||
|
htmlcov/
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
NAME,HEADQUARTER,MONTH,SALE STATUS,AREA TO COVER,SALE OBJECTIVE,STATUS
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
@@ -0,0 +1,26 @@
|
|||||||
|
NAME,HEADQUARTER,MONTH,DOCTOR NAME,DATE OF VISIT,PRODUCT TARGETED,STATUS
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
,,,,,,
|
||||||
|
@@ -0,0 +1,44 @@
|
|||||||
|
{$DOMAIN} {
|
||||||
|
encode gzip
|
||||||
|
|
||||||
|
# Security headers. HSTS is deliberately left commented until the domain is
|
||||||
|
# confirmed — turning it on before you are certain about HTTPS locks browsers in.
|
||||||
|
header {
|
||||||
|
X-Content-Type-Options nosniff
|
||||||
|
X-Frame-Options DENY
|
||||||
|
Referrer-Policy strict-origin-when-cross-origin
|
||||||
|
# Strict-Transport-Security "max-age=31536000; includeSubDomains"
|
||||||
|
-Server
|
||||||
|
}
|
||||||
|
|
||||||
|
# API and API documentation stay behind the FastAPI service. Everything else
|
||||||
|
# is the React single-page application served by the lightweight web container.
|
||||||
|
handle /api/* {
|
||||||
|
reverse_proxy api:8000
|
||||||
|
}
|
||||||
|
handle /docs* {
|
||||||
|
reverse_proxy api:8000
|
||||||
|
}
|
||||||
|
handle /redoc* {
|
||||||
|
reverse_proxy api:8000
|
||||||
|
}
|
||||||
|
handle /openapi.json {
|
||||||
|
reverse_proxy api:8000
|
||||||
|
}
|
||||||
|
handle /health {
|
||||||
|
reverse_proxy api:8000
|
||||||
|
}
|
||||||
|
# Hashed build files never change, so they may be cached for a year. The app shell
|
||||||
|
# (index.html) must be re-checked every time, or a user keeps running the old
|
||||||
|
# version after a deploy until they hard-refresh.
|
||||||
|
handle /assets/* {
|
||||||
|
reverse_proxy web:80 {
|
||||||
|
header_down Cache-Control "public, max-age=31536000, immutable"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
handle {
|
||||||
|
reverse_proxy web:80 {
|
||||||
|
header_down Cache-Control "no-cache"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
NAME,HEADQUARTER,DATE,MONTH,DOCTOR SR. NO.,DR. NAME,QUALIFICATION,PRODUCT PROMOTE,PRODUCT SAMPLE,REMARKS,CHEMIST SR. NO.,NAME OF THE CHEMIST,POB,STOCKIST VISIT,ORDER
|
||||||
|
,,,,1,,,,,,1,,,,
|
||||||
|
,,,,2,,,,,,2,,,,
|
||||||
|
,,,,3,,,,,,3,,,,
|
||||||
|
,,,,4,,,,,,4,,,,
|
||||||
|
,,,,5,,,,,,5,,,,
|
||||||
|
,,,,6,,,,,,,,,,
|
||||||
|
,,,,7,,,,,,,,,,
|
||||||
|
,,,,8,,,,,,,,,,
|
||||||
|
,,,,9,,,,,,,,,,
|
||||||
|
,,,,10,,,,,,,,,,
|
||||||
|
+65
@@ -0,0 +1,65 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
|
# ---- build stage: resolve and install the Python dependencies into a venv ----
|
||||||
|
FROM python:3.12-slim AS builder
|
||||||
|
|
||||||
|
ENV PIP_NO_CACHE_DIR=1 PIP_DISABLE_PIP_VERSION_CHECK=1
|
||||||
|
RUN python -m venv /opt/venv
|
||||||
|
ENV PATH="/opt/venv/bin:$PATH"
|
||||||
|
|
||||||
|
WORKDIR /build
|
||||||
|
COPY pyproject.toml ./
|
||||||
|
COPY app ./app
|
||||||
|
# Install the dependencies only. The application itself runs from /srv/app, so the
|
||||||
|
# copy pip just installed into site-packages is removed to avoid a shadow copy.
|
||||||
|
RUN pip install . && pip uninstall -y pharma-field-force
|
||||||
|
|
||||||
|
# ---- runtime stage ----
|
||||||
|
FROM python:3.12-slim
|
||||||
|
|
||||||
|
# WeasyPrint's native libraries and the fonts the PDF forms name: Liberation Sans/Serif
|
||||||
|
# (metric-compatible with the Arial/Times of the printed company forms), Carlito (the
|
||||||
|
# Calibri look-alike) and DejaVu as the last-resort fallback.
|
||||||
|
# Pinned here so a missing library shows up at build time, not at the first PDF.
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
libpango-1.0-0 \
|
||||||
|
libpangoft2-1.0-0 \
|
||||||
|
libharfbuzz0b \
|
||||||
|
fontconfig \
|
||||||
|
fonts-dejavu-core \
|
||||||
|
fonts-liberation \
|
||||||
|
fonts-crosextra-carlito \
|
||||||
|
curl \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
ENV PATH="/opt/venv/bin:$PATH" \
|
||||||
|
PYTHONUNBUFFERED=1 \
|
||||||
|
PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
ENVIRONMENT=production \
|
||||||
|
PDF_STORAGE_PATH=/srv/storage/pdf \
|
||||||
|
WEB_CONCURRENCY=2
|
||||||
|
|
||||||
|
COPY --from=builder /opt/venv /opt/venv
|
||||||
|
|
||||||
|
WORKDIR /srv
|
||||||
|
COPY app ./app
|
||||||
|
COPY alembic ./alembic
|
||||||
|
COPY alembic.ini ./
|
||||||
|
COPY scripts ./scripts
|
||||||
|
|
||||||
|
RUN useradd --create-home --uid 1000 appuser \
|
||||||
|
&& mkdir -p /srv/storage/pdf \
|
||||||
|
&& chown -R appuser:appuser /srv/storage \
|
||||||
|
&& chmod +x /srv/scripts/docker-entrypoint.sh
|
||||||
|
USER appuser
|
||||||
|
|
||||||
|
# Fail the image build if the PDF engine cannot load (missing system library).
|
||||||
|
RUN python -c "import weasyprint; weasyprint.HTML(string='<p>ok</p>').write_pdf()"
|
||||||
|
|
||||||
|
EXPOSE 8000
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=3 \
|
||||||
|
CMD curl -fsS http://localhost:8000/health || exit 1
|
||||||
|
|
||||||
|
ENTRYPOINT ["/srv/scripts/docker-entrypoint.sh"]
|
||||||
|
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", \
|
||||||
|
"--proxy-headers", "--forwarded-allow-ips", "*"]
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
NAME,HEADQUARTER,MONTH,DATE,STATION WORKED,NO. OF DOCTORS CALLED,NO. OF CHEMISTS/PDS CALLED,DOCTOR CALL AVG,CHEMIST CALL AVG
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
,,,,,,,,
|
||||||
|
@@ -0,0 +1,26 @@
|
|||||||
|
NAME,HEADQUARTER,SL. NO.,DATE,FROM,TO,KILOMETERS (KM)
|
||||||
|
,,1,,,,
|
||||||
|
,,2,,,,
|
||||||
|
,,3,,,,
|
||||||
|
,,4,,,,
|
||||||
|
,,5,,,,
|
||||||
|
,,6,,,,
|
||||||
|
,,7,,,,
|
||||||
|
,,8,,,,
|
||||||
|
,,9,,,,
|
||||||
|
,,10,,,,
|
||||||
|
,,11,,,,
|
||||||
|
,,12,,,,
|
||||||
|
,,13,,,,
|
||||||
|
,,14,,,,
|
||||||
|
,,15,,,,
|
||||||
|
,,16,,,,
|
||||||
|
,,17,,,,
|
||||||
|
,,18,,,,
|
||||||
|
,,19,,,,
|
||||||
|
,,20,,,,
|
||||||
|
,,21,,,,
|
||||||
|
,,22,,,,
|
||||||
|
,,23,,,,
|
||||||
|
,,24,,,,
|
||||||
|
,,25,,,,
|
||||||
|
@@ -0,0 +1,66 @@
|
|||||||
|
.PHONY: help install dev migrate revision seed test test-unit test-e2e lint fmt up down logs harden dev-up dev-db setup deploy status
|
||||||
|
|
||||||
|
help:
|
||||||
|
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-14s\033[0m %s\n", $$1, $$2}'
|
||||||
|
|
||||||
|
install: ## Install runtime + dev dependencies
|
||||||
|
pip install -e ".[dev]"
|
||||||
|
|
||||||
|
dev: ## Run the API with auto-reload
|
||||||
|
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
|
||||||
|
|
||||||
|
migrate: ## Apply all migrations
|
||||||
|
alembic upgrade head
|
||||||
|
|
||||||
|
revision: ## Autogenerate a migration: make revision m="add product table"
|
||||||
|
alembic revision --autogenerate -m "$(m)"
|
||||||
|
|
||||||
|
seed: ## Seed the minimum MVP system (1 company, 1 HQ, GM/AM/MR, 15 doctors, 5 chemists)
|
||||||
|
python -m scripts.seed
|
||||||
|
|
||||||
|
test: ## Run the whole suite (needs Postgres)
|
||||||
|
pytest -q
|
||||||
|
|
||||||
|
test-unit: ## State machine and pure logic only — no database needed
|
||||||
|
pytest tests/unit -q
|
||||||
|
|
||||||
|
test-e2e: ## The 13-step acceptance test plus the negative-scope tests
|
||||||
|
pytest tests/e2e -q
|
||||||
|
|
||||||
|
lint: ## Check style
|
||||||
|
ruff check app tests
|
||||||
|
|
||||||
|
fmt: ## Fix style
|
||||||
|
ruff check --fix app tests && ruff format app tests
|
||||||
|
|
||||||
|
setup: ## Create/refresh .env for this machine (secrets, free ports) — safe to re-run
|
||||||
|
./scripts/setup.sh
|
||||||
|
|
||||||
|
deploy: setup ## setup + build + start + wait until the API is healthy
|
||||||
|
docker compose up -d --build
|
||||||
|
@for i in $$(seq 1 30); do \
|
||||||
|
docker compose exec -T api curl -fsS http://localhost:8000/health >/dev/null 2>&1 && \
|
||||||
|
{ echo "API healthy"; $(MAKE) --no-print-directory status; exit 0; }; sleep 2; done; \
|
||||||
|
echo "API did not become healthy: docker compose logs api"; exit 1
|
||||||
|
|
||||||
|
status: ## Show containers and the URL the site answers on
|
||||||
|
@docker compose ps --format 'table {{.Name}}\t{{.Status}}\t{{.Ports}}'
|
||||||
|
@echo "site: http://localhost:$$(grep -E '^HTTP_PORT=' .env 2>/dev/null | cut -d= -f2 | grep . || echo 80)"
|
||||||
|
|
||||||
|
up: ## Start the production stack (needs .env — see .env.example)
|
||||||
|
docker compose up -d --build
|
||||||
|
|
||||||
|
dev-up: ## Start the whole stack with DB and API published on localhost
|
||||||
|
docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d --build
|
||||||
|
|
||||||
|
dev-db: ## Start only PostgreSQL on localhost (host-run API and tests)
|
||||||
|
docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d db
|
||||||
|
|
||||||
|
down: ## Stop the stack
|
||||||
|
docker compose down
|
||||||
|
|
||||||
|
logs: ## Tail API logs
|
||||||
|
docker compose logs -f api
|
||||||
|
|
||||||
|
harden: ## Apply the append-only audit-log grants (run once, as superuser)
|
||||||
|
psql "$${ADMIN_DATABASE_URL:?set ADMIN_DATABASE_URL}" -f scripts/harden_audit.sql
|
||||||
+364
@@ -0,0 +1,364 @@
|
|||||||
|
# Production guide
|
||||||
|
|
||||||
|
How to deploy, secure, operate and recover the Celtic Life Science field-force system on a
|
||||||
|
single server. This is the operator's document; `README.md` is the developer's.
|
||||||
|
|
||||||
|
Every command below was run against this codebase's Docker stack unless it is marked
|
||||||
|
**untested**.
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
1. [What you are deploying](#1-what-you-are-deploying)
|
||||||
|
2. [Requirements](#2-requirements)
|
||||||
|
3. [First deployment](#3-first-deployment)
|
||||||
|
4. [Creating the real users](#4-creating-the-real-users)
|
||||||
|
5. [Loading reference data](#5-loading-reference-data)
|
||||||
|
6. [Configuration](#6-configuration)
|
||||||
|
7. [Domain, HTTPS and reverse proxies](#7-domain-https-and-reverse-proxies)
|
||||||
|
8. [Security checklist](#8-security-checklist)
|
||||||
|
9. [Backups and restore](#9-backups-and-restore)
|
||||||
|
10. [Updating and rolling back](#10-updating-and-rolling-back)
|
||||||
|
11. [Monitoring and logs](#11-monitoring-and-logs)
|
||||||
|
12. [Runbook](#12-runbook)
|
||||||
|
13. [Go-live checklist](#13-go-live-checklist)
|
||||||
|
14. [Known limitations](#14-known-limitations)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. What you are deploying
|
||||||
|
|
||||||
|
```
|
||||||
|
browser ──HTTPS──▶ caddy ──/api /docs /health──▶ api (FastAPI, uvicorn) ──▶ db (PostgreSQL 16)
|
||||||
|
│ │
|
||||||
|
└──everything else──▶ web └─▶ pdfstore volume (approved DCR PDFs)
|
||||||
|
(static React build)
|
||||||
|
```
|
||||||
|
|
||||||
|
| Service | Image | Role |
|
||||||
|
|---|---|---|
|
||||||
|
| `caddy` | `caddy:2-alpine` | The only thing that publishes ports. TLS (Let's Encrypt), gzip, security headers, routing. |
|
||||||
|
| `api` | built from `Dockerfile` | FastAPI app and PDF rendering (WeasyPrint). Non-root, **read-only filesystem**, all capabilities dropped. Runs `alembic upgrade head` on start. |
|
||||||
|
| `web` | built from `web/Dockerfile` | The React app, built at image-build time and served as static files. |
|
||||||
|
| `db` | `postgres:16-alpine` | Internal network only. Data in the `pgdata` volume. |
|
||||||
|
|
||||||
|
Persistent state lives in exactly two volumes: **`pgdata`** (the database) and **`pdfstore`**
|
||||||
|
(approved DCR PDFs). `caddydata` holds certificates. Everything else is rebuilt from the code.
|
||||||
|
|
||||||
|
Roles: MR (medical representative), AM (area manager), GM (general manager), ADMIN. The MR
|
||||||
|
files daily call reports and company forms, the AM approves, the GM has read access across
|
||||||
|
territories, the ADMIN maintains people, organisation and master data.
|
||||||
|
|
||||||
|
## 2. Requirements
|
||||||
|
|
||||||
|
- A Linux server with **Docker Engine and the Compose plugin** (`docker compose version`).
|
||||||
|
1 vCPU / 2 GB RAM / 20 GB disk is enough for one company and a few dozen users.
|
||||||
|
- `git`, `make`, `python3` (used by `scripts/setup.sh` to generate secrets; `openssl` is the fallback).
|
||||||
|
- For HTTPS with a real domain: a DNS `A` record pointing at the server, and ports 80 and 443 free
|
||||||
|
and reachable from the internet.
|
||||||
|
- Outbound internet access at build time (base images, `apt`, `pip`, `npm`).
|
||||||
|
|
||||||
|
## 3. First deployment
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone <your-repo-url> pharma-web-celtic && cd pharma-web-celtic # or copy this folder
|
||||||
|
DOMAIN=app.example.com make deploy # omit DOMAIN if you only have an IP address
|
||||||
|
```
|
||||||
|
|
||||||
|
`make deploy` runs `scripts/setup.sh`, then `docker compose up -d --build`, then waits for the
|
||||||
|
API to report healthy. It is safe to re-run. `setup.sh`:
|
||||||
|
|
||||||
|
- creates `.env` from `.env.example` when missing (**`.env` is never committed and is not part of this repository**);
|
||||||
|
- generates a 64-character `SECRET_KEY` when missing or a placeholder;
|
||||||
|
- sets `ENVIRONMENT=production` and `DEBUG=false`;
|
||||||
|
- generates `POSTGRES_PASSWORD` for a **new** database only — an existing database keeps its password;
|
||||||
|
- picks the ports: 80/443 when free, otherwise plain HTTP on the first free port from 2000 (HTTPS side 2443) and tells you which.
|
||||||
|
|
||||||
|
Verify:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make status
|
||||||
|
curl -s http://localhost:<HTTP_PORT>/health
|
||||||
|
# {"status":"ok","environment":"production","pdf_engine":"weasyprint"}
|
||||||
|
```
|
||||||
|
|
||||||
|
`pdf_engine` must say `weasyprint`. In production the API refuses to start if WeasyPrint's
|
||||||
|
system libraries are missing or `SECRET_KEY` is a placeholder or shorter than 32 characters,
|
||||||
|
so a bad image fails loudly at boot rather than producing broken PDFs later.
|
||||||
|
|
||||||
|
> **Running this next to another copy on the same machine.** Compose derives the project name
|
||||||
|
> from the folder name, and volumes are named after it (`<project>_pgdata`). Two folders with
|
||||||
|
> the same name share volumes and fight over ports. Set `COMPOSE_PROJECT_NAME=<something unique>`
|
||||||
|
> in the environment (or `.env`) before the first `make deploy` of the second copy.
|
||||||
|
|
||||||
|
## 4. Creating the real users
|
||||||
|
|
||||||
|
There is no "create first admin" command. (An Administrator can reset any user's password, email and employee code from **Users → Edit**; users cannot change their own.)
|
||||||
|
The only way to obtain a first administrator is the seed script, which creates demo accounts
|
||||||
|
that all share one well-known password (`ChangeMe123!`, in `scripts/seed.py`). Treat that as a
|
||||||
|
short-lived bootstrap and do the following **before the server is reachable by anyone else**
|
||||||
|
(firewall closed, or on a private network):
|
||||||
|
|
||||||
|
1. Seed once: `docker compose exec api python -m scripts.seed`
|
||||||
|
(creates the company row, one headquarters `BBSR`, four demo users `adm001 / gm001 / am001 /
|
||||||
|
mr001 @acmepharma.in`, 15 sample doctors and 5 chemists. Idempotent.)
|
||||||
|
2. Sign in as `adm001@acmepharma.in`.
|
||||||
|
3. **Setup → Organisation**: create the real headquarters. **Setup → People**: create the real
|
||||||
|
users, one of them an **Administrator**, each with a strong password. Passwords cannot be
|
||||||
|
changed later from the app, so choose them as final and hand them over securely.
|
||||||
|
4. Sign out, sign in as the **new** administrator, open **Users** and **deactivate all four demo
|
||||||
|
accounts** (deactivation also revokes their sessions). Verify `adm001` can no longer sign in.
|
||||||
|
5. Assign an Area Manager to each headquarters, then assign doctors and chemists to MRs
|
||||||
|
(**Setup → Assignments**).
|
||||||
|
|
||||||
|
If you would rather not keep the demo doctors, chemists and the `BBSR` headquarters, deactivate
|
||||||
|
them from **Doctors & Chemists** / leave them unassigned.
|
||||||
|
|
||||||
|
## 5. Loading reference data
|
||||||
|
|
||||||
|
**Stock / Products list** — the Products page reads the `stock_inventory` table. It is created
|
||||||
|
**and filled (26 products from `stock.csv`) by the migration** `h8d4f0a6c3e5`, so it is there
|
||||||
|
after the first start with nothing to do. Administrators can add, edit and delete products from
|
||||||
|
the Products page.
|
||||||
|
|
||||||
|
**Sales Projection and Sales & Stock product lists** — the Sales Projection form needs its
|
||||||
|
product list (name and PTS) in the database, and the Sales & Stock Statement lists the same
|
||||||
|
products. Load them once with the **non-destructive** mode of the import script. The CSVs are
|
||||||
|
deliberately not part of the Docker image and the API container is read-only, so mount the two
|
||||||
|
files into a one-off container:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose run --rm --no-deps -T \
|
||||||
|
-v "$PWD/sales_projection.csv:/srv/sales_projection.csv:ro" \
|
||||||
|
-v "$PWD/Sales_and_Stock_Statement.csv:/srv/Sales_and_Stock_Statement.csv:ro" \
|
||||||
|
api python -m scripts.import_csv_data --only-empty
|
||||||
|
```
|
||||||
|
|
||||||
|
`--only-empty` loads a table only if it has **no rows** and prints `skipped, already has N rows`
|
||||||
|
otherwise, so it can be re-run safely. **Never run the script without `--only-empty` on a
|
||||||
|
database that holds real data** — the plain form deletes every form table before loading.
|
||||||
|
|
||||||
|
## 6. Configuration
|
||||||
|
|
||||||
|
Only variables listed in `docker-compose.yml` reach the API container. Set them in `.env`.
|
||||||
|
|
||||||
|
| Variable | Default | Purpose |
|
||||||
|
|---|---|---|
|
||||||
|
| `SECRET_KEY` | *(required)* | JWT signing key, 64+ random characters. Changing it signs everyone out. |
|
||||||
|
| `POSTGRES_PASSWORD` | *(required)* | Database password. See [rotation](#12-runbook). |
|
||||||
|
| `POSTGRES_USER`, `POSTGRES_DB` | `pharma`, `pharma` | Database user and name. |
|
||||||
|
| `ENVIRONMENT` | `production` | `production` enables the boot-time safety checks. |
|
||||||
|
| `DEBUG` | `false` | Keep `false`. |
|
||||||
|
| `DOMAIN` | `localhost` | Host name Caddy serves; `:80` means plain HTTP (behind another proxy / no TLS). |
|
||||||
|
| `HTTP_PORT`, `HTTPS_PORT` | `80`, `443` | Host ports Caddy publishes. |
|
||||||
|
| `APP_TIMEZONE` | `Asia/Kolkata` | Business timezone. "Today" and the visit-time check use it, not the server's UTC clock. (Set under `api.environment:` in `docker-compose.yml` to change it.) |
|
||||||
|
| `BACKDATING_WINDOW_DAYS` | `7` | How many days back an MR may file a report. |
|
||||||
|
| `SUBMISSION_DEADLINE_DAYS` | `1` | A report for day D must be submitted by end of D + this many days. |
|
||||||
|
| `WEB_CONCURRENCY` | `2` | uvicorn worker processes. |
|
||||||
|
| `RUN_MIGRATIONS` | `1` | Set `0` on the `api` service to skip migrations at start. |
|
||||||
|
|
||||||
|
Other application settings (`app/config/settings.py`) — the letterhead printed on PDFs
|
||||||
|
(`PDF_COMPANY_NAME`, `_ADDRESS`, `_WEBSITE`, `_EMAIL`, `_PHONE`), `ACCESS_TOKEN_EXPIRE_MINUTES`
|
||||||
|
(15), `REFRESH_TOKEN_EXPIRE_DAYS` (7), `LOGIN_MAX_FAILED_ATTEMPTS` (10) — are **not** passed
|
||||||
|
through by the shipped compose file. To change one, add it under `api.environment:` in
|
||||||
|
`docker-compose.yml` and run `docker compose up -d`. The defaults already carry Celtic's details.
|
||||||
|
|
||||||
|
## 7. Domain, HTTPS and reverse proxies
|
||||||
|
|
||||||
|
| Situation | Result |
|
||||||
|
|---|---|
|
||||||
|
| Ports 80/443 free and `DOMAIN=app.example.com` (DNS already pointing here) | Caddy obtains and renews a Let's Encrypt certificate itself. |
|
||||||
|
| Ports 80/443 free, no domain | `DOMAIN=localhost`: HTTPS with a self-signed certificate (browser warning). |
|
||||||
|
| 80/443 owned by another service | `DOMAIN=:80` on `HTTP_PORT` (e.g. 2000). Put your existing proxy in front. |
|
||||||
|
|
||||||
|
Existing nginx terminating TLS in front of Caddy:
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
server {
|
||||||
|
server_name app.example.com;
|
||||||
|
listen 443 ssl; # + your certificate directives
|
||||||
|
location / {
|
||||||
|
proxy_pass http://127.0.0.1:2000; # the HTTP_PORT chosen by setup.sh
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Forwarded-For $remote_addr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Block the published port from the internet when a proxy on the same host fronts it
|
||||||
|
(`sudo ufw deny 2000/tcp`; the proxy still reaches `127.0.0.1:2000`).
|
||||||
|
|
||||||
|
Once HTTPS works on the real domain, enable HSTS: uncomment the
|
||||||
|
`Strict-Transport-Security` line in `Caddyfile` and `docker compose up -d`. Do not enable it
|
||||||
|
earlier — it locks browsers into HTTPS for a year.
|
||||||
|
|
||||||
|
## 8. Security checklist
|
||||||
|
|
||||||
|
- [ ] `.env` is `chmod 600`, owned by the deploy user, and is **not** in any repository or backup that leaves the server unencrypted.
|
||||||
|
- [ ] `SECRET_KEY` and `POSTGRES_PASSWORD` are generated values (`setup.sh` does this). `setup.sh` warns if the database still uses the default `pharma` password — rotate it.
|
||||||
|
- [ ] The four demo accounts are **deactivated** ([section 4](#4-creating-the-real-users)).
|
||||||
|
- [ ] Only ports 80/443 (or your proxy) are open. The database and API are not published; do not use `docker-compose.dev.yml` on a server — it publishes them.
|
||||||
|
- [ ] HTTPS on the real domain, then HSTS enabled.
|
||||||
|
- [ ] The host is patched, SSH is key-only, and `docker` group membership is limited to operators.
|
||||||
|
- [ ] Backups run and a restore has been **rehearsed** ([section 9](#9-backups-and-restore)).
|
||||||
|
- [ ] Decide about the public API docs: `/docs`, `/redoc` and `/openapi.json` are **reachable by anyone** through Caddy in the shipped configuration (they list every endpoint, though not data). To hide them, delete the corresponding `handle` blocks in `Caddyfile` and `docker compose up -d`.
|
||||||
|
- [ ] Someone reads the API logs for repeated `401`s (accounts lock after 10 failed sign-ins).
|
||||||
|
|
||||||
|
What the containers already enforce: API runs as a non-root user on a read-only filesystem with
|
||||||
|
all Linux capabilities dropped and `no-new-privileges`; the database is unreachable from outside
|
||||||
|
the compose network; Caddy sends `X-Content-Type-Options`, `X-Frame-Options: DENY` and a strict
|
||||||
|
`Referrer-Policy`, and hides the server banner; JSON logs rotate at 10 MB × 5 files per service.
|
||||||
|
|
||||||
|
**Audit log hardening (optional, not enabled by default).** `scripts/harden_audit.sql` creates a
|
||||||
|
`pharma_app` role that can insert into and read `audit_log` but never update or delete it. The
|
||||||
|
shipped compose file connects with a single owner role that also runs migrations, so enabling it
|
||||||
|
means splitting credentials: run migrations with the owner role (set `RUN_MIGRATIONS=0` on `api`
|
||||||
|
and run `alembic upgrade head` in a one-off container) and point the running API's
|
||||||
|
`DATABASE_URL` at `pharma_app`, after changing that role's placeholder password in the script.
|
||||||
|
This flow is **untested** in this repository — rehearse it on a staging copy first.
|
||||||
|
|
||||||
|
## 9. Backups and restore
|
||||||
|
|
||||||
|
What to back up: the **database** (`pg_dump`) and the **`pdfstore` volume**. Everything else is
|
||||||
|
code or regenerable. Take a backup **before every update**.
|
||||||
|
|
||||||
|
**Database backup** (verified):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
set -a; . ./.env; set +a
|
||||||
|
docker compose exec -T db pg_dump -U "$POSTGRES_USER" -Fc "$POSTGRES_DB" > backup-$(date +%F).dump
|
||||||
|
```
|
||||||
|
|
||||||
|
**PDF store backup:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run --rm -v "$(basename "$PWD")_pdfstore:/data:ro" -v "$PWD:/backup" alpine \
|
||||||
|
tar czf /backup/pdfstore-$(date +%F).tgz -C /data .
|
||||||
|
```
|
||||||
|
|
||||||
|
(Adjust the volume name if you set `COMPOSE_PROJECT_NAME`; list volumes with `docker volume ls`.)
|
||||||
|
|
||||||
|
**Nightly cron** (as the deploy user, `crontab -e`; copy the dumps off the server too):
|
||||||
|
|
||||||
|
```cron
|
||||||
|
15 2 * * * cd /opt/pharma-web-celtic && set -a && . ./.env && set +a && docker compose exec -T db pg_dump -U "$POSTGRES_USER" -Fc "$POSTGRES_DB" > /var/backups/pharma/db-$(date +\%F).dump && find /var/backups/pharma -name 'db-*.dump' -mtime +30 -delete
|
||||||
|
```
|
||||||
|
|
||||||
|
**Restore rehearsal** — restores into a *scratch* database so nothing live is touched (verified):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
set -a; . ./.env; set +a
|
||||||
|
docker compose exec -T db createdb -U "$POSTGRES_USER" restore_check
|
||||||
|
docker compose exec -T db pg_restore -U "$POSTGRES_USER" -d restore_check --no-owner < backup-YYYY-MM-DD.dump
|
||||||
|
docker compose exec -T db psql -U "$POSTGRES_USER" -d restore_check \
|
||||||
|
-c 'select count(*) from "user"' -c 'select count(*) from stock_inventory'
|
||||||
|
docker compose exec -T db dropdb -U "$POSTGRES_USER" restore_check
|
||||||
|
```
|
||||||
|
|
||||||
|
**Real disaster recovery** (empty server, backup in hand): deploy as in section 3, then
|
||||||
|
`docker compose stop api`, restore into the empty database
|
||||||
|
(`pg_restore -U … -d "$POSTGRES_DB" --clean --if-exists --no-owner < backup.dump`), restore the
|
||||||
|
PDF archive into the `pdfstore` volume, then `docker compose up -d`. Use the same `SECRET_KEY`
|
||||||
|
if you want existing sessions to survive; otherwise users simply sign in again.
|
||||||
|
|
||||||
|
## 10. Updating and rolling back
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. back up (section 9)
|
||||||
|
# 2. get the new code
|
||||||
|
git pull # or replace the folder contents
|
||||||
|
# 3. rebuild and restart — migrations run automatically on api start
|
||||||
|
make deploy
|
||||||
|
make status
|
||||||
|
```
|
||||||
|
|
||||||
|
The API image is rebuilt, so `pip`/`apt`/`npm` need network access. Compose recreates only what
|
||||||
|
changed; the database and volumes are untouched. Check `docker compose logs api | grep alembic`
|
||||||
|
to see which migrations ran.
|
||||||
|
|
||||||
|
**Rollback:** restore the previous code, and if the new release added migrations, step the schema
|
||||||
|
back first, using the **new** image (it knows those revisions):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose exec api alembic downgrade -1 # once per migration to undo; check with: alembic current
|
||||||
|
# then deploy the previous code: git checkout <previous-tag> && make deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
If in doubt, restore the pre-update database backup instead — it is always the safe path.
|
||||||
|
|
||||||
|
## 11. Monitoring and logs
|
||||||
|
|
||||||
|
- **Health:** `GET /health` → `{"status":"ok", ..., "pdf_engine":"weasyprint"}`. Docker health
|
||||||
|
checks run on `api` and `db`; `docker compose ps` shows `(healthy)`. Point an external uptime
|
||||||
|
monitor at `https://<domain>/health`.
|
||||||
|
- **Logs:** `docker compose logs -f api` (also `caddy`, `db`, `web`). Rotated automatically.
|
||||||
|
- **Disk:** watch the Docker data directory (`docker system df`); the `pgdata` and `pdfstore`
|
||||||
|
volumes only grow.
|
||||||
|
- **Errors:** no error tracker is wired in. Add Sentry or similar if you need alerting on 500s.
|
||||||
|
|
||||||
|
## 12. Runbook
|
||||||
|
|
||||||
|
| Task | Command |
|
||||||
|
|---|---|
|
||||||
|
| Status / URL | `make status` |
|
||||||
|
| Restart the API | `docker compose restart api` |
|
||||||
|
| Stop everything (data kept) | `docker compose down` |
|
||||||
|
| **Delete all data** | `docker compose down -v` — **never** on a live system |
|
||||||
|
| Open a database shell | `docker compose exec db psql -U "$POSTGRES_USER" "$POSTGRES_DB"` |
|
||||||
|
| Unlock a user (10 failed sign-ins) | `UPDATE "user" SET failed_login_attempts = 0 WHERE email = '…';` in the shell above |
|
||||||
|
| Rotate `SECRET_KEY` | edit `.env`, `docker compose up -d` — everyone must sign in again |
|
||||||
|
| Rotate the database password | see below |
|
||||||
|
|
||||||
|
**Rotating the database password** — the database keeps the password it was created with, so
|
||||||
|
changing `.env` alone would lock the API out:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
NEW=$(python3 -c "import secrets;print(secrets.token_urlsafe(24))")
|
||||||
|
docker compose exec db psql -U pharma -d pharma -c "ALTER USER pharma PASSWORD '$NEW';"
|
||||||
|
sed -i "s|^POSTGRES_PASSWORD=.*|POSTGRES_PASSWORD=$NEW|" .env
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
**Common failures**
|
||||||
|
|
||||||
|
| Symptom | Cause / fix |
|
||||||
|
|---|---|
|
||||||
|
| `make deploy` says `set POSTGRES_PASSWORD in .env` | Run `make setup` (or `./scripts/setup.sh`). |
|
||||||
|
| API restarts in a loop, log says `SECRET_KEY must be a random value` | `.env` has a placeholder key; run `make setup`. |
|
||||||
|
| API log: `WeasyPrint system libraries are required` | The image was built without Pango/fonts; rebuild with `docker compose build --no-cache api`. |
|
||||||
|
| Caddy cannot bind port 80/443 | Another service owns them; run `make setup` (it moves Caddy to a free port) and put a proxy in front. |
|
||||||
|
| API cannot connect after editing `.env` | The database still has the old password — see rotation above. |
|
||||||
|
| A page shows *"This didn't load — Request failed (500)"* | `docker compose logs api` shows the cause; after an update check the migration ran (`alembic current`). |
|
||||||
|
| PDFs look plain-text | The API logged the WeasyPrint fallback warning; the image is missing native libraries. |
|
||||||
|
|
||||||
|
## 13. Go-live checklist
|
||||||
|
|
||||||
|
1. `make deploy` finishes and `/health` reports `weasyprint`.
|
||||||
|
2. Real headquarters and users created; **all demo accounts deactivated** (section 4).
|
||||||
|
3. Reference data loaded (section 5): Products page shows 26 products; Sales Projection shows the
|
||||||
|
product list.
|
||||||
|
4. One end-to-end pass with real accounts: MR files a DCR → AM approves → PDF downloads and
|
||||||
|
opens; each company form downloads a PDF that matches the printed original.
|
||||||
|
5. HTTPS works on the final domain; HSTS enabled.
|
||||||
|
6. Firewall: only 80/443 (or the proxy) open.
|
||||||
|
7. First backup taken **and a restore rehearsed**; cron installed.
|
||||||
|
8. Uptime monitor pointed at `/health`; someone owns reading the logs.
|
||||||
|
9. Business rules confirmed with the client: the back-dating window and submission deadline
|
||||||
|
(`BACKDATING_WINDOW_DAYS`, `SUBMISSION_DEADLINE_DAYS`) are shipped assumptions.
|
||||||
|
|
||||||
|
## 14. Known limitations
|
||||||
|
|
||||||
|
- **Users cannot change their own password.** Only an Administrator can, from **Users → Edit**
|
||||||
|
(also email and employee code). A reset signs that user out everywhere and clears a lockout,
|
||||||
|
but an access token already issued stays valid until it expires (15 minutes). If the last
|
||||||
|
Administrator password is lost, create a new admin with a one-off script (see `scripts/`) —
|
||||||
|
there is no self-service recovery and no email flow.
|
||||||
|
- **Company-form approval is per form, not per row.** Tour plan, standard tour plan and fare chart
|
||||||
|
each have one approval state, stored on the server (`form_approval`): the MR sends a form that has
|
||||||
|
rows, the Area Manager approves it, and the PDF signature shows that name. Any change to the rows
|
||||||
|
withdraws the approval. The signature is decided by the server, never by the browser.
|
||||||
|
- **Audit-log immutability is opt-in** (section 8) and untested with the shipped compose file.
|
||||||
|
- **No built-in alerting or error tracking**; only health checks and logs.
|
||||||
|
- **Single server, single database.** There is no high availability; recovery time is "restore the
|
||||||
|
latest backup". That is the deliberate trade-off for this size of deployment.
|
||||||
|
- The test suite needs a reachable PostgreSQL; some tests under `tests/unit` do too.
|
||||||
@@ -0,0 +1,470 @@
|
|||||||
|
# Pharma Field-Force Reporting
|
||||||
|
|
||||||
|
> **Deploying to a server?** Use [PRODUCTION.md](PRODUCTION.md) — the operator's guide (first deployment, real users, backups, updates, runbook). This README is for development.
|
||||||
|
|
||||||
|
Field-force reporting for a pharmaceutical sales team (Celtic Life Science Pvt Ltd): Medical Representatives (MRs) file **Daily Call Reports**, Area Managers (AMs) review and approve them (the General Manager has a read-only overview), and approved reports are locked and rendered as PDFs. Alongside the DCR, the system manages the company's paper forms — tour plans, fare charts, stock statements and more — and prints each one on its own PDF layout.
|
||||||
|
|
||||||
|
- **Backend:** FastAPI · SQLAlchemy 2 (async) · PostgreSQL 16 · Alembic
|
||||||
|
- **PDFs:** Jinja2 templates rendered by WeasyPrint
|
||||||
|
- **Web app:** React 18 + TypeScript (Vite), Celtic-branded, served by Caddy
|
||||||
|
- **Deployment:** Docker Compose on a single VPS, automatic HTTPS via Caddy
|
||||||
|
|
||||||
|
Deliberately **not** in scope: HR, payroll, attendance, distributor management, GPS, offline mode.
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
|
||||||
|
1. [Features](#features)
|
||||||
|
2. [Quick start with Docker](#quick-start-with-docker) — incl. VPS over SSH, ports, operations
|
||||||
|
3. [Local development](#local-development)
|
||||||
|
4. [Configuration](#configuration)
|
||||||
|
5. [Roles and permissions](#roles-and-permissions)
|
||||||
|
6. [The approval workflow](#the-approval-workflow)
|
||||||
|
7. [Company forms and PDFs](#company-forms-and-pdfs)
|
||||||
|
8. [API overview](#api-overview)
|
||||||
|
9. [Project layout](#project-layout)
|
||||||
|
10. [Design decisions](#design-decisions)
|
||||||
|
11. [Testing](#testing)
|
||||||
|
12. [Production checklist](#production-checklist)
|
||||||
|
13. [Known limitations](#known-limitations)
|
||||||
|
14. [Troubleshooting](#troubleshooting)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
| Area | What it does |
|
||||||
|
|---|---|
|
||||||
|
| Daily Call Reports | MR records doctor and chemist calls per day; one report per MR per date |
|
||||||
|
| Approval workflow | `DRAFT → PENDING_AM → APPROVED`, with a return-for-correction loop (the Area Manager is the final approver); approved reports are immutable |
|
||||||
|
| Audit trail | Append-only log of every state change; approval history is a view over it |
|
||||||
|
| PDFs | Approved DCRs are stored as PDFs; company forms download as PDFs on demand |
|
||||||
|
| Company forms | Ten form tables (tour plan, fare chart, stock statement, …) with per-form PDF layouts |
|
||||||
|
| Masters | Users, headquarters, AM↔HQ mapping, doctors, chemists, products, with MR assignments |
|
||||||
|
| Security | JWT with refresh-token rotation, argon2 password hashing, role **and** scope checks |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Quick start with Docker
|
||||||
|
|
||||||
|
Requires Docker with the Compose plugin. On any machine — laptop, or a VPS over SSH:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone <repo-url> pharma-web-celtic && cd pharma-web-celtic
|
||||||
|
make deploy # = ./scripts/setup.sh + docker compose up -d --build + wait until healthy
|
||||||
|
```
|
||||||
|
|
||||||
|
`make deploy` is safe to re-run; it is also how you update after `git pull`. The setup step (`scripts/setup.sh`) prepares `.env` for you:
|
||||||
|
|
||||||
|
- creates `.env` from `.env.example` if it is missing;
|
||||||
|
- generates a strong `SECRET_KEY` (if missing or a placeholder), and sets `ENVIRONMENT=production`, `DEBUG=false`;
|
||||||
|
- generates `POSTGRES_PASSWORD` for a **new** database (an existing database keeps its password — see [Rotating the database password](#rotating-the-database-password));
|
||||||
|
- **picks free ports**: if 80/443 are free, Caddy serves your `DOMAIN` with automatic HTTPS; if another service already owns them, it switches to plain HTTP on the first free host port from 2000 (HTTPS side from 2443) and tells you which.
|
||||||
|
|
||||||
|
Then load the demo data once (skip this if the database already has users):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose exec api python -m scripts.seed
|
||||||
|
```
|
||||||
|
|
||||||
|
Check it:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make status # containers, ports and the site URL
|
||||||
|
curl http://localhost:<HTTP_PORT>/health # {"status":"ok", ... "pdf_engine":"weasyprint"}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Deploying on a VPS over SSH
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ssh user@your-vps
|
||||||
|
sudo apt-get install -y docker.io docker-compose-v2 git # or Docker's official install script
|
||||||
|
git clone <repo-url> pharma-web-celtic && cd pharma-web-celtic
|
||||||
|
DOMAIN=app.example.com make deploy # omit DOMAIN if you only have an IP address
|
||||||
|
```
|
||||||
|
|
||||||
|
Which case applies is decided by what is listening on the server:
|
||||||
|
|
||||||
|
| Situation | What `setup.sh` does | How users reach it |
|
||||||
|
|---|---|---|
|
||||||
|
| Ports 80/443 free, real `DOMAIN` (DNS already points at the server) | Caddy takes 80/443 | `https://app.example.com` — certificate is automatic |
|
||||||
|
| Ports 80/443 free, no domain | `DOMAIN=localhost` | `https://<ip>` with a self-signed certificate warning |
|
||||||
|
| **80/443 already used** by another service | `DOMAIN=:80`, next free `HTTP_PORT` (e.g. `2000`) | `http://<ip>:2000`, or put your existing proxy in front (below) |
|
||||||
|
|
||||||
|
Open the chosen port in the firewall only if you want direct access (`sudo ufw allow 2000/tcp`); if a proxy on the same host fronts it, block it instead (`sudo ufw deny 2000/tcp` — the proxy still reaches it on `127.0.0.1`).
|
||||||
|
|
||||||
|
**Existing nginx in front** (terminating TLS on 80/443):
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
server {
|
||||||
|
server_name app.example.com;
|
||||||
|
listen 443 ssl; # + your certificate directives
|
||||||
|
location / {
|
||||||
|
proxy_pass http://127.0.0.1:2000; # the HTTP_PORT chosen by setup.sh
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Forwarded-For $remote_addr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Choosing ports yourself:** edit `.env` (`HTTP_PORT`, `HTTPS_PORT`, `DOMAIN`) and run `docker compose up -d`. `setup.sh` keeps ports your own containers already use and only moves them when something else holds them.
|
||||||
|
|
||||||
|
### Day-to-day operations
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose logs -f api # API logs (also: web, caddy, db)
|
||||||
|
docker compose ps # status
|
||||||
|
make deploy # after git pull: rebuild and restart
|
||||||
|
docker compose down # stop (data volumes are kept)
|
||||||
|
docker compose down -v # stop AND DELETE the database and PDFs — never on a live system
|
||||||
|
docker compose exec db pg_dump -U pharma pharma > backup-$(date +%F).sql # database backup
|
||||||
|
```
|
||||||
|
|
||||||
|
### Rotating the database password
|
||||||
|
|
||||||
|
The database keeps the password it was created with; changing `POSTGRES_PASSWORD` in `.env` alone would lock the API out. To rotate (needed if `setup.sh` warned about a default password):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
NEW=$(python3 -c "import secrets;print(secrets.token_urlsafe(24))")
|
||||||
|
docker compose exec db psql -U pharma -d pharma -c "ALTER USER pharma PASSWORD '$NEW';"
|
||||||
|
sed -i "s|^POSTGRES_PASSWORD=.*|POSTGRES_PASSWORD=$NEW|" .env
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
### What the stack contains
|
||||||
|
|
||||||
|
| Service | Image | Notes |
|
||||||
|
|---|---|---|
|
||||||
|
| `caddy` | `caddy:2-alpine` | The only service publishing ports; routes `/api`, `/docs`, `/health` to the API and everything else to the web app |
|
||||||
|
| `api` | built from `Dockerfile` | Non-root, read-only filesystem, runs `alembic upgrade head` on start |
|
||||||
|
| `web` | built from `web/Dockerfile` | Static React build served by Caddy |
|
||||||
|
| `db` | `postgres:16-alpine` | Internal network only; data in the `pgdata` volume |
|
||||||
|
|
||||||
|
Things worth knowing:
|
||||||
|
|
||||||
|
- Compose refuses to start without `POSTGRES_PASSWORD` and `SECRET_KEY` (`make setup` fills them in).
|
||||||
|
- In `ENVIRONMENT=production` the API refuses to boot if WeasyPrint's system libraries are missing or `SECRET_KEY` is a placeholder / under 32 characters. `GET /health` reports `"pdf_engine": "weasyprint"`.
|
||||||
|
- Set `RUN_MIGRATIONS=0` on the `api` service to skip the start-up migration.
|
||||||
|
- The database and API are **not** published to the host. To reach the database from the host (tests, `psql`) use the development overlay: `DB_PORT=5433 make dev-db` publishes it on `127.0.0.1:5433` only.
|
||||||
|
- Volumes to back up: `pgdata` (use `pg_dump`) and `pdfstore` (approved DCR PDFs).
|
||||||
|
- The seed creates demo accounts that share one well-known password (see `scripts/seed.py`). **Change every password before real use.**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Local development
|
||||||
|
|
||||||
|
Prerequisites: Python 3.11+, Node.js 20+, Docker (for PostgreSQL).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Python environment
|
||||||
|
python -m venv .venv && source .venv/bin/activate # Windows: .\.venv\Scripts\Activate.ps1
|
||||||
|
pip install -e ".[dev]"
|
||||||
|
|
||||||
|
# 2. Settings
|
||||||
|
cp .env.example .env # development defaults; DATABASE_URL already points at localhost:5432
|
||||||
|
|
||||||
|
# 3. PostgreSQL on localhost:5432 (also creates the pharma_test database)
|
||||||
|
make dev-db # port taken? DB_PORT=5433 make dev-db, and use 5433 in DATABASE_URL
|
||||||
|
|
||||||
|
# 4. Schema and demo data
|
||||||
|
alembic upgrade head
|
||||||
|
python -m scripts.seed
|
||||||
|
|
||||||
|
# 5. API (http://localhost:8000, docs at /docs)
|
||||||
|
uvicorn app.main:app --reload
|
||||||
|
|
||||||
|
# 6. Web app (http://localhost:5173, proxies /api to port 8000)
|
||||||
|
cd web && npm install && npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
`make dev-up` starts the whole stack in containers with the database (`DB_PORT`, default 5432) and API (`API_PORT`, default 8000) published on `127.0.0.1` only. Run `make help` for all targets.
|
||||||
|
|
||||||
|
**PDF rendering on a dev machine:** WeasyPrint needs Pango and HarfBuzz (`apt install libpango-1.0-0 libpangoft2-1.0-0 libharfbuzz0b fonts-dejavu-core fonts-liberation fonts-crosextra-carlito` on Debian/Ubuntu). Without them the app still runs but produces plain-text PDFs and logs a warning; use the Docker image to see the real layout.
|
||||||
|
|
||||||
|
Seeded accounts (`scripts/seed.py`): `adm001@acmepharma.in` (System Admin), `gm001@acmepharma.in` (GM), `am001@acmepharma.in` (AM), `mr001@acmepharma.in` (MR) — one company, one headquarters (BBSR), 15 doctors (3 core) and 5 chemists assigned to the MR.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
All settings come from environment variables (or `.env`); nothing secret lives in code. See `app/config/settings.py`.
|
||||||
|
|
||||||
|
**Deployment (read by Docker Compose)**
|
||||||
|
|
||||||
|
| Variable | Default | Purpose |
|
||||||
|
|---|---|---|
|
||||||
|
| `POSTGRES_USER` / `POSTGRES_DB` | `pharma` | Database credentials and name |
|
||||||
|
| `POSTGRES_PASSWORD` | *required* | Database password |
|
||||||
|
| `SECRET_KEY` | *required* | JWT signing key — 64+ random characters |
|
||||||
|
| `DOMAIN` | `localhost` | Host name Caddy serves and obtains a certificate for (`:80` = plain HTTP, see below) |
|
||||||
|
| `HTTP_PORT` / `HTTPS_PORT` | `80` / `443` | Host ports Caddy publishes (`setup.sh` picks free ones) |
|
||||||
|
| `ENVIRONMENT` | `production` | `production` enables the start-up safety checks |
|
||||||
|
| `WEB_CONCURRENCY` | `2` | Uvicorn worker processes |
|
||||||
|
|
||||||
|
**Application**
|
||||||
|
|
||||||
|
| Variable | Default | Purpose |
|
||||||
|
|---|---|---|
|
||||||
|
| `DATABASE_URL` | local Postgres | `postgresql+asyncpg://…` (Alembic derives a `psycopg` URL from it) |
|
||||||
|
| `PDF_STORAGE_PATH` | `./storage/pdf` | Where approved DCR PDFs are written |
|
||||||
|
| `CORS_ORIGINS` | localhost dev origins | Allowed browser origins |
|
||||||
|
| `DEBUG` / `DB_ECHO` | `false` | Verbose logging / SQL echo |
|
||||||
|
| `PDF_COMPANY_NAME`, `_ADDRESS`, `_WEBSITE`, `_EMAIL`, `_PHONE` | Celtic details | Letterhead on every PDF |
|
||||||
|
|
||||||
|
**Business rules** — settings rather than constants, so they change without a code change:
|
||||||
|
|
||||||
|
| Variable | Default | Rule |
|
||||||
|
|---|---|---|
|
||||||
|
| `BACKDATING_WINDOW_DAYS` | `7` | How many days back an MR may file |
|
||||||
|
| `SUBMISSION_DEADLINE_DAYS` | `1` | Report for date D must be submitted by end of D+N |
|
||||||
|
| `MIN_RETURN_REASON_LENGTH` | `10` | Minimum length of a manager's return reason |
|
||||||
|
| `ACCESS_TOKEN_EXPIRE_MINUTES` | `15` | Access-token life |
|
||||||
|
| `REFRESH_TOKEN_EXPIRE_DAYS` | `7` | Refresh-token life |
|
||||||
|
| `LOGIN_MAX_FAILED_ATTEMPTS` | `10` | Failed logins before lockout |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Web application
|
||||||
|
|
||||||
|
A React 18 + TypeScript (Vite) single-page app in `web/`, styled as a minimal SaaS console: sidebar navigation with the Celtic logo, a top bar with the user menu, cards, tables with search and filters, side drawers for forms, toast notifications, and loading / empty / error states on every screen. It works down to phone width (the sidebar becomes a slide-in menu) and remembers whether the sidebar is collapsed.
|
||||||
|
|
||||||
|
```
|
||||||
|
web/src/
|
||||||
|
├── main.tsx, App.tsx Entry point; role-aware route table and sign-in gate
|
||||||
|
├── api/ client.ts (fetch, token refresh, downloads) · index.ts (all endpoints)
|
||||||
|
├── lib/ router (hash-based), session (auth context), navigation, formatting
|
||||||
|
├── hooks/useAsync.ts Data loading with loading / error / reload state
|
||||||
|
├── components/
|
||||||
|
│ ├── ui/ Button, Card, Badge, Field, DataTable, Tabs, Modal/drawer, Toast, Icon, …
|
||||||
|
│ ├── layout/ AppShell, Sidebar, Topbar
|
||||||
|
│ └── reports/ StatusBadge, WorkflowTracker, ApprovalTimeline, VisitList, AddVisitForm, ReviewPanel
|
||||||
|
├── pages/ Login, Dashboard, Directory, Products, Profile
|
||||||
|
│ ├── reports/ list, new, detail (with review actions)
|
||||||
|
│ ├── forms/ company forms: table, row drawer, approval state
|
||||||
|
│ └── admin/ Setup (tabs) and Users
|
||||||
|
└── styles/ tokens.css · base.css · layout.css · components.css
|
||||||
|
```
|
||||||
|
|
||||||
|
Screens are role-aware: MR / AM / GM get a dashboard with counts and a "waiting on you" queue; the Administrator gets an organisation overview. Routes use hash URLs (`#/reports/<id>`), so every screen is linkable and the back button works behind any static file server. To add a page, create it under `pages/`, add a route in `App.tsx` and a menu entry in `lib/navigation.ts`.
|
||||||
|
|
||||||
|
### Branding and theme
|
||||||
|
|
||||||
|
The UI uses the Celtic logo and the colours taken from it.
|
||||||
|
|
||||||
|
| Token | Value | Used for |
|
||||||
|
|---|---|---|
|
||||||
|
| Brand blue | `#285AA8` (dark `#23509A`) | Primary buttons, links, active navigation, sign-in panel |
|
||||||
|
| Brand orange | `#E95C00` | Small accents (sign-in panel highlight, logo star) |
|
||||||
|
| Brand grey | `#808080` | The logo's dot; text and borders use a neutral grey scale |
|
||||||
|
|
||||||
|
- The logo is `web/public/celtic-logo.svg`; it is shown in the sidebar, on the sign-in page and as the browser-tab icon. Replace that one file to change it everywhere in the web app.
|
||||||
|
- All colours, radii, shadows and sizes are CSS variables in `web/src/styles/tokens.css` — change `--brand-*` there to re-theme the whole app. Status colours (green approved, amber in review, red returned) are semantic and intentionally not brand-coloured.
|
||||||
|
- The PDF letterhead is text (company details from the `PDF_COMPANY_*` settings) and shares its own stylesheet in `app/pdf/templates/base.html`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Roles and permissions
|
||||||
|
|
||||||
|
| Role | Can do |
|
||||||
|
|---|---|
|
||||||
|
| **MR** | File and edit own DCRs while `DRAFT`/`RETURNED`; submit; edit company forms |
|
||||||
|
| **AM** | Review DCRs of own headquarters: approve or return; sees only the approval forms (Tour Plan, Standard Tour Plan, Fare Chart) |
|
||||||
|
| **GM** | Read-only: view reports, users and headquarters across the company; no approval step |
|
||||||
|
| **ADMIN** | Provision users, headquarters and masters. **Cannot approve or read report content** |
|
||||||
|
|
||||||
|
Permissions are checked in two separate layers, because most RBAC bugs live in the gap between them:
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Layer 1 — WHAT may this role do?
|
||||||
|
current_user: User = Depends(require_role(Role.MR))
|
||||||
|
|
||||||
|
# Layer 2 — WHOSE data may this specific user touch?
|
||||||
|
await assert_can_view_dcr(db, current_user, dcr)
|
||||||
|
```
|
||||||
|
|
||||||
|
"AM" is a role; "AM *of this headquarters*" is a scope. Both are mandatory on scoped endpoints, and each has a negative test asserting **403** — not 404 or an empty 200 — so a scope bug cannot hide behind an ambiguous response.
|
||||||
|
|
||||||
|
The System Administrator can never approve: `ADMIN` matches no transition in the state machine, so the audit trail stays evidence that a manager made the decision.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## The approval workflow
|
||||||
|
|
||||||
|
```
|
||||||
|
DRAFT ──submit(MR)──► PENDING_AM ──approve(AM)──► APPROVED (terminal, immutable)
|
||||||
|
▲ │
|
||||||
|
│ └──return(AM)──┐
|
||||||
|
└──────submit(MR)───── RETURNED ◄───────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
- `RETURNED` records who returned it in the `returned_by_role` column. There is no General Manager stage; the GM is a read-only role.
|
||||||
|
- `APPROVED` is both "finally approved" and "locked": immutability is a property of the state, enforced in one guard, so there is no window where a report is approved but still editable.
|
||||||
|
- Managers change state and add comments; they never edit another person's call rows.
|
||||||
|
- Returning a report requires a reason (`MIN_RETURN_REASON_LENGTH`).
|
||||||
|
|
||||||
|
The whole workflow is `app/approvals/state_machine.py`, a table of transitions with the role allowed to make each one.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Company forms and PDFs
|
||||||
|
|
||||||
|
The `csv_data` module exposes the company's paper forms as editable tables, importable from the CSV files in the repository root.
|
||||||
|
|
||||||
|
| Form | Table | Layout highlights |
|
||||||
|
|---|---|---|
|
||||||
|
| Standard Tour Plan ¹ | `standard_tour_plan` | Route places, place count |
|
||||||
|
| Tour Plan ¹ | `tour_plan` | Date/from/to, POB total, stockist-visit count |
|
||||||
|
| Fare Chart ¹ | `fare_chart` | Travel log with total kilometers |
|
||||||
|
| Area Covered | `area_covered` | Area coverage and sale objectives |
|
||||||
|
| Core Doctor Call Conversion | `core_dr_call_conversion` | Doctor follow-up with status summary |
|
||||||
|
| Field Activity Report | `field_activity_report` | Daily activity, totals and call averages |
|
||||||
|
| Sales and Stock Statement | `sales_and_stock_statement` | Opening/receipt/sale/closing with value totals |
|
||||||
|
| Sales Projection | `sales_projection` | Landscape, product-wise projection |
|
||||||
|
| Weekly Report | `weekly_report` | One page per saved report |
|
||||||
|
| Daily Call Report (CSV) | `daily_call_report_csv` | Doctor and chemist sections (not exposed in the UI) |
|
||||||
|
|
||||||
|
¹ *Approval forms* — the AM can only see these, and their PDF carries the AM approval signature line.
|
||||||
|
|
||||||
|
**Approval forms are per MR.** Tour Plan, Standard Tour Plan and Fare Chart rows belong to the MR who entered them (`owner_user_id`), each MR sees and numbers only their own, and the approval (`form_approval`) is kept per form *and* MR. A request goes only to the Area Manager who currently manages that MR's headquarters: any other Area Manager gets a 403 and never sees it in their list, and an MR whose headquarters has no Area Manager cannot send a form. Editing an MR's rows withdraws only that MR's approval. An admin fills a form in on behalf of one chosen MR and can never approve.
|
||||||
|
|
||||||
|
**Monthly download.** Forms with a month (Sales Projection, Weekly Report, Field Activity Report, Core Doctor Call Conversion, Area Covered, Sales and Stock Statement) get a Month selector. The table and the PDF (`GET /csv-data/{form}/pdf?month=November`) then cover that month only; a month with no rows is refused rather than printed blank.
|
||||||
|
|
||||||
|
**How PDFs are built.** The DCR (`dcr.html`) extends the stylesheet `app/pdf/templates/base.html`. The company forms do **not**: each is a copy of the company's printed form — same letterhead, title, column headings, column proportions, number of ruled lines and signature block — built from `app/pdf/templates/forms/_form_base.html` plus one small template per form. `app/pdf/forms.py` decides what each form prints (headings, widths, how many blank lines); stored rows fill the lines from the top, and rows beyond the printed length continue on the next page with the header repeated. Fonts: Liberation Sans/Serif and Carlito (the Arial / Times / Calibri look-alikes of the printed forms), with DejaVu as fallback.
|
||||||
|
|
||||||
|
- `GET /api/v1/csv-data/{table}/pdf` prints **every stored row**; `…/rows/{id}/pdf` prints one row.
|
||||||
|
- Blank numbered lines pad each form to its printed length; longer data is never truncated.
|
||||||
|
- Identity fields (name, headquarter, month) are gathered from all rows, and for an MR always reflect the logged-in account.
|
||||||
|
|
||||||
|
**Importing data.** `python -m scripts.import_csv_data` loads the CSV files from the repo root. It **replaces** the contents of every form table — never run it against a database holding real data — use `python -m scripts.import_csv_data --only-empty` instead, which loads only tables that have no rows (e.g. the product lists) and never deletes anything. It is deliberately not part of container start-up, and the CSVs are not in the Docker image.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## API overview
|
||||||
|
|
||||||
|
Base path `/api/v1`; interactive documentation at `/docs` and `/redoc`, schema at `/openapi.json`.
|
||||||
|
|
||||||
|
| Module | Prefix | Purpose |
|
||||||
|
|---|---|---|
|
||||||
|
| auth | `/auth` | Login, refresh (rotating tokens), logout, current user |
|
||||||
|
| users | `/users` | User administration and the MR profile |
|
||||||
|
| organization | `/headquarters` | Headquarters and AM↔HQ mapping |
|
||||||
|
| doctors, chemists | `/doctors`, `/chemists` | Masters and MR assignment |
|
||||||
|
| products | `/products` | Product master and stock inventory list |
|
||||||
|
| reports | `/dcr` | DCR CRUD, calls, submit / return / approve, PDF |
|
||||||
|
| audit | `/audit` | Read access to the audit log |
|
||||||
|
| csv_data | `/csv-data` | Company form tables, rows and PDFs |
|
||||||
|
|
||||||
|
Errors use one envelope: `{"error": {"code": "…", "message": "…", "details": {…}}}`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Project layout
|
||||||
|
|
||||||
|
```
|
||||||
|
app/
|
||||||
|
├── main.py App factory, error envelope, CORS, production preflight
|
||||||
|
├── config/ Pydantic settings
|
||||||
|
├── database/ Engine, session, declarative base, model registry
|
||||||
|
├── common/ Enums, exceptions, base repository, helpers
|
||||||
|
├── auth/ JWT, argon2, refresh rotation, permission dependencies
|
||||||
|
├── users/ organization/ doctors/ chemists/ products/ Masters
|
||||||
|
├── reports/ DailyCallReport, DoctorCall, ChemistCall ← core domain
|
||||||
|
├── approvals/ The state machine ← the rules live here
|
||||||
|
├── audit/ Append-only log
|
||||||
|
├── csv_data/ Company form tables and their endpoints
|
||||||
|
├── pdf/ service.py, forms.py, templates/ (base, dcr, forms/*)
|
||||||
|
└── api/v1/ Router mount point
|
||||||
|
alembic/ Migrations
|
||||||
|
scripts/ seed, CSV import, audit hardening SQL, container entrypoint
|
||||||
|
web/ React application (its own Dockerfile) — see "Web application"
|
||||||
|
tests/ unit/, integration/, e2e/
|
||||||
|
```
|
||||||
|
|
||||||
|
Domain modules share the same file set, so a new module is a copy of a folder: `models.py` (ORM), `schemas.py` (Pydantic), `service.py` (business rules, transactions, audit calls) and `router.py` (HTTP only).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Design decisions
|
||||||
|
|
||||||
|
**Database-enforced constraints.** Under concurrency only the database can guarantee these, so they are constraints, not just service checks:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- One report per MR per calendar day
|
||||||
|
ALTER TABLE daily_call_report ADD CONSTRAINT uq_dcr_mr_date UNIQUE (mr_user_id, report_date);
|
||||||
|
|
||||||
|
-- No duplicate doctor call within one report
|
||||||
|
ALTER TABLE doctor_call ADD CONSTRAINT uq_call_dcr_doctor UNIQUE (dcr_id, doctor_id);
|
||||||
|
|
||||||
|
-- Exactly one active Area Manager per headquarters
|
||||||
|
CREATE UNIQUE INDEX uq_active_am_per_hq ON am_headquarters (headquarters_id)
|
||||||
|
WHERE effective_to IS NULL;
|
||||||
|
```
|
||||||
|
|
||||||
|
`tests/integration/test_db_constraints.py` proves each rejects the bad case *and* permits the good one.
|
||||||
|
|
||||||
|
**Tables deliberately not created.** The original brief listed 28 tables; the core domain uses far fewer:
|
||||||
|
|
||||||
|
| Not created | Instead |
|
||||||
|
|---|---|
|
||||||
|
| `role` | `user.role` enum — four fixed roles; a lookup table adds a join to every request |
|
||||||
|
| `mr_profile`, `area_manager_profile` | Merged into `user` |
|
||||||
|
| `area_territory` | Merged into `headquarters` — the HQ *is* the territory |
|
||||||
|
| `mr_assignment` | `user.headquarters_id` — an MR has exactly one HQ |
|
||||||
|
| `core_doctor_conversion` | `doctor.is_core_doctor` + `doctor_call.conversion_status` |
|
||||||
|
| `comments` | `audit_log.comment` — every comment attaches to a state change |
|
||||||
|
| `approval_history` | A filtered query over `audit_log` — one source of truth |
|
||||||
|
|
||||||
|
**Single-VPS deployment.** No Kubernetes, message broker or microservices: one company and a handful of MRs do not need them, and each extra piece is something to operate.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Tests run against a real PostgreSQL database — never SQLite. The system relies on partial unique indexes, composite uniques and `jsonb`, which SQLite does not implement the same way.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make dev-db # starts Postgres and creates pharma_test
|
||||||
|
export TEST_DATABASE_URL=postgresql+asyncpg://pharma:<password>@localhost:5432/pharma_test
|
||||||
|
pytest -q # everything
|
||||||
|
pytest tests/unit -q # state machine, PDF layouts — see note below
|
||||||
|
```
|
||||||
|
|
||||||
|
`tests/unit` is mostly pure logic (state machine, form PDF view-models and rendering), but a couple of tests there use the database. `make lint` runs ruff.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Production checklist
|
||||||
|
|
||||||
|
1. **Set a real `SECRET_KEY`** (64 random characters) and `POSTGRES_PASSWORD`, from a secrets manager — never in the repo.
|
||||||
|
2. **Run `scripts/harden_audit.sql`** once as a superuser to make `audit_log` genuinely append-only (revokes UPDATE/DELETE from the app role, plus a trigger as a backstop). Then connect the API as the `pharma_app` role it creates.
|
||||||
|
3. **Change every seeded password**, or do not seed at all and create real users.
|
||||||
|
4. **Set `DOMAIN`** to the real host name and, once HTTPS is confirmed, enable the commented HSTS header in `Caddyfile`.
|
||||||
|
5. **Confirm the blocking business rules** marked in code as `A1`–`A16` / `Q1`–`Q9`; the shipped defaults are assumptions, not decisions.
|
||||||
|
6. **Back up** `pgdata` and `pdfstore`, and **test a restore** — an untested backup is not a backup.
|
||||||
|
7. **Point an error tracker (e.g. Sentry) at the app** so production 500s surface as errors.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Known limitations
|
||||||
|
|
||||||
|
- **Company-form approval is per form, not per row.** The tour plan, standard tour plan and fare chart each have one server-stored approval state (`draft → pending → approved`). The MR sends a form that has rows, the Area Manager approves it, and the PDF signature is decided by the server. Any change to the rows withdraws the approval.
|
||||||
|
- **`web/node_modules` and `web/dist` are committed** to the repository (with stale build output) and should be untracked; Docker builds the app from source.
|
||||||
|
- The test suite needs a reachable PostgreSQL; some tests under `tests/unit` also need it.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
| Symptom | Fix |
|
||||||
|
|---|---|
|
||||||
|
| `required variable POSTGRES_PASSWORD is missing` | Create `.env` from `.env.example` and fill it in |
|
||||||
|
| API exits with `SECRET_KEY must be a random value…` | Set a `SECRET_KEY` of 32+ random characters |
|
||||||
|
| API exits with `WeasyPrint system libraries are required` | Use the provided image, or install Pango/HarfBuzz and DejaVu fonts |
|
||||||
|
| PDFs are plain text | WeasyPrint is unavailable (`/health` shows `"pdf_engine": "fallback"`) |
|
||||||
|
| `no pq wrapper available` from Alembic | `pip install --upgrade --force-reinstall "psycopg[binary]"` |
|
||||||
|
| Web build in Docker fails on `esbuild` | A host `node_modules` leaked in; check `web/.dockerignore` |
|
||||||
|
| `npm run build` fails with `tsc: Permission denied` | The committed `web/node_modules` has lost its executable bits. Delete it and run `npm ci` (or build through Docker, which does this) |
|
||||||
|
| `failed to bind host port 0.0.0.0:80 … address already in use` | Another service owns 80/443. Run `make setup` (or `make deploy`): it switches to free ports. Manually: `DOMAIN=:80`, `HTTP_PORT=2000`, `HTTPS_PORT=2443` in `.env` |
|
||||||
|
| `password authentication failed` after editing `POSTGRES_PASSWORD` | The database keeps its original password — see *Rotating the database password* |
|
||||||
|
| API container unhealthy / restarting | `docker compose logs api`: a weak `SECRET_KEY` or missing WeasyPrint stops a production start on purpose |
|
||||||
|
| Port 5432 in use during `make dev-db` | Set `DB_PORT` (e.g. `DB_PORT=5433`) and adjust `TEST_DATABASE_URL` |
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
NAME,HEADQUARTER,SL. NO.,PLACE
|
||||||
|
,,1,
|
||||||
|
,,2,
|
||||||
|
,,3,
|
||||||
|
,,4,
|
||||||
|
,,5,
|
||||||
|
,,6,
|
||||||
|
,,7,
|
||||||
|
,,8,
|
||||||
|
,,9,
|
||||||
|
,,10,
|
||||||
|
,,11,
|
||||||
|
,,12,
|
||||||
|
,,13,
|
||||||
|
,,14,
|
||||||
|
,,15,
|
||||||
|
,,16,
|
||||||
|
,,17,
|
||||||
|
,,18,
|
||||||
|
,,19,
|
||||||
|
,,20,
|
||||||
|
,,21,
|
||||||
|
,,22,
|
||||||
|
,,23,
|
||||||
|
,,24,
|
||||||
|
,,25,
|
||||||
|
@@ -0,0 +1,27 @@
|
|||||||
|
NAME,HEADQUARTER,DATE,MONTH,SL. NO.,NAME OF THE PRODUCT,OPENING,RECEIPT,SALE,CLOSING,VALUE IN PTS
|
||||||
|
,,,,1,Intezole-PD,,,,,
|
||||||
|
,,,,2,Intezole-RD,,,,,
|
||||||
|
,,,,3,Intezole-EL,,,,,
|
||||||
|
,,,,4,Intezole-ED,,,,,
|
||||||
|
,,,,5,Intezole-P40,,,,,
|
||||||
|
,,,,6,Fenmonac-P,,,,,
|
||||||
|
,,,,7,Fenmonac-SP,,,,,
|
||||||
|
,,,,8,Fenmonac-MR,,,,,
|
||||||
|
,,,,9,Penorenz-MR-4,,,,,
|
||||||
|
,,,,10,Celvadox-CV,,,,,
|
||||||
|
,,,,11,Amoclodax-CV-625,,,,,
|
||||||
|
,,,,12,Infezox-O,,,,,
|
||||||
|
,,,,13,Febrivance-Plus,,,,,
|
||||||
|
,,,,14,Hiferglobin-XT,,,,,
|
||||||
|
,,,,15,Vivacellix-360,,,,,
|
||||||
|
,,,,16,Healthovance-super,,,,,
|
||||||
|
,,,,17,Healthovance-Q10,,,,,
|
||||||
|
,,,,18,Megavance-Forte,,,,,
|
||||||
|
,,,,19,Bontra-Strong,,,,,
|
||||||
|
,,,,20,Bontra-max+,,,,,
|
||||||
|
,,,,21,Weakover,,,,,
|
||||||
|
,,,,22,Bellyfully,,,,,
|
||||||
|
,,,,23,Tummysure,,,,,
|
||||||
|
,,,,24,Viscosynth,,,,,
|
||||||
|
,,,,25,Hiferglobin-Red+,,,,,
|
||||||
|
,,,,26,Lypopink-Adv,,,,,
|
||||||
|
@@ -0,0 +1,26 @@
|
|||||||
|
NAME,HEADQUARTER,SL. NO.,DATE,FROM,TO,POB,STOCKIEST VISIT
|
||||||
|
,,1,,,,,
|
||||||
|
,,2,,,,,
|
||||||
|
,,3,,,,,
|
||||||
|
,,4,,,,,
|
||||||
|
,,5,,,,,
|
||||||
|
,,6,,,,,
|
||||||
|
,,7,,,,,
|
||||||
|
,,8,,,,,
|
||||||
|
,,9,,,,,
|
||||||
|
,,10,,,,,
|
||||||
|
,,11,,,,,
|
||||||
|
,,12,,,,,
|
||||||
|
,,13,,,,,
|
||||||
|
,,14,,,,,
|
||||||
|
,,15,,,,,
|
||||||
|
,,16,,,,,
|
||||||
|
,,17,,,,,
|
||||||
|
,,18,,,,,
|
||||||
|
,,19,,,,,
|
||||||
|
,,20,,,,,
|
||||||
|
,,21,,,,,
|
||||||
|
,,22,,,,,
|
||||||
|
,,23,,,,,
|
||||||
|
,,24,,,,,
|
||||||
|
,,25,,,,,
|
||||||
|
@@ -0,0 +1,2 @@
|
|||||||
|
EMPLOYEE NAME,DATE,HEADQUARTER,MONTH,NO. OF DAYS WORKED,NO. OF DOCTOR CALLED,NO. OF CHEMIST CALLED,POB BOOKED,SECONDARY SALES,POB OBJECTIVE,SECONDARY OBJECTIVE,PRODUCT - OFFER SCHEME BOOKED,PRODUCT - OFFER SCHEME OBJECTIVE
|
||||||
|
,,,,,,,,,,,,
|
||||||
|
+39
@@ -0,0 +1,39 @@
|
|||||||
|
[alembic]
|
||||||
|
script_location = alembic
|
||||||
|
prepend_sys_path = .
|
||||||
|
version_path_separator = os
|
||||||
|
# sqlalchemy.url is supplied at runtime from app.config.settings — never hard-code it here.
|
||||||
|
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARN
|
||||||
|
handlers = console
|
||||||
|
qualname =
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARN
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
from sqlalchemy import engine_from_config, pool
|
||||||
|
|
||||||
|
from app.config.settings import settings
|
||||||
|
from app.database.all_models import Base # noqa: F401 - registers every model
|
||||||
|
|
||||||
|
config = context.config
|
||||||
|
config.set_main_option("sqlalchemy.url", settings.sync_database_url)
|
||||||
|
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_offline() -> None:
|
||||||
|
context.configure(
|
||||||
|
url=settings.sync_database_url,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
dialect_opts={"paramstyle": "named"},
|
||||||
|
compare_type=True,
|
||||||
|
)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
connectable = engine_from_config(
|
||||||
|
config.get_section(config.config_ini_section, {}),
|
||||||
|
prefix="sqlalchemy.",
|
||||||
|
poolclass=pool.NullPool,
|
||||||
|
)
|
||||||
|
with connectable.connect() as connection:
|
||||||
|
context.configure(
|
||||||
|
connection=connection, target_metadata=target_metadata, compare_type=True
|
||||||
|
)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
"""
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
revision: str = ${repr(up_revision)}
|
||||||
|
down_revision: str | None = ${repr(down_revision)}
|
||||||
|
branch_labels: str | Sequence[str] | None = ${repr(branch_labels)}
|
||||||
|
depends_on: str | Sequence[str] | None = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
"""initial MVP schema
|
||||||
|
|
||||||
|
Revision ID: a40386dcf76c
|
||||||
|
Revises:
|
||||||
|
Create Date: 2026-09-10 13:54:30.431676
|
||||||
|
"""
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision: str = 'a40386dcf76c'
|
||||||
|
down_revision: str | None = None
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table('company',
|
||||||
|
sa.Column('name', sa.String(length=200), nullable=False),
|
||||||
|
sa.Column('address', sa.String(length=500), nullable=True),
|
||||||
|
sa.Column('is_active', sa.Boolean(), nullable=False),
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_table('headquarters',
|
||||||
|
sa.Column('company_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('code', sa.String(length=20), nullable=False),
|
||||||
|
sa.Column('name', sa.String(length=200), nullable=False),
|
||||||
|
sa.Column('district', sa.String(length=100), nullable=True),
|
||||||
|
sa.Column('state', sa.String(length=100), nullable=True),
|
||||||
|
sa.Column('is_active', sa.Boolean(), nullable=False),
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['company_id'], ['company.id'], ondelete='RESTRICT'),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('company_id', 'code', name='uq_hq_company_code')
|
||||||
|
)
|
||||||
|
op.create_table('chemist',
|
||||||
|
sa.Column('headquarters_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(length=200), nullable=False),
|
||||||
|
sa.Column('shop_address', sa.String(length=500), nullable=False),
|
||||||
|
sa.Column('contact_number', sa.String(length=20), nullable=True),
|
||||||
|
sa.Column('is_active', sa.Boolean(), nullable=False),
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['headquarters_id'], ['headquarters.id'], ondelete='RESTRICT'),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('headquarters_id', 'name', 'shop_address', name='uq_chemist_hq_name_shop')
|
||||||
|
)
|
||||||
|
op.create_table('doctor',
|
||||||
|
sa.Column('headquarters_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(length=200), nullable=False),
|
||||||
|
sa.Column('speciality', sa.String(length=100), nullable=True),
|
||||||
|
sa.Column('qualification', sa.String(length=100), nullable=True),
|
||||||
|
sa.Column('clinic_address', sa.String(length=500), nullable=False),
|
||||||
|
sa.Column('contact_number', sa.String(length=20), nullable=True),
|
||||||
|
sa.Column('is_core_doctor', sa.Boolean(), nullable=False),
|
||||||
|
sa.Column('is_active', sa.Boolean(), nullable=False),
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['headquarters_id'], ['headquarters.id'], ondelete='RESTRICT'),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('headquarters_id', 'name', 'clinic_address', name='uq_doctor_hq_name_clinic')
|
||||||
|
)
|
||||||
|
op.create_table('user',
|
||||||
|
sa.Column('company_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('email', sa.String(length=255), nullable=False),
|
||||||
|
sa.Column('password_hash', sa.String(length=255), nullable=False),
|
||||||
|
sa.Column('full_name', sa.String(length=200), nullable=False),
|
||||||
|
sa.Column('employee_code', sa.String(length=50), nullable=False),
|
||||||
|
sa.Column('phone', sa.String(length=20), nullable=True),
|
||||||
|
sa.Column('role', sa.Enum('ADMIN', 'GM', 'AM', 'MR', name='role_enum', native_enum=False, length=10), nullable=False),
|
||||||
|
sa.Column('headquarters_id', sa.UUID(), nullable=True),
|
||||||
|
sa.Column('is_active', sa.Boolean(), nullable=False),
|
||||||
|
sa.Column('failed_login_attempts', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.CheckConstraint("(role = 'MR' AND headquarters_id IS NOT NULL) OR (role <> 'MR' AND headquarters_id IS NULL)", name='ck_user_mr_requires_hq'),
|
||||||
|
sa.ForeignKeyConstraint(['company_id'], ['company.id'], ondelete='RESTRICT'),
|
||||||
|
sa.ForeignKeyConstraint(['headquarters_id'], ['headquarters.id'], ondelete='RESTRICT'),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('company_id', 'email', name='uq_user_company_email'),
|
||||||
|
sa.UniqueConstraint('company_id', 'employee_code', name='uq_user_company_empcode')
|
||||||
|
)
|
||||||
|
op.create_table('am_headquarters',
|
||||||
|
sa.Column('area_manager_user_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('headquarters_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('effective_from', sa.Date(), nullable=False),
|
||||||
|
sa.Column('effective_to', sa.Date(), nullable=True),
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['area_manager_user_id'], ['user.id'], ondelete='RESTRICT'),
|
||||||
|
sa.ForeignKeyConstraint(['headquarters_id'], ['headquarters.id'], ondelete='RESTRICT'),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index('uq_active_am_per_hq', 'am_headquarters', ['headquarters_id'], unique=True, postgresql_where=sa.text('effective_to IS NULL'))
|
||||||
|
op.create_table('audit_log',
|
||||||
|
sa.Column('actor_user_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('entity_type', sa.Enum('USER', 'HEADQUARTERS', 'DOCTOR', 'CHEMIST', 'DCR', name='entity_type_enum', native_enum=False, length=30), nullable=False),
|
||||||
|
sa.Column('entity_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('action', sa.Enum('CREATE', 'UPDATE', 'DELETE', 'SUBMIT', 'FORWARD', 'RETURN', 'APPROVE', 'ASSIGN', 'LOGIN', 'DEACTIVATE', name='audit_action_enum', native_enum=False, length=20), nullable=False),
|
||||||
|
sa.Column('before_data', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
|
||||||
|
sa.Column('after_data', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
|
||||||
|
sa.Column('comment', sa.Text(), nullable=True),
|
||||||
|
sa.Column('ip_address', sa.String(length=45), nullable=True),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['actor_user_id'], ['user.id'], ondelete='RESTRICT'),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_audit_log_created_at'), 'audit_log', ['created_at'], unique=False)
|
||||||
|
op.create_index(op.f('ix_audit_log_entity_id'), 'audit_log', ['entity_id'], unique=False)
|
||||||
|
op.create_index(op.f('ix_audit_log_entity_type'), 'audit_log', ['entity_type'], unique=False)
|
||||||
|
op.create_table('chemist_assignment',
|
||||||
|
sa.Column('chemist_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('mr_user_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('effective_from', sa.Date(), nullable=False),
|
||||||
|
sa.Column('effective_to', sa.Date(), nullable=True),
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['chemist_id'], ['chemist.id'], ondelete='CASCADE'),
|
||||||
|
sa.ForeignKeyConstraint(['mr_user_id'], ['user.id'], ondelete='RESTRICT'),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index('uq_active_chemist_assignment', 'chemist_assignment', ['chemist_id'], unique=True, postgresql_where=sa.text('effective_to IS NULL'))
|
||||||
|
op.create_table('daily_call_report',
|
||||||
|
sa.Column('mr_user_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('headquarters_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('report_date', sa.Date(), nullable=False),
|
||||||
|
sa.Column('status', sa.Enum('DRAFT', 'PENDING_AM', 'PENDING_GM', 'RETURNED', 'APPROVED', name='dcr_status_enum', native_enum=False, length=20), nullable=False),
|
||||||
|
sa.Column('current_am_user_id', sa.UUID(), nullable=True),
|
||||||
|
sa.Column('current_gm_user_id', sa.UUID(), nullable=True),
|
||||||
|
sa.Column('mr_remarks', sa.Text(), nullable=True),
|
||||||
|
sa.Column('return_reason', sa.Text(), nullable=True),
|
||||||
|
sa.Column('returned_by_role', sa.Enum('ADMIN', 'GM', 'AM', 'MR', name='role_enum', native_enum=False, length=10), nullable=True),
|
||||||
|
sa.Column('submitted_at', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column('approved_at', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column('pdf_path', sa.String(length=500), nullable=True),
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.CheckConstraint("(status = 'APPROVED' AND approved_at IS NOT NULL) OR (status <> 'APPROVED' AND approved_at IS NULL)", name='ck_dcr_approved_at'),
|
||||||
|
sa.ForeignKeyConstraint(['current_am_user_id'], ['user.id'], ondelete='RESTRICT'),
|
||||||
|
sa.ForeignKeyConstraint(['current_gm_user_id'], ['user.id'], ondelete='RESTRICT'),
|
||||||
|
sa.ForeignKeyConstraint(['headquarters_id'], ['headquarters.id'], ondelete='RESTRICT'),
|
||||||
|
sa.ForeignKeyConstraint(['mr_user_id'], ['user.id'], ondelete='RESTRICT'),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('mr_user_id', 'report_date', name='uq_dcr_mr_date')
|
||||||
|
)
|
||||||
|
op.create_table('doctor_assignment',
|
||||||
|
sa.Column('doctor_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('mr_user_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('effective_from', sa.Date(), nullable=False),
|
||||||
|
sa.Column('effective_to', sa.Date(), nullable=True),
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['doctor_id'], ['doctor.id'], ondelete='CASCADE'),
|
||||||
|
sa.ForeignKeyConstraint(['mr_user_id'], ['user.id'], ondelete='RESTRICT'),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index('uq_active_doctor_assignment', 'doctor_assignment', ['doctor_id'], unique=True, postgresql_where=sa.text('effective_to IS NULL'))
|
||||||
|
op.create_table('refresh_token',
|
||||||
|
sa.Column('user_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('token_hash', sa.String(length=64), nullable=False),
|
||||||
|
sa.Column('expires_at', sa.DateTime(timezone=True), nullable=False),
|
||||||
|
sa.Column('revoked', sa.Boolean(), nullable=False),
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ondelete='CASCADE'),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_refresh_token_token_hash'), 'refresh_token', ['token_hash'], unique=True)
|
||||||
|
op.create_index(op.f('ix_refresh_token_user_id'), 'refresh_token', ['user_id'], unique=False)
|
||||||
|
op.create_table('chemist_call',
|
||||||
|
sa.Column('dcr_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('chemist_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('visit_time', sa.Time(), nullable=False),
|
||||||
|
sa.Column('remarks', sa.Text(), nullable=True),
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['chemist_id'], ['chemist.id'], ondelete='RESTRICT'),
|
||||||
|
sa.ForeignKeyConstraint(['dcr_id'], ['daily_call_report.id'], ondelete='CASCADE'),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('dcr_id', 'chemist_id', name='uq_call_dcr_chemist')
|
||||||
|
)
|
||||||
|
op.create_table('doctor_call',
|
||||||
|
sa.Column('dcr_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('doctor_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('visit_time', sa.Time(), nullable=False),
|
||||||
|
sa.Column('call_outcome', sa.Enum('MET', 'NOT_AVAILABLE', 'RESCHEDULED', name='call_outcome_enum', native_enum=False, length=20), nullable=False),
|
||||||
|
sa.Column('conversion_status', sa.Enum('NOT_STARTED', 'IN_PROGRESS', 'CONVERTED', 'LOST', name='conversion_status_enum', native_enum=False, length=20), nullable=True),
|
||||||
|
sa.Column('remarks', sa.Text(), nullable=True),
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['dcr_id'], ['daily_call_report.id'], ondelete='CASCADE'),
|
||||||
|
sa.ForeignKeyConstraint(['doctor_id'], ['doctor.id'], ondelete='RESTRICT'),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('dcr_id', 'doctor_id', name='uq_call_dcr_doctor')
|
||||||
|
)
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_table('doctor_call')
|
||||||
|
op.drop_table('chemist_call')
|
||||||
|
op.drop_index(op.f('ix_refresh_token_user_id'), table_name='refresh_token')
|
||||||
|
op.drop_index(op.f('ix_refresh_token_token_hash'), table_name='refresh_token')
|
||||||
|
op.drop_table('refresh_token')
|
||||||
|
op.drop_index('uq_active_doctor_assignment', table_name='doctor_assignment', postgresql_where=sa.text('effective_to IS NULL'))
|
||||||
|
op.drop_table('doctor_assignment')
|
||||||
|
op.drop_table('daily_call_report')
|
||||||
|
op.drop_index('uq_active_chemist_assignment', table_name='chemist_assignment', postgresql_where=sa.text('effective_to IS NULL'))
|
||||||
|
op.drop_table('chemist_assignment')
|
||||||
|
op.drop_index(op.f('ix_audit_log_entity_type'), table_name='audit_log')
|
||||||
|
op.drop_index(op.f('ix_audit_log_entity_id'), table_name='audit_log')
|
||||||
|
op.drop_index(op.f('ix_audit_log_created_at'), table_name='audit_log')
|
||||||
|
op.drop_table('audit_log')
|
||||||
|
op.drop_index('uq_active_am_per_hq', table_name='am_headquarters', postgresql_where=sa.text('effective_to IS NULL'))
|
||||||
|
op.drop_table('am_headquarters')
|
||||||
|
op.drop_table('user')
|
||||||
|
op.drop_table('doctor')
|
||||||
|
op.drop_table('chemist')
|
||||||
|
op.drop_table('headquarters')
|
||||||
|
op.drop_table('company')
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"""make AM the final approver and add the product master
|
||||||
|
|
||||||
|
Revision ID: b71d4c22a917
|
||||||
|
Revises: a40386dcf76c
|
||||||
|
Create Date: 2026-09-17
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "b71d4c22a917"
|
||||||
|
down_revision: str | None = "a40386dcf76c"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# Native enums are deliberately disabled in the initial schema. Existing reports
|
||||||
|
# that were waiting for GM are returned to the AM queue for a final decision.
|
||||||
|
op.execute("UPDATE daily_call_report SET status = 'PENDING_AM' WHERE status = 'PENDING_GM'")
|
||||||
|
op.create_table(
|
||||||
|
"product",
|
||||||
|
sa.Column("company_id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("name", sa.String(length=200), nullable=False),
|
||||||
|
sa.Column("pack", sa.String(length=100), nullable=True),
|
||||||
|
sa.Column("unit", sa.String(length=50), nullable=True),
|
||||||
|
sa.Column("is_active", sa.Boolean(), nullable=False, server_default=sa.true()),
|
||||||
|
sa.Column("id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"created_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("now()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"updated_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("now()"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(["company_id"], ["company.id"], ondelete="RESTRICT"),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
sa.UniqueConstraint("company_id", "name", name="uq_product_company_name"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("product")
|
||||||
|
# A downgrade cannot safely reinstate the former GM queue assignment. Reopen the
|
||||||
|
# reports in the old AM queue rather than fabricating a GM approval decision.
|
||||||
|
op.execute("UPDATE daily_call_report SET status = 'PENDING_AM' WHERE status = 'PENDING_AM'")
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
"""store non-MVP CSV source rows
|
||||||
|
|
||||||
|
Revision ID: c2e7f5b1a9d4
|
||||||
|
Revises: b71d4c22a917
|
||||||
|
Create Date: 2026-09-18
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "c2e7f5b1a9d4"
|
||||||
|
down_revision: str | None = "b71d4c22a917"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"csv_import_row",
|
||||||
|
sa.Column("id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("source_file", sa.String(length=255), nullable=False),
|
||||||
|
sa.Column("row_number", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("data", sa.JSON(), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
sa.UniqueConstraint("source_file", "row_number", name="uq_csv_import_file_row"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("csv_import_row")
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
"""replace the old single CSV table with individual CSV tables
|
||||||
|
|
||||||
|
Revision ID: d4f8a6c2e1b0
|
||||||
|
Revises: c2e7f5b1a9d4
|
||||||
|
Create Date: 2026-09-18
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "d4f8a6c2e1b0"
|
||||||
|
down_revision: str | None = "c2e7f5b1a9d4"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
TABLE_COLUMNS = {
|
||||||
|
"weekly_report": ["employee_name", "report_date", "headquarter", "month", "no_of_days_worked", "no_of_doctor_called", "no_of_chemist_called", "pob_booked", "secondary_sales", "pob_objective", "secondary_objective", "product_offer_scheme_booked", "product_offer_scheme_objective"],
|
||||||
|
"field_activity_report": ["name", "headquarter", "month", "report_date", "station_worked", "no_of_doctors_called", "no_of_chemists_pds_called", "doctor_call_avg", "chemist_call_avg"],
|
||||||
|
"fare_chart": ["name", "headquarter", "serial_no", "report_date", "from_location", "to_location", "kilometers_km"],
|
||||||
|
"daily_call_report_csv": ["name", "headquarter", "report_date", "month", "doctor_sr_no", "doctor_name", "qualification", "product_promote", "product_sample", "remarks", "chemist_sr_no", "chemist_name", "pob", "stockist_visit", "order_value"],
|
||||||
|
"core_dr_call_conversion": ["name", "headquarter", "month", "doctor_name", "date_of_visit", "product_targeted", "status"],
|
||||||
|
"area_covered": ["name", "headquarter", "month", "sale_status", "area_to_cover", "sale_objective", "status"],
|
||||||
|
"sales_and_stock_statement": ["name", "headquarter", "report_date", "month", "serial_no", "product_name", "opening", "receipt", "sale", "closing", "value_in_pts"],
|
||||||
|
"tour_plan": ["name", "headquarter", "serial_no", "report_date", "from_location", "to_location", "pob", "stockiest_visit"],
|
||||||
|
"standard_tour_plan": ["name", "headquarter", "serial_no", "place"],
|
||||||
|
"sales_projection": ["serial_no", "product_name", "pts", "secondary_qty", "value", "closing", "secondary_value", "aug_sales", "value_2"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.drop_table("csv_import_row")
|
||||||
|
for table_name, columns in TABLE_COLUMNS.items():
|
||||||
|
op.create_table(
|
||||||
|
table_name,
|
||||||
|
sa.Column("id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("source_row_number", sa.Integer(), nullable=False),
|
||||||
|
*(sa.Column(column, sa.Text(), nullable=True) for column in columns),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
sa.UniqueConstraint("source_row_number", name=f"uq_{table_name}_source_row"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
for table_name in reversed(TABLE_COLUMNS):
|
||||||
|
op.drop_table(table_name)
|
||||||
|
op.create_table(
|
||||||
|
"csv_import_row",
|
||||||
|
sa.Column("id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("source_file", sa.String(length=255), nullable=False),
|
||||||
|
sa.Column("row_number", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("data", sa.JSON(), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
sa.UniqueConstraint("source_file", "row_number", name="uq_csv_import_file_row"),
|
||||||
|
)
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"""add the sales projection CSV table
|
||||||
|
|
||||||
|
Revision ID: e5a1c7d9f3b2
|
||||||
|
Revises: d4f8a6c2e1b0
|
||||||
|
Create Date: 2026-09-18
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "e5a1c7d9f3b2"
|
||||||
|
down_revision: str | None = "d4f8a6c2e1b0"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# A pre-migration local table may exist with the old product-master schema.
|
||||||
|
# The CSV is the canonical source, so recreate it using the shared CSV-table shape.
|
||||||
|
op.execute("DROP TABLE IF EXISTS sales_projection")
|
||||||
|
op.create_table(
|
||||||
|
"sales_projection",
|
||||||
|
sa.Column("id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("source_row_number", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("serial_no", sa.Text(), nullable=True),
|
||||||
|
sa.Column("product_name", sa.Text(), nullable=True),
|
||||||
|
sa.Column("pts", sa.Text(), nullable=True),
|
||||||
|
sa.Column("secondary_qty", sa.Text(), nullable=True),
|
||||||
|
sa.Column("value", sa.Text(), nullable=True),
|
||||||
|
sa.Column("closing", sa.Text(), nullable=True),
|
||||||
|
sa.Column("secondary_value", sa.Text(), nullable=True),
|
||||||
|
sa.Column("aug_sales", sa.Text(), nullable=True),
|
||||||
|
sa.Column("value_2", sa.Text(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
sa.UniqueConstraint("source_row_number", name="uq_sales_projection_source_row"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("sales_projection")
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""add account identity fields to sales projection
|
||||||
|
|
||||||
|
Revision ID: f6b2d8e4a1c3
|
||||||
|
Revises: e5a1c7d9f3b2
|
||||||
|
Create Date: 2026-09-18
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "f6b2d8e4a1c3"
|
||||||
|
down_revision: str | None = "e5a1c7d9f3b2"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("sales_projection", sa.Column("name", sa.Text(), nullable=True))
|
||||||
|
op.add_column("sales_projection", sa.Column("headquarter", sa.Text(), nullable=True))
|
||||||
|
op.execute(
|
||||||
|
'''UPDATE "sales_projection" AS projection
|
||||||
|
SET name = account.full_name,
|
||||||
|
headquarter = headquarters.name
|
||||||
|
FROM "user" AS account
|
||||||
|
LEFT JOIN headquarters ON headquarters.id = account.headquarters_id
|
||||||
|
WHERE account.role = 'MR' '''
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_column("sales_projection", "headquarter")
|
||||||
|
op.drop_column("sales_projection", "name")
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
"""add date and month fields to sales projection
|
||||||
|
|
||||||
|
Revision ID: g7c3e9f5b2d4
|
||||||
|
Revises: f6b2d8e4a1c3
|
||||||
|
Create Date: 2026-09-19
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "g7c3e9f5b2d4"
|
||||||
|
down_revision: str | None = "f6b2d8e4a1c3"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("sales_projection", sa.Column("report_date", sa.Text(), nullable=True))
|
||||||
|
op.add_column("sales_projection", sa.Column("month", sa.Text(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_column("sales_projection", "month")
|
||||||
|
op.drop_column("sales_projection", "report_date")
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
"""add the stock inventory table behind the Products page and load stock.csv
|
||||||
|
|
||||||
|
The Products page (GET /products/stock-inventory) reads ``stock_inventory``, which no
|
||||||
|
migration created — the endpoint returned 500 on any database built from migrations.
|
||||||
|
The rows are the company's product / pack / quantity list (stock.csv). They are inlined
|
||||||
|
here because the CSV files are not part of the Docker image.
|
||||||
|
|
||||||
|
Revision ID: h8d4f0a6c3e5
|
||||||
|
Revises: g7c3e9f5b2d4
|
||||||
|
Create Date: 2026-09-20
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "h8d4f0a6c3e5"
|
||||||
|
down_revision: str | None = "g7c3e9f5b2d4"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
# (serial_no, product_name, pack, quantity, unit) — straight from stock.csv
|
||||||
|
STOCK_ROWS = [
|
||||||
|
(1, 'INTEZOLE-PD', '10X10 CAP', '10+2', None),
|
||||||
|
(2, 'INTEZOLE-RD', '10X10 CAP', '10+2', None),
|
||||||
|
(3, 'INTEZOLE-EL', '10X10 CAP', '10+2', None),
|
||||||
|
(4, 'INTEZOLE-ED', '10X10 CAP', '10+2', None),
|
||||||
|
(5, 'INTEZOLE-P40', '10X10 TAB', '10+1', None),
|
||||||
|
(6, 'FENMONAC-P', '10X10 TAB', '10+1', None),
|
||||||
|
(7, 'FENMONAC-SP', '10X10 TAB', '10+1', None),
|
||||||
|
(8, 'FENMONAC-MR', '10X10 TAB', '10+1', None),
|
||||||
|
(9, 'PENORENZ-MR 4', '10X10 TAB', '10+1', None),
|
||||||
|
(10, 'CELVADOX-CV', '10X1X10 TAB', 'NA', None),
|
||||||
|
(11, 'AMOCLADOV-CV 625', '10X1X10 TAB', '10+1', None),
|
||||||
|
(12, 'INFEZOX-O', '10X10 TAB', '9+1', None),
|
||||||
|
(13, 'FEBRIVANCE-PLUS', '10X10 TAB', '10+2', None),
|
||||||
|
(14, 'HIFERGLOBIN-XT', '10X10 TAB', '9+1', None),
|
||||||
|
(15, 'VIVACELLIX-360', '10X10 TAB', 'NA', None),
|
||||||
|
(16, 'HEALTHOVANCE-SUPER', '10X10 TAB', '9+1', None),
|
||||||
|
(17, 'HEALTHOVANCE-Q10', '10X10 TAB', 'NA', None),
|
||||||
|
(18, 'MEGAVANCE-FORTE', '10X1X10CAP', '10+2', None),
|
||||||
|
(19, 'BONETRA-STRONG', '10X1X10CAP', '9+1', None),
|
||||||
|
(20, 'BONETRA-MAX+', '10X1X10CAP', '9+1', None),
|
||||||
|
(21, 'WEAKOVER', '200ML SYRUP', '11+1', None),
|
||||||
|
(22, 'BELLYFULLY', '200ML SYRUP', '11+1', None),
|
||||||
|
(23, 'TUMMY SURE', '200ML SYRUP', '14+1', None),
|
||||||
|
(24, 'VISCOSYNTH', '200ML SYRUP', '11+1', None),
|
||||||
|
(25, 'HIFERGLOBIN-RED+', '200ML SYRUP', '14+1', None),
|
||||||
|
(26, 'LYPOPINK-ADV', '200ML SYRUP', 'NA', None),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
stock = op.create_table(
|
||||||
|
"stock_inventory",
|
||||||
|
sa.Column("id", sa.Integer(), sa.Identity(), primary_key=True),
|
||||||
|
sa.Column("serial_no", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("product_name", sa.Text(), nullable=False),
|
||||||
|
sa.Column("pack", sa.Text(), nullable=True),
|
||||||
|
sa.Column("quantity", sa.Text(), nullable=True),
|
||||||
|
sa.Column("unit", sa.Text(), nullable=True),
|
||||||
|
sa.UniqueConstraint("serial_no", name="uq_stock_inventory_serial_no"),
|
||||||
|
)
|
||||||
|
op.bulk_insert(
|
||||||
|
stock,
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"serial_no": serial_no,
|
||||||
|
"product_name": product_name,
|
||||||
|
"pack": pack,
|
||||||
|
"quantity": quantity,
|
||||||
|
"unit": unit,
|
||||||
|
}
|
||||||
|
for serial_no, product_name, pack, quantity, unit in STOCK_ROWS
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("stock_inventory")
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""remove the General Manager approval stage
|
||||||
|
|
||||||
|
The Area Manager is the final approver: PENDING_AM -> APPROVED | RETURNED. Any report
|
||||||
|
still sitting in the retired PENDING_GM status goes back to the Area Manager's queue.
|
||||||
|
Historical audit rows (including FORWARD) are left untouched.
|
||||||
|
|
||||||
|
Revision ID: i9e5a1b7d4f6
|
||||||
|
Revises: h8d4f0a6c3e5
|
||||||
|
Create Date: 2026-09-21
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "i9e5a1b7d4f6"
|
||||||
|
down_revision: str | None = "h8d4f0a6c3e5"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.execute("UPDATE daily_call_report SET status = 'PENDING_AM' WHERE status = 'PENDING_GM'")
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# Nothing to restore: the GM stage no longer exists in the code.
|
||||||
|
pass
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""capture the printed Daily Call Report's extra fields
|
||||||
|
|
||||||
|
Doctor visits gain PRODUCT PROMOTE / PRODUCT SAMPLE, chemist visits gain POB, and the
|
||||||
|
report gains STOCKIST VISIT / ORDER, so the approved PDF can reproduce the paper form.
|
||||||
|
All nullable: existing reports are unaffected.
|
||||||
|
|
||||||
|
Revision ID: j0f6b2c8e5a7
|
||||||
|
Revises: i9e5a1b7d4f6
|
||||||
|
Create Date: 2026-09-21
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "j0f6b2c8e5a7"
|
||||||
|
down_revision: str | None = "i9e5a1b7d4f6"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("doctor_call", sa.Column("product_promote", sa.String(length=200), nullable=True))
|
||||||
|
op.add_column("doctor_call", sa.Column("product_sample", sa.String(length=200), nullable=True))
|
||||||
|
op.add_column("chemist_call", sa.Column("pob", sa.String(length=100), nullable=True))
|
||||||
|
op.add_column("daily_call_report", sa.Column("stockist_visit", sa.String(length=200), nullable=True))
|
||||||
|
op.add_column("daily_call_report", sa.Column("order_value", sa.String(length=100), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_column("daily_call_report", "order_value")
|
||||||
|
op.drop_column("daily_call_report", "stockist_visit")
|
||||||
|
op.drop_column("chemist_call", "pob")
|
||||||
|
op.drop_column("doctor_call", "product_sample")
|
||||||
|
op.drop_column("doctor_call", "product_promote")
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""store company-form approvals on the server
|
||||||
|
|
||||||
|
Until now the "approved / pending" state of the tour plan, standard tour plan and fare
|
||||||
|
chart lived in each browser's local storage: an Area Manager's approval was invisible to
|
||||||
|
the MR, and the PDF signature was whatever the browser sent. It is now a table.
|
||||||
|
|
||||||
|
Revision ID: k1a7c3d9f6b8
|
||||||
|
Revises: j0f6b2c8e5a7
|
||||||
|
Create Date: 2026-09-21
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "k1a7c3d9f6b8"
|
||||||
|
down_revision: str | None = "j0f6b2c8e5a7"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"form_approval",
|
||||||
|
sa.Column("table_name", sa.String(length=64), primary_key=True),
|
||||||
|
sa.Column("status", sa.String(length=10), nullable=False, server_default="draft"),
|
||||||
|
sa.Column("requested_by_user_id", sa.UUID(), sa.ForeignKey("user.id", ondelete="SET NULL"), nullable=True),
|
||||||
|
sa.Column("approved_by_user_id", sa.UUID(), sa.ForeignKey("user.id", ondelete="SET NULL"), nullable=True),
|
||||||
|
sa.Column("approved_by_name", sa.String(length=200), nullable=True),
|
||||||
|
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("form_approval")
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
"""company forms belong to one MR, and so does their approval
|
||||||
|
|
||||||
|
The tour plan, standard tour plan and fare chart were one shared table with one shared
|
||||||
|
approval, so any Area Manager could sign for any MR. Each row now records its owner (the MR),
|
||||||
|
and an approval is kept per (form, MR) so it can only be requested from, and signed by, the
|
||||||
|
Area Manager who manages that MR's headquarters.
|
||||||
|
|
||||||
|
Revision ID: l2b8d4e0a7c9
|
||||||
|
Revises: k1a7c3d9f6b8
|
||||||
|
Create Date: 2026-09-21
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "l2b8d4e0a7c9"
|
||||||
|
down_revision: str | None = "k1a7c3d9f6b8"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
OWNED = ("tour_plan", "standard_tour_plan", "fare_chart")
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("form_approval", sa.Column("owner_user_id", sa.UUID(), nullable=True))
|
||||||
|
# The MR who sent a form for approval is the one whose data it was.
|
||||||
|
op.execute("UPDATE form_approval SET owner_user_id = requested_by_user_id")
|
||||||
|
op.execute("DELETE FROM form_approval WHERE owner_user_id IS NULL")
|
||||||
|
op.drop_constraint("form_approval_pkey", "form_approval", type_="primary")
|
||||||
|
op.alter_column("form_approval", "owner_user_id", nullable=False)
|
||||||
|
op.create_primary_key("form_approval_pkey", "form_approval", ["table_name", "owner_user_id"])
|
||||||
|
op.create_foreign_key(
|
||||||
|
"fk_form_approval_owner", "form_approval", "user", ["owner_user_id"], ["id"], ondelete="CASCADE"
|
||||||
|
)
|
||||||
|
|
||||||
|
for table in OWNED:
|
||||||
|
op.add_column(table, sa.Column("owner_user_id", sa.UUID(), sa.ForeignKey("user.id", ondelete="SET NULL"), nullable=True))
|
||||||
|
op.create_index(f"ix_{table}_owner", table, ["owner_user_id"])
|
||||||
|
# Rows that existed belong to the MR who put the form up for approval, with that MR's identity.
|
||||||
|
op.execute(
|
||||||
|
f'''UPDATE "{table}" t
|
||||||
|
SET owner_user_id = a.owner_user_id, name = u.full_name, headquarter = h.name
|
||||||
|
FROM form_approval a
|
||||||
|
JOIN "user" u ON u.id = a.owner_user_id
|
||||||
|
LEFT JOIN headquarters h ON h.id = u.headquarters_id
|
||||||
|
WHERE a.table_name = '{table}' '''
|
||||||
|
)
|
||||||
|
|
||||||
|
# An approval by an Area Manager who does not manage the MR's headquarters was never valid:
|
||||||
|
# send it back to the right one.
|
||||||
|
op.execute(
|
||||||
|
'''UPDATE form_approval a
|
||||||
|
SET status = 'pending', approved_by_user_id = NULL, approved_by_name = NULL
|
||||||
|
FROM "user" u
|
||||||
|
WHERE u.id = a.owner_user_id AND a.status = 'approved'
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM am_headquarters m
|
||||||
|
WHERE m.headquarters_id = u.headquarters_id AND m.effective_to IS NULL
|
||||||
|
AND m.area_manager_user_id = a.approved_by_user_id)'''
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
for table in OWNED:
|
||||||
|
op.drop_index(f"ix_{table}_owner", table_name=table)
|
||||||
|
op.drop_column(table, "owner_user_id")
|
||||||
|
op.drop_constraint("fk_form_approval_owner", "form_approval", type_="foreignkey")
|
||||||
|
op.drop_constraint("form_approval_pkey", "form_approval", type_="primary")
|
||||||
|
op.execute(
|
||||||
|
"DELETE FROM form_approval a USING form_approval b "
|
||||||
|
"WHERE a.table_name = b.table_name AND a.ctid < b.ctid"
|
||||||
|
)
|
||||||
|
op.drop_column("form_approval", "owner_user_id")
|
||||||
|
op.create_primary_key("form_approval_pkey", "form_approval", ["table_name"])
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""Mount point for every v1 module router.
|
||||||
|
|
||||||
|
Versioning matters here because of the Phase-3 mobile app: an installed app cannot be
|
||||||
|
force-updated, so v1 must stay frozen once it ships and breaking changes go to v2.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.audit.router import router as audit_router
|
||||||
|
from app.auth.router import router as auth_router
|
||||||
|
from app.chemists.router import router as chemists_router
|
||||||
|
from app.csv_data.router import router as csv_data_router
|
||||||
|
from app.doctors.router import router as doctors_router
|
||||||
|
from app.organization.router import router as organization_router
|
||||||
|
from app.products.router import router as products_router
|
||||||
|
from app.reports.router import router as reports_router
|
||||||
|
from app.users.router import router as users_router
|
||||||
|
|
||||||
|
api_router = APIRouter()
|
||||||
|
api_router.include_router(auth_router)
|
||||||
|
api_router.include_router(users_router)
|
||||||
|
api_router.include_router(organization_router)
|
||||||
|
api_router.include_router(doctors_router)
|
||||||
|
api_router.include_router(chemists_router)
|
||||||
|
api_router.include_router(csv_data_router)
|
||||||
|
api_router.include_router(products_router)
|
||||||
|
api_router.include_router(reports_router)
|
||||||
|
api_router.include_router(audit_router)
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
"""The approval workflow for the revised business requirement.
|
||||||
|
|
||||||
|
DRAFT --submit(MR)--> PENDING_AM
|
||||||
|
RETURNED --submit(MR)--> PENDING_AM
|
||||||
|
PENDING_AM --approve(AM)--> APPROVED (terminal, immutable)
|
||||||
|
PENDING_AM --return(AM)--> RETURNED
|
||||||
|
|
||||||
|
The Area Manager is the final approver; there is no General Manager stage.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from app.common.enums import EDITABLE_STATUSES, DCRStatus, Role, WorkflowAction
|
||||||
|
from app.common.exceptions import ForbiddenError, InvalidStateTransitionError
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Transition:
|
||||||
|
from_status: DCRStatus
|
||||||
|
action: WorkflowAction
|
||||||
|
to_status: DCRStatus
|
||||||
|
allowed_role: Role
|
||||||
|
requires_reason: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
TRANSITIONS: tuple[Transition, ...] = (
|
||||||
|
Transition(DCRStatus.DRAFT, WorkflowAction.SUBMIT, DCRStatus.PENDING_AM, Role.MR),
|
||||||
|
Transition(DCRStatus.RETURNED, WorkflowAction.SUBMIT, DCRStatus.PENDING_AM, Role.MR),
|
||||||
|
Transition(DCRStatus.PENDING_AM, WorkflowAction.APPROVE, DCRStatus.APPROVED, Role.AM),
|
||||||
|
Transition(
|
||||||
|
DCRStatus.PENDING_AM, WorkflowAction.RETURN, DCRStatus.RETURNED, Role.AM,
|
||||||
|
requires_reason=True,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
_INDEX: dict[tuple[DCRStatus, WorkflowAction], Transition] = {
|
||||||
|
(t.from_status, t.action): t for t in TRANSITIONS
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def find_transition(status: DCRStatus, action: WorkflowAction) -> Transition | None:
|
||||||
|
return _INDEX.get((status, action))
|
||||||
|
|
||||||
|
|
||||||
|
def assert_transition(status: DCRStatus, action: WorkflowAction, role: Role) -> Transition:
|
||||||
|
"""Validate a requested move and return the transition to apply.
|
||||||
|
|
||||||
|
Raises InvalidStateTransitionError (409) if the move does not exist from this
|
||||||
|
status, and ForbiddenError (403) if it exists but this role may not make it.
|
||||||
|
ADMIN never matches any transition — SEC-2: the System Administrator can never
|
||||||
|
approve a report.
|
||||||
|
"""
|
||||||
|
transition = find_transition(status, action)
|
||||||
|
if transition is None:
|
||||||
|
raise InvalidStateTransitionError(
|
||||||
|
f"Cannot {action.value.lower()} a report in status {status.value}",
|
||||||
|
{
|
||||||
|
"current_status": status.value,
|
||||||
|
"attempted_action": action.value,
|
||||||
|
"allowed_actions": sorted(
|
||||||
|
t.action.value for t in TRANSITIONS if t.from_status == status
|
||||||
|
),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if transition.allowed_role != role:
|
||||||
|
raise ForbiddenError(
|
||||||
|
f"Role {role.value} may not {action.value.lower()} this report",
|
||||||
|
{"required_role": transition.allowed_role.value, "your_role": role.value},
|
||||||
|
)
|
||||||
|
return transition
|
||||||
|
|
||||||
|
|
||||||
|
def assert_editable(status: DCRStatus) -> None:
|
||||||
|
"""V9/V10 — report data may only change in DRAFT or RETURNED."""
|
||||||
|
if status not in EDITABLE_STATUSES:
|
||||||
|
from app.common.exceptions import ReportLockedError
|
||||||
|
|
||||||
|
raise ReportLockedError(
|
||||||
|
f"A report in status {status.value} cannot be modified",
|
||||||
|
{
|
||||||
|
"current_status": status.value,
|
||||||
|
"editable_statuses": sorted(s.value for s in EDITABLE_STATUSES),
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
"""Append-only audit log.
|
||||||
|
|
||||||
|
`approval_history` and `comments` were NOT created as separate tables (report §13.2).
|
||||||
|
Approval history is a filtered query over this table; every comment in this system
|
||||||
|
attaches to a state change, so it lives in `audit_log.comment`.
|
||||||
|
|
||||||
|
SEC-3: the application must never be granted UPDATE or DELETE on this table. See
|
||||||
|
`scripts/harden_audit.sql`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import DateTime, Enum, ForeignKey, String, Text, func
|
||||||
|
from sqlalchemy.dialects.postgresql import JSONB
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from app.common.enums import AuditAction, EntityType
|
||||||
|
from app.database.base import Base, UUIDMixin
|
||||||
|
|
||||||
|
|
||||||
|
class AuditLog(Base, UUIDMixin):
|
||||||
|
__tablename__ = "audit_log"
|
||||||
|
|
||||||
|
actor_user_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT"), nullable=False
|
||||||
|
)
|
||||||
|
entity_type: Mapped[EntityType] = mapped_column(
|
||||||
|
Enum(EntityType, name="entity_type_enum", native_enum=False, length=30),
|
||||||
|
nullable=False,
|
||||||
|
index=True,
|
||||||
|
)
|
||||||
|
entity_id: Mapped[uuid.UUID] = mapped_column(PGUUID(as_uuid=True), nullable=False, index=True)
|
||||||
|
action: Mapped[AuditAction] = mapped_column(
|
||||||
|
Enum(AuditAction, name="audit_action_enum", native_enum=False, length=20), nullable=False
|
||||||
|
)
|
||||||
|
before_data: Mapped[dict[str, Any] | None] = mapped_column(JSONB)
|
||||||
|
after_data: Mapped[dict[str, Any] | None] = mapped_column(JSONB)
|
||||||
|
#: The manager's reason — business context no automatic row-versioner can capture.
|
||||||
|
comment: Mapped[str | None] = mapped_column(Text)
|
||||||
|
ip_address: Mapped[str | None] = mapped_column(String(45))
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now(), nullable=False, index=True
|
||||||
|
)
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import uuid
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Query
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.audit.schemas import ApprovalHistoryItem, AuditLogRead
|
||||||
|
from app.audit.service import AuditService
|
||||||
|
from app.auth.dependencies import assert_can_view_dcr, get_current_user
|
||||||
|
from app.common.enums import EntityType, Role
|
||||||
|
from app.common.exceptions import NotFoundError
|
||||||
|
from app.database.session import get_db
|
||||||
|
from app.reports.repository import DCRRepository
|
||||||
|
from app.users.models import User
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/audit", tags=["audit"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=list[AuditLogRead])
|
||||||
|
async def get_audit_history(
|
||||||
|
entity_type: EntityType = Query(...),
|
||||||
|
entity_id: uuid.UUID = Query(...),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Scoped audit history.
|
||||||
|
|
||||||
|
For a report, the caller must be able to view the report itself — the audit log is
|
||||||
|
not a side door around the data-scope rules.
|
||||||
|
"""
|
||||||
|
if entity_type == EntityType.DCR:
|
||||||
|
dcr = await DCRRepository(db).get(entity_id)
|
||||||
|
if dcr is None:
|
||||||
|
raise NotFoundError("Report not found")
|
||||||
|
await assert_can_view_dcr(db, current_user, dcr)
|
||||||
|
elif current_user.role not in (Role.ADMIN, Role.GM):
|
||||||
|
from app.common.exceptions import ForbiddenError
|
||||||
|
|
||||||
|
raise ForbiddenError("Only ADMIN or GM may read non-report audit history")
|
||||||
|
|
||||||
|
return await AuditService(db).history_for(entity_type, entity_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/dcr/{dcr_id}/approval-history", response_model=list[ApprovalHistoryItem])
|
||||||
|
async def approval_history(
|
||||||
|
dcr_id: uuid.UUID,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> list[ApprovalHistoryItem]:
|
||||||
|
""""Approval history" is a filtered view over audit_log, not a second table."""
|
||||||
|
dcr = await DCRRepository(db).get(dcr_id)
|
||||||
|
if dcr is None:
|
||||||
|
raise NotFoundError("Report not found")
|
||||||
|
await assert_can_view_dcr(db, current_user, dcr)
|
||||||
|
|
||||||
|
entries = await AuditService(db).approval_history_for(dcr_id)
|
||||||
|
items: list[ApprovalHistoryItem] = []
|
||||||
|
for entry in entries:
|
||||||
|
actor = await db.get(User, entry.actor_user_id)
|
||||||
|
items.append(
|
||||||
|
ApprovalHistoryItem(
|
||||||
|
action=entry.action,
|
||||||
|
actor_name=actor.full_name if actor else "Unknown",
|
||||||
|
actor_role=actor.role.value if actor else "-",
|
||||||
|
comment=entry.comment,
|
||||||
|
at=entry.created_at,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return items
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict
|
||||||
|
|
||||||
|
from app.common.enums import AuditAction, EntityType
|
||||||
|
|
||||||
|
|
||||||
|
class AuditLogRead(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: uuid.UUID
|
||||||
|
actor_user_id: uuid.UUID
|
||||||
|
entity_type: EntityType
|
||||||
|
entity_id: uuid.UUID
|
||||||
|
action: AuditAction
|
||||||
|
comment: str | None
|
||||||
|
before_data: dict[str, Any] | None
|
||||||
|
after_data: dict[str, Any] | None
|
||||||
|
ip_address: str | None
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class ApprovalHistoryItem(BaseModel):
|
||||||
|
"""The approval trail as shown on S7 and printed in the PDF."""
|
||||||
|
|
||||||
|
action: AuditAction
|
||||||
|
actor_name: str
|
||||||
|
actor_role: str
|
||||||
|
comment: str | None
|
||||||
|
at: datetime
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
"""Explicit, application-level audit logging.
|
||||||
|
|
||||||
|
Deliberately NOT automatic row-versioning (report §14.3 C4): an automatic versioner
|
||||||
|
records *what* changed but cannot record *why* — and the manager's return reason is
|
||||||
|
the single most important thing in this audit trail.
|
||||||
|
|
||||||
|
Every `log()` call happens inside the caller's transaction, so a state change and its
|
||||||
|
audit row commit together or not at all (V12).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.audit.models import AuditLog
|
||||||
|
from app.common.enums import AuditAction, EntityType
|
||||||
|
|
||||||
|
|
||||||
|
class AuditService:
|
||||||
|
def __init__(self, db: AsyncSession) -> None:
|
||||||
|
self.db = db
|
||||||
|
|
||||||
|
async def log(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
actor_user_id: uuid.UUID,
|
||||||
|
entity_type: EntityType,
|
||||||
|
entity_id: uuid.UUID,
|
||||||
|
action: AuditAction,
|
||||||
|
before: dict[str, Any] | None = None,
|
||||||
|
after: dict[str, Any] | None = None,
|
||||||
|
comment: str | None = None,
|
||||||
|
ip_address: str | None = None,
|
||||||
|
) -> AuditLog:
|
||||||
|
entry = AuditLog(
|
||||||
|
actor_user_id=actor_user_id,
|
||||||
|
entity_type=entity_type,
|
||||||
|
entity_id=entity_id,
|
||||||
|
action=action,
|
||||||
|
before_data=before,
|
||||||
|
after_data=after,
|
||||||
|
comment=comment,
|
||||||
|
ip_address=ip_address,
|
||||||
|
)
|
||||||
|
self.db.add(entry)
|
||||||
|
# Flush, not commit — the caller owns the transaction boundary.
|
||||||
|
await self.db.flush()
|
||||||
|
return entry
|
||||||
|
|
||||||
|
async def history_for(
|
||||||
|
self, entity_type: EntityType, entity_id: uuid.UUID
|
||||||
|
) -> list[AuditLog]:
|
||||||
|
stmt = (
|
||||||
|
select(AuditLog)
|
||||||
|
.where(AuditLog.entity_type == entity_type, AuditLog.entity_id == entity_id)
|
||||||
|
.order_by(AuditLog.created_at.asc())
|
||||||
|
)
|
||||||
|
return list((await self.db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
|
async def approval_history_for(self, dcr_id: uuid.UUID) -> list[AuditLog]:
|
||||||
|
""""Approval history" is a FILTERED QUERY, not a second table (report §13.2)."""
|
||||||
|
workflow_actions = [
|
||||||
|
AuditAction.CREATE,
|
||||||
|
AuditAction.SUBMIT,
|
||||||
|
AuditAction.FORWARD,
|
||||||
|
AuditAction.RETURN,
|
||||||
|
AuditAction.APPROVE,
|
||||||
|
]
|
||||||
|
stmt = (
|
||||||
|
select(AuditLog)
|
||||||
|
.where(
|
||||||
|
AuditLog.entity_type == EntityType.DCR,
|
||||||
|
AuditLog.entity_id == dcr_id,
|
||||||
|
AuditLog.action.in_(workflow_actions),
|
||||||
|
)
|
||||||
|
.order_by(AuditLog.created_at.asc())
|
||||||
|
)
|
||||||
|
return list((await self.db.execute(stmt)).scalars().all())
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
"""The permission core — two layers.
|
||||||
|
|
||||||
|
Layer 1 (`require_role`) answers "WHAT may this role do?".
|
||||||
|
Layer 2 (`assert_can_*`) answers "WHOSE data may this specific user touch?".
|
||||||
|
|
||||||
|
Most RBAC bugs live in the gap between those two questions: "AM" is a role, but
|
||||||
|
"AM *of this headquarters*" is a scope. Both checks are mandatory on scoped
|
||||||
|
endpoints, and every one has a negative test asserting 403 (X1-X3).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from fastapi import Depends, Request
|
||||||
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth.security import decode_access_token
|
||||||
|
from app.common.enums import Role
|
||||||
|
from app.common.exceptions import ForbiddenError, UnauthorizedError
|
||||||
|
from app.database.session import get_db
|
||||||
|
from app.organization.models import AMHeadquarters
|
||||||
|
from app.users.models import User
|
||||||
|
|
||||||
|
bearer_scheme = HTTPBearer(auto_error=False)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_current_user(
|
||||||
|
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> User:
|
||||||
|
if credentials is None:
|
||||||
|
raise UnauthorizedError("Missing bearer token")
|
||||||
|
|
||||||
|
payload = decode_access_token(credentials.credentials)
|
||||||
|
try:
|
||||||
|
user_id = uuid.UUID(payload["sub"])
|
||||||
|
except (KeyError, ValueError) as exc:
|
||||||
|
raise UnauthorizedError("Malformed token subject") from exc
|
||||||
|
|
||||||
|
user = await db.get(User, user_id)
|
||||||
|
if user is None:
|
||||||
|
raise UnauthorizedError("User no longer exists")
|
||||||
|
# SEC-5: checked on EVERY request, not only at login.
|
||||||
|
if not user.is_active:
|
||||||
|
raise UnauthorizedError("User account is deactivated")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def require_role(*allowed: Role):
|
||||||
|
"""Layer 1. Usage: `user: User = Depends(require_role(Role.MR))`."""
|
||||||
|
|
||||||
|
async def _check(user: User = Depends(get_current_user)) -> User:
|
||||||
|
if user.role not in allowed:
|
||||||
|
raise ForbiddenError(
|
||||||
|
"Role not permitted for this action",
|
||||||
|
{"your_role": user.role.value, "required": [r.value for r in allowed]},
|
||||||
|
)
|
||||||
|
return user
|
||||||
|
|
||||||
|
return _check
|
||||||
|
|
||||||
|
|
||||||
|
async def active_hq_ids_for_am(db: AsyncSession, am_user_id: uuid.UUID) -> set[uuid.UUID]:
|
||||||
|
"""Headquarters this Area Manager currently manages (`effective_to IS NULL`)."""
|
||||||
|
stmt = select(AMHeadquarters.headquarters_id).where(
|
||||||
|
AMHeadquarters.area_manager_user_id == am_user_id,
|
||||||
|
AMHeadquarters.effective_to.is_(None),
|
||||||
|
)
|
||||||
|
return set((await db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
|
|
||||||
|
async def visible_hq_ids(db: AsyncSession, user: User) -> set[uuid.UUID] | None:
|
||||||
|
"""Headquarters the user may see. `None` means "all" (GM and ADMIN)."""
|
||||||
|
if user.role in (Role.GM, Role.ADMIN):
|
||||||
|
return None
|
||||||
|
if user.role == Role.AM:
|
||||||
|
return await active_hq_ids_for_am(db, user.id)
|
||||||
|
if user.role == Role.MR:
|
||||||
|
return {user.headquarters_id} if user.headquarters_id else set()
|
||||||
|
return set()
|
||||||
|
|
||||||
|
|
||||||
|
async def assert_can_view_hq(db: AsyncSession, user: User, headquarters_id: uuid.UUID) -> None:
|
||||||
|
allowed = await visible_hq_ids(db, user)
|
||||||
|
if allowed is None or headquarters_id in allowed:
|
||||||
|
return
|
||||||
|
raise ForbiddenError("Headquarters outside your data scope")
|
||||||
|
|
||||||
|
|
||||||
|
async def assert_can_view_dcr(db: AsyncSession, user: User, dcr) -> None:
|
||||||
|
"""Layer 2 for reports.
|
||||||
|
|
||||||
|
ADMIN may inspect report content for support and administration, but cannot act on
|
||||||
|
reports because every transition endpoint still requires the AM role.
|
||||||
|
"""
|
||||||
|
if user.role in (Role.GM, Role.ADMIN):
|
||||||
|
return
|
||||||
|
if user.role == Role.MR and dcr.mr_user_id == user.id:
|
||||||
|
return
|
||||||
|
if user.role == Role.AM:
|
||||||
|
if dcr.headquarters_id in await active_hq_ids_for_am(db, user.id):
|
||||||
|
return
|
||||||
|
raise ForbiddenError("Report outside your data scope")
|
||||||
|
|
||||||
|
|
||||||
|
def client_ip(request: Request) -> str | None:
|
||||||
|
forwarded = request.headers.get("x-forwarded-for")
|
||||||
|
if forwarded:
|
||||||
|
return forwarded.split(",")[0].strip()
|
||||||
|
return request.client.host if request.client else None
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
"""Server-side refresh tokens.
|
||||||
|
|
||||||
|
Stored server-side (not stateless) precisely so they can be REVOKED — a departing MR
|
||||||
|
must lose access immediately (SEC-5).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import Boolean, DateTime, ForeignKey, String
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from app.database.base import Base, TimestampMixin, UUIDMixin
|
||||||
|
|
||||||
|
|
||||||
|
class RefreshToken(Base, UUIDMixin, TimestampMixin):
|
||||||
|
__tablename__ = "refresh_token"
|
||||||
|
|
||||||
|
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="CASCADE"), nullable=False, index=True
|
||||||
|
)
|
||||||
|
#: SHA-256 of the token — a database leak must not yield usable tokens.
|
||||||
|
token_hash: Mapped[str] = mapped_column(String(64), nullable=False, unique=True, index=True)
|
||||||
|
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||||
|
revoked: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
from fastapi import APIRouter, Depends, Request, status
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth.dependencies import client_ip, get_current_user
|
||||||
|
from app.auth.schemas import CurrentUser, LoginRequest, RefreshRequest, TokenPair
|
||||||
|
from app.auth.service import AuthService
|
||||||
|
from app.database.session import get_db
|
||||||
|
from app.users.models import User
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/login", response_model=TokenPair)
|
||||||
|
async def login(
|
||||||
|
payload: LoginRequest, request: Request, db: AsyncSession = Depends(get_db)
|
||||||
|
) -> TokenPair:
|
||||||
|
return await AuthService(db).login(payload.email, payload.password, client_ip(request))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/refresh", response_model=TokenPair)
|
||||||
|
async def refresh(payload: RefreshRequest, db: AsyncSession = Depends(get_db)) -> TokenPair:
|
||||||
|
return await AuthService(db).refresh(payload.refresh_token)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
async def logout(
|
||||||
|
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
||||||
|
) -> None:
|
||||||
|
await AuthService(db).logout(current_user.id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/me", response_model=CurrentUser)
|
||||||
|
async def me(current_user: User = Depends(get_current_user)) -> User:
|
||||||
|
return current_user
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import uuid
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, EmailStr, Field
|
||||||
|
|
||||||
|
from app.common.enums import Role
|
||||||
|
|
||||||
|
|
||||||
|
class LoginRequest(BaseModel):
|
||||||
|
email: EmailStr
|
||||||
|
password: str = Field(min_length=1)
|
||||||
|
|
||||||
|
|
||||||
|
class TokenPair(BaseModel):
|
||||||
|
access_token: str
|
||||||
|
refresh_token: str
|
||||||
|
token_type: str = "bearer"
|
||||||
|
expires_in: int
|
||||||
|
|
||||||
|
|
||||||
|
class RefreshRequest(BaseModel):
|
||||||
|
refresh_token: str
|
||||||
|
|
||||||
|
|
||||||
|
class CurrentUser(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: uuid.UUID
|
||||||
|
email: str
|
||||||
|
full_name: str
|
||||||
|
employee_code: str
|
||||||
|
role: Role
|
||||||
|
headquarters_id: uuid.UUID | None
|
||||||
|
is_active: bool
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"""Password hashing and JWT encoding/decoding."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import secrets
|
||||||
|
import uuid
|
||||||
|
from datetime import UTC, datetime, timedelta
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from argon2 import PasswordHasher
|
||||||
|
from argon2.exceptions import VerificationError, VerifyMismatchError
|
||||||
|
from jose import JWTError, jwt
|
||||||
|
|
||||||
|
from app.common.exceptions import UnauthorizedError
|
||||||
|
from app.config.settings import settings
|
||||||
|
|
||||||
|
_hasher = PasswordHasher()
|
||||||
|
|
||||||
|
|
||||||
|
def utcnow() -> datetime:
|
||||||
|
return datetime.now(UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def hash_password(plain: str) -> str:
|
||||||
|
return _hasher.hash(plain)
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(plain: str, hashed: str) -> bool:
|
||||||
|
try:
|
||||||
|
_hasher.verify(hashed, plain)
|
||||||
|
return True
|
||||||
|
except (VerifyMismatchError, VerificationError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def create_access_token(user_id: uuid.UUID, role: str) -> str:
|
||||||
|
now = utcnow()
|
||||||
|
payload: dict[str, Any] = {
|
||||||
|
"sub": str(user_id),
|
||||||
|
"role": role,
|
||||||
|
"type": "access",
|
||||||
|
"iat": now,
|
||||||
|
"exp": now + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES),
|
||||||
|
"jti": secrets.token_urlsafe(16),
|
||||||
|
}
|
||||||
|
return jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
|
||||||
|
|
||||||
|
|
||||||
|
def decode_access_token(token: str) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])
|
||||||
|
except JWTError as exc:
|
||||||
|
raise UnauthorizedError("Invalid or expired token") from exc
|
||||||
|
if payload.get("type") != "access":
|
||||||
|
raise UnauthorizedError("Wrong token type")
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def generate_refresh_token() -> tuple[str, str]:
|
||||||
|
"""Return (plaintext_token, sha256_hash). Only the hash is stored."""
|
||||||
|
raw = secrets.token_urlsafe(48)
|
||||||
|
return raw, hash_refresh_token(raw)
|
||||||
|
|
||||||
|
|
||||||
|
def hash_refresh_token(raw: str) -> str:
|
||||||
|
return hashlib.sha256(raw.encode()).hexdigest()
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.audit.service import AuditService
|
||||||
|
from app.auth.models import RefreshToken
|
||||||
|
from app.auth.schemas import TokenPair
|
||||||
|
from app.auth.security import (
|
||||||
|
create_access_token,
|
||||||
|
generate_refresh_token,
|
||||||
|
hash_refresh_token,
|
||||||
|
utcnow,
|
||||||
|
verify_password,
|
||||||
|
)
|
||||||
|
from app.common.enums import AuditAction, EntityType
|
||||||
|
from app.common.exceptions import UnauthorizedError
|
||||||
|
from app.config.settings import settings
|
||||||
|
from app.users.models import User
|
||||||
|
|
||||||
|
|
||||||
|
class AuthService:
|
||||||
|
def __init__(self, db: AsyncSession) -> None:
|
||||||
|
self.db = db
|
||||||
|
self.audit = AuditService(db)
|
||||||
|
|
||||||
|
async def login(self, email: str, password: str, ip: str | None = None) -> TokenPair:
|
||||||
|
stmt = select(User).where(User.email == email)
|
||||||
|
user = (await self.db.execute(stmt)).scalar_one_or_none()
|
||||||
|
|
||||||
|
# Same message for unknown user and wrong password — do not leak which.
|
||||||
|
if user is None or not verify_password(password, user.password_hash):
|
||||||
|
if user is not None:
|
||||||
|
user.failed_login_attempts += 1
|
||||||
|
await self.db.commit()
|
||||||
|
raise UnauthorizedError("Invalid email or password")
|
||||||
|
|
||||||
|
if not user.is_active:
|
||||||
|
raise UnauthorizedError("User account is deactivated")
|
||||||
|
|
||||||
|
# SEC-10 — lock out after repeated failures.
|
||||||
|
if user.failed_login_attempts >= settings.LOGIN_MAX_FAILED_ATTEMPTS:
|
||||||
|
raise UnauthorizedError("Account locked after too many failed attempts")
|
||||||
|
|
||||||
|
user.failed_login_attempts = 0
|
||||||
|
await self.audit.log(
|
||||||
|
actor_user_id=user.id,
|
||||||
|
entity_type=EntityType.USER,
|
||||||
|
entity_id=user.id,
|
||||||
|
action=AuditAction.LOGIN,
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
|
pair = await self._issue_tokens(user)
|
||||||
|
await self.db.commit()
|
||||||
|
return pair
|
||||||
|
|
||||||
|
async def refresh(self, raw_token: str) -> TokenPair:
|
||||||
|
token_hash = hash_refresh_token(raw_token)
|
||||||
|
stmt = select(RefreshToken).where(RefreshToken.token_hash == token_hash)
|
||||||
|
stored = (await self.db.execute(stmt)).scalar_one_or_none()
|
||||||
|
|
||||||
|
if stored is None or stored.revoked or stored.expires_at < utcnow():
|
||||||
|
raise UnauthorizedError("Invalid or expired refresh token")
|
||||||
|
|
||||||
|
user = await self.db.get(User, stored.user_id)
|
||||||
|
if user is None or not user.is_active:
|
||||||
|
raise UnauthorizedError("User no longer active")
|
||||||
|
|
||||||
|
# Rotate: the presented token is burned as the new one is issued.
|
||||||
|
stored.revoked = True
|
||||||
|
pair = await self._issue_tokens(user)
|
||||||
|
await self.db.commit()
|
||||||
|
return pair
|
||||||
|
|
||||||
|
async def logout(self, user_id: uuid.UUID) -> None:
|
||||||
|
"""Revoke every refresh token for this user."""
|
||||||
|
stmt = select(RefreshToken).where(
|
||||||
|
RefreshToken.user_id == user_id, RefreshToken.revoked.is_(False)
|
||||||
|
)
|
||||||
|
for token in (await self.db.execute(stmt)).scalars().all():
|
||||||
|
token.revoked = True
|
||||||
|
await self.db.commit()
|
||||||
|
|
||||||
|
async def _issue_tokens(self, user: User) -> TokenPair:
|
||||||
|
access = create_access_token(user.id, user.role.value)
|
||||||
|
raw_refresh, refresh_hash = generate_refresh_token()
|
||||||
|
self.db.add(
|
||||||
|
RefreshToken(
|
||||||
|
user_id=user.id,
|
||||||
|
token_hash=refresh_hash,
|
||||||
|
expires_at=utcnow() + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
await self.db.flush()
|
||||||
|
return TokenPair(
|
||||||
|
access_token=access,
|
||||||
|
refresh_token=raw_refresh,
|
||||||
|
expires_in=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60,
|
||||||
|
)
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"""Chemist master data and chemist → MR assignment (same shape as doctors)."""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from sqlalchemy import Boolean, Date, ForeignKey, Index, String, UniqueConstraint, text
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
|
from app.database.base import Base, TimestampMixin, UUIDMixin
|
||||||
|
|
||||||
|
|
||||||
|
class Chemist(Base, UUIDMixin, TimestampMixin):
|
||||||
|
__tablename__ = "chemist"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint(
|
||||||
|
"headquarters_id", "name", "shop_address", name="uq_chemist_hq_name_shop"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
headquarters_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("headquarters.id", ondelete="RESTRICT"), nullable=False
|
||||||
|
)
|
||||||
|
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||||
|
shop_address: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
|
contact_number: Mapped[str | None] = mapped_column(String(20))
|
||||||
|
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||||
|
|
||||||
|
assignments: Mapped[list["ChemistAssignment"]] = relationship(back_populates="chemist")
|
||||||
|
|
||||||
|
|
||||||
|
class ChemistAssignment(Base, UUIDMixin, TimestampMixin):
|
||||||
|
__tablename__ = "chemist_assignment"
|
||||||
|
__table_args__ = (
|
||||||
|
Index(
|
||||||
|
"uq_active_chemist_assignment",
|
||||||
|
"chemist_id",
|
||||||
|
unique=True,
|
||||||
|
postgresql_where=text("effective_to IS NULL"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
chemist_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("chemist.id", ondelete="CASCADE"), nullable=False
|
||||||
|
)
|
||||||
|
mr_user_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT"), nullable=False
|
||||||
|
)
|
||||||
|
effective_from: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
effective_to: Mapped[date | None] = mapped_column(Date)
|
||||||
|
|
||||||
|
chemist: Mapped["Chemist"] = relationship(back_populates="assignments")
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import uuid
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Request, status
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth.dependencies import client_ip, get_current_user, require_role
|
||||||
|
from app.chemists.models import Chemist
|
||||||
|
from app.chemists.schemas import ChemistCreate, ChemistRead, ChemistUpdate
|
||||||
|
from app.chemists.service import ChemistService
|
||||||
|
from app.common.enums import Role
|
||||||
|
from app.database.session import get_db
|
||||||
|
from app.doctors.schemas import AssignToMR
|
||||||
|
from app.users.models import User
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/chemists", tags=["chemists"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=list[ChemistRead])
|
||||||
|
async def list_chemists(
|
||||||
|
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
||||||
|
) -> list[Chemist]:
|
||||||
|
return await ChemistService(db).list_for(current_user)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=ChemistRead, status_code=status.HTTP_201_CREATED)
|
||||||
|
async def create_chemist(
|
||||||
|
payload: ChemistCreate,
|
||||||
|
request: Request,
|
||||||
|
current_user: User = Depends(require_role(Role.ADMIN)),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> Chemist:
|
||||||
|
return await ChemistService(db).create(payload, current_user, client_ip(request))
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/{chemist_id}", response_model=ChemistRead)
|
||||||
|
async def update_chemist(
|
||||||
|
chemist_id: uuid.UUID,
|
||||||
|
payload: ChemistUpdate,
|
||||||
|
request: Request,
|
||||||
|
current_user: User = Depends(require_role(Role.ADMIN)),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> Chemist:
|
||||||
|
return await ChemistService(db).update(chemist_id, payload, current_user, client_ip(request))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{chemist_id}/assign", status_code=status.HTTP_201_CREATED)
|
||||||
|
async def assign_chemist(
|
||||||
|
chemist_id: uuid.UUID,
|
||||||
|
payload: AssignToMR,
|
||||||
|
request: Request,
|
||||||
|
current_user: User = Depends(require_role(Role.ADMIN, Role.GM, Role.AM)),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
assignment = await ChemistService(db).assign_to_mr(
|
||||||
|
chemist_id, payload.mr_user_id, payload.effective_from, current_user, client_ip(request)
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"id": assignment.id,
|
||||||
|
"chemist_id": assignment.chemist_id,
|
||||||
|
"mr_user_id": assignment.mr_user_id,
|
||||||
|
"effective_from": assignment.effective_from,
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import uuid
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
|
|
||||||
|
class ChemistCreate(BaseModel):
|
||||||
|
headquarters_id: uuid.UUID
|
||||||
|
name: str = Field(min_length=2, max_length=200)
|
||||||
|
shop_address: str = Field(min_length=2, max_length=500)
|
||||||
|
contact_number: str | None = Field(default=None, max_length=20)
|
||||||
|
|
||||||
|
|
||||||
|
class ChemistUpdate(BaseModel):
|
||||||
|
name: str | None = Field(default=None, min_length=2, max_length=200)
|
||||||
|
shop_address: str | None = Field(default=None, min_length=2, max_length=500)
|
||||||
|
contact_number: str | None = Field(default=None, max_length=20)
|
||||||
|
is_active: bool | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ChemistRead(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: uuid.UUID
|
||||||
|
headquarters_id: uuid.UUID
|
||||||
|
name: str
|
||||||
|
shop_address: str
|
||||||
|
contact_number: str | None
|
||||||
|
is_active: bool
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.audit.service import AuditService
|
||||||
|
from app.auth.dependencies import assert_can_view_hq, visible_hq_ids
|
||||||
|
from app.chemists.models import Chemist, ChemistAssignment
|
||||||
|
from app.chemists.schemas import ChemistCreate, ChemistUpdate
|
||||||
|
from app.common.enums import AuditAction, EntityType, Role
|
||||||
|
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
|
||||||
|
from app.common.utils import snapshot
|
||||||
|
from app.users.models import User
|
||||||
|
|
||||||
|
_AUDIT_FIELDS = ["name", "shop_address", "contact_number", "is_active"]
|
||||||
|
|
||||||
|
|
||||||
|
class ChemistService:
|
||||||
|
def __init__(self, db: AsyncSession) -> None:
|
||||||
|
self.db = db
|
||||||
|
self.audit = AuditService(db)
|
||||||
|
|
||||||
|
async def create(self, data: ChemistCreate, actor: User, ip: str | None = None) -> Chemist:
|
||||||
|
await assert_can_view_hq(self.db, actor, data.headquarters_id)
|
||||||
|
|
||||||
|
chemist = Chemist(**data.model_dump())
|
||||||
|
self.db.add(chemist)
|
||||||
|
try:
|
||||||
|
await self.db.flush()
|
||||||
|
except IntegrityError as exc:
|
||||||
|
await self.db.rollback()
|
||||||
|
raise ConflictError(
|
||||||
|
"A chemist with this name already exists at this address in this headquarters",
|
||||||
|
{"cause": "uq_chemist_hq_name_shop"},
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
await self.audit.log(
|
||||||
|
actor_user_id=actor.id,
|
||||||
|
entity_type=EntityType.CHEMIST,
|
||||||
|
entity_id=chemist.id,
|
||||||
|
action=AuditAction.CREATE,
|
||||||
|
after=snapshot(chemist, _AUDIT_FIELDS),
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
|
await self.db.commit()
|
||||||
|
return chemist
|
||||||
|
|
||||||
|
async def update(
|
||||||
|
self, chemist_id: uuid.UUID, data: ChemistUpdate, actor: User, ip: str | None = None
|
||||||
|
) -> Chemist:
|
||||||
|
chemist = await self.db.get(Chemist, chemist_id)
|
||||||
|
if chemist is None:
|
||||||
|
raise NotFoundError("Chemist not found")
|
||||||
|
await assert_can_view_hq(self.db, actor, chemist.headquarters_id)
|
||||||
|
|
||||||
|
before = snapshot(chemist, _AUDIT_FIELDS)
|
||||||
|
for field, value in data.model_dump(exclude_unset=True).items():
|
||||||
|
setattr(chemist, field, value)
|
||||||
|
|
||||||
|
await self.audit.log(
|
||||||
|
actor_user_id=actor.id,
|
||||||
|
entity_type=EntityType.CHEMIST,
|
||||||
|
entity_id=chemist.id,
|
||||||
|
action=AuditAction.UPDATE,
|
||||||
|
before=before,
|
||||||
|
after=snapshot(chemist, _AUDIT_FIELDS),
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
|
await self.db.commit()
|
||||||
|
return chemist
|
||||||
|
|
||||||
|
async def list_for(self, actor: User) -> list[Chemist]:
|
||||||
|
if actor.role == Role.MR:
|
||||||
|
stmt = (
|
||||||
|
select(Chemist)
|
||||||
|
.join(ChemistAssignment, ChemistAssignment.chemist_id == Chemist.id)
|
||||||
|
.where(
|
||||||
|
ChemistAssignment.mr_user_id == actor.id,
|
||||||
|
ChemistAssignment.effective_to.is_(None),
|
||||||
|
Chemist.is_active.is_(True),
|
||||||
|
)
|
||||||
|
.order_by(Chemist.name)
|
||||||
|
)
|
||||||
|
return list((await self.db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
|
allowed = await visible_hq_ids(self.db, actor)
|
||||||
|
stmt = select(Chemist).order_by(Chemist.name)
|
||||||
|
if allowed is not None:
|
||||||
|
stmt = stmt.where(Chemist.headquarters_id.in_(allowed or [None]))
|
||||||
|
return list((await self.db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
|
async def assign_to_mr(
|
||||||
|
self,
|
||||||
|
chemist_id: uuid.UUID,
|
||||||
|
mr_user_id: uuid.UUID,
|
||||||
|
effective_from: date | None,
|
||||||
|
actor: User,
|
||||||
|
ip: str | None = None,
|
||||||
|
) -> ChemistAssignment:
|
||||||
|
chemist = await self.db.get(Chemist, chemist_id)
|
||||||
|
if chemist is None:
|
||||||
|
raise NotFoundError("Chemist not found")
|
||||||
|
await assert_can_view_hq(self.db, actor, chemist.headquarters_id)
|
||||||
|
|
||||||
|
mr = await self.db.get(User, mr_user_id)
|
||||||
|
if mr is None:
|
||||||
|
raise NotFoundError("MR not found")
|
||||||
|
if mr.role != Role.MR:
|
||||||
|
raise ValidationError("Chemists can only be assigned to an MR")
|
||||||
|
if mr.headquarters_id != chemist.headquarters_id:
|
||||||
|
raise ValidationError("MR and chemist belong to different headquarters")
|
||||||
|
|
||||||
|
start = effective_from or date.today()
|
||||||
|
existing = (
|
||||||
|
await self.db.execute(
|
||||||
|
select(ChemistAssignment).where(
|
||||||
|
ChemistAssignment.chemist_id == chemist_id,
|
||||||
|
ChemistAssignment.effective_to.is_(None),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
for row in existing:
|
||||||
|
if row.mr_user_id == mr_user_id:
|
||||||
|
return row
|
||||||
|
row.effective_to = start
|
||||||
|
await self.db.flush()
|
||||||
|
|
||||||
|
assignment = ChemistAssignment(
|
||||||
|
chemist_id=chemist_id, mr_user_id=mr_user_id, effective_from=start
|
||||||
|
)
|
||||||
|
self.db.add(assignment)
|
||||||
|
await self.audit.log(
|
||||||
|
actor_user_id=actor.id,
|
||||||
|
entity_type=EntityType.CHEMIST,
|
||||||
|
entity_id=chemist_id,
|
||||||
|
action=AuditAction.ASSIGN,
|
||||||
|
after={"mr_user_id": str(mr_user_id), "effective_from": start.isoformat()},
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
|
await self.db.commit()
|
||||||
|
return assignment
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
"""Domain enumerations.
|
||||||
|
|
||||||
|
Roles are a fixed enum on `user.role`, not a `role` table — with 4 roles that never
|
||||||
|
change at runtime a lookup table adds a join to every request and buys nothing.
|
||||||
|
(See report §13.2.)
|
||||||
|
"""
|
||||||
|
|
||||||
|
from enum import StrEnum
|
||||||
|
|
||||||
|
|
||||||
|
class Role(StrEnum):
|
||||||
|
"""Operational roles (MR/AM/GM) plus the technical ADMIN role.
|
||||||
|
|
||||||
|
ADMIN sits OUTSIDE the business hierarchy. It provisions users and masters but
|
||||||
|
can never approve a report or read report content (report §8, SEC-2).
|
||||||
|
"""
|
||||||
|
|
||||||
|
ADMIN = "ADMIN"
|
||||||
|
GM = "GM"
|
||||||
|
AM = "AM"
|
||||||
|
MR = "MR"
|
||||||
|
|
||||||
|
|
||||||
|
class DCRStatus(StrEnum):
|
||||||
|
"""MR submits, the Area Manager approves or returns it.
|
||||||
|
|
||||||
|
`RETURNED` captures the correction loop, and `APPROVED` remains terminal and
|
||||||
|
immutable. There is no General Manager step.
|
||||||
|
"""
|
||||||
|
|
||||||
|
DRAFT = "DRAFT"
|
||||||
|
PENDING_AM = "PENDING_AM"
|
||||||
|
RETURNED = "RETURNED"
|
||||||
|
APPROVED = "APPROVED"
|
||||||
|
|
||||||
|
|
||||||
|
#: Statuses in which the owning MR may still change report data (V9).
|
||||||
|
EDITABLE_STATUSES: frozenset[DCRStatus] = frozenset(
|
||||||
|
{DCRStatus.DRAFT, DCRStatus.RETURNED}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class WorkflowAction(StrEnum):
|
||||||
|
SUBMIT = "SUBMIT"
|
||||||
|
RETURN = "RETURN"
|
||||||
|
APPROVE = "APPROVE"
|
||||||
|
|
||||||
|
|
||||||
|
class CallOutcome(StrEnum):
|
||||||
|
MET = "MET"
|
||||||
|
NOT_AVAILABLE = "NOT_AVAILABLE"
|
||||||
|
RESCHEDULED = "RESCHEDULED"
|
||||||
|
|
||||||
|
|
||||||
|
class ConversionStatus(StrEnum):
|
||||||
|
"""Core-doctor conversion. Stored as a column on doctor_call, not a table."""
|
||||||
|
|
||||||
|
NOT_STARTED = "NOT_STARTED"
|
||||||
|
IN_PROGRESS = "IN_PROGRESS"
|
||||||
|
CONVERTED = "CONVERTED"
|
||||||
|
LOST = "LOST"
|
||||||
|
|
||||||
|
|
||||||
|
class AuditAction(StrEnum):
|
||||||
|
CREATE = "CREATE"
|
||||||
|
UPDATE = "UPDATE"
|
||||||
|
DELETE = "DELETE"
|
||||||
|
SUBMIT = "SUBMIT"
|
||||||
|
FORWARD = "FORWARD"
|
||||||
|
RETURN = "RETURN"
|
||||||
|
APPROVE = "APPROVE"
|
||||||
|
ASSIGN = "ASSIGN"
|
||||||
|
LOGIN = "LOGIN"
|
||||||
|
DEACTIVATE = "DEACTIVATE"
|
||||||
|
|
||||||
|
|
||||||
|
class EntityType(StrEnum):
|
||||||
|
USER = "user"
|
||||||
|
HEADQUARTERS = "headquarters"
|
||||||
|
DOCTOR = "doctor"
|
||||||
|
CHEMIST = "chemist"
|
||||||
|
DCR = "dcr"
|
||||||
|
PRODUCT = "product"
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
"""Application error hierarchy → one consistent JSON error envelope."""
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
class AppError(Exception):
|
||||||
|
"""Base for every error the application raises deliberately."""
|
||||||
|
|
||||||
|
status_code: int = 400
|
||||||
|
code: str = "APP_ERROR"
|
||||||
|
|
||||||
|
def __init__(self, message: str, details: dict[str, Any] | None = None) -> None:
|
||||||
|
self.message = message
|
||||||
|
self.details = details or {}
|
||||||
|
super().__init__(message)
|
||||||
|
|
||||||
|
def to_dict(self) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"error": {
|
||||||
|
"code": self.code,
|
||||||
|
"message": self.message,
|
||||||
|
"details": self.details,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class NotFoundError(AppError):
|
||||||
|
status_code = 404
|
||||||
|
code = "NOT_FOUND"
|
||||||
|
|
||||||
|
|
||||||
|
class ForbiddenError(AppError):
|
||||||
|
"""Raised for both role failures and data-scope failures.
|
||||||
|
|
||||||
|
Deliberately 403 and not 404: the negative-scope tests (X1-X3) assert 403, so a
|
||||||
|
scope bug cannot hide behind an ambiguous "not found".
|
||||||
|
"""
|
||||||
|
|
||||||
|
status_code = 403
|
||||||
|
code = "FORBIDDEN"
|
||||||
|
|
||||||
|
|
||||||
|
class UnauthorizedError(AppError):
|
||||||
|
status_code = 401
|
||||||
|
code = "UNAUTHORIZED"
|
||||||
|
|
||||||
|
|
||||||
|
class ConflictError(AppError):
|
||||||
|
status_code = 409
|
||||||
|
code = "CONFLICT"
|
||||||
|
|
||||||
|
|
||||||
|
class ValidationError(AppError):
|
||||||
|
status_code = 422
|
||||||
|
code = "VALIDATION_ERROR"
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidStateTransitionError(AppError):
|
||||||
|
status_code = 409
|
||||||
|
code = "INVALID_STATE_TRANSITION"
|
||||||
|
|
||||||
|
|
||||||
|
class ReportLockedError(AppError):
|
||||||
|
"""V10 — an APPROVED report can never be modified by any role."""
|
||||||
|
|
||||||
|
status_code = 409
|
||||||
|
code = "REPORT_LOCKED"
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""Generic data-access base. Repositories hold queries only — never business rules."""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from typing import Generic, TypeVar
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.common.exceptions import NotFoundError
|
||||||
|
from app.database.base import Base
|
||||||
|
|
||||||
|
ModelT = TypeVar("ModelT", bound=Base)
|
||||||
|
|
||||||
|
|
||||||
|
class BaseRepository(Generic[ModelT]):
|
||||||
|
model: type[ModelT]
|
||||||
|
|
||||||
|
def __init__(self, db: AsyncSession) -> None:
|
||||||
|
self.db = db
|
||||||
|
|
||||||
|
async def get(self, entity_id: uuid.UUID) -> ModelT | None:
|
||||||
|
return await self.db.get(self.model, entity_id)
|
||||||
|
|
||||||
|
async def get_or_404(self, entity_id: uuid.UUID) -> ModelT:
|
||||||
|
entity = await self.get(entity_id)
|
||||||
|
if entity is None:
|
||||||
|
raise NotFoundError(f"{self.model.__name__} not found", {"id": str(entity_id)})
|
||||||
|
return entity
|
||||||
|
|
||||||
|
async def list_all(self) -> list[ModelT]:
|
||||||
|
return list((await self.db.execute(select(self.model))).scalars().all())
|
||||||
|
|
||||||
|
def add(self, entity: ModelT) -> ModelT:
|
||||||
|
self.db.add(entity)
|
||||||
|
return entity
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""Small shared helpers."""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import UTC, date, datetime, time
|
||||||
|
from typing import Any
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from sqlalchemy import inspect
|
||||||
|
|
||||||
|
|
||||||
|
def utcnow() -> datetime:
|
||||||
|
return datetime.now(UTC)
|
||||||
|
|
||||||
|
|
||||||
|
def local_now() -> datetime:
|
||||||
|
"""Current time in the company's timezone (`APP_TIMEZONE`), timezone-aware."""
|
||||||
|
from app.config.settings import settings
|
||||||
|
|
||||||
|
return datetime.now(ZoneInfo(settings.APP_TIMEZONE))
|
||||||
|
|
||||||
|
|
||||||
|
def local_today() -> date:
|
||||||
|
"""Today's date in the company's timezone — the server clock runs on UTC."""
|
||||||
|
return local_now().date()
|
||||||
|
|
||||||
|
|
||||||
|
def _jsonable(value: Any) -> Any:
|
||||||
|
if isinstance(value, uuid.UUID):
|
||||||
|
return str(value)
|
||||||
|
if isinstance(value, datetime | date | time):
|
||||||
|
return value.isoformat()
|
||||||
|
if hasattr(value, "value"): # StrEnum and friends
|
||||||
|
return value.value
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def snapshot(instance: Any, fields: list[str] | None = None) -> dict[str, Any]:
|
||||||
|
"""Serialise an ORM instance's column values for the audit log's JSONB columns.
|
||||||
|
|
||||||
|
Only loaded column attributes are read, so this never triggers lazy IO inside a
|
||||||
|
transaction that is about to commit.
|
||||||
|
"""
|
||||||
|
mapper = inspect(instance).mapper
|
||||||
|
names = fields or [c.key for c in mapper.column_attrs]
|
||||||
|
return {name: _jsonable(getattr(instance, name, None)) for name in names}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
"""Application settings. Everything comes from the environment — no secrets in code."""
|
||||||
|
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
|
from pydantic import Field
|
||||||
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
model_config = SettingsConfigDict(
|
||||||
|
env_file=".env", env_file_encoding="utf-8", extra="ignore"
|
||||||
|
)
|
||||||
|
|
||||||
|
# --- Application ---------------------------------------------------
|
||||||
|
APP_NAME: str = "Celtic Life Science Pvt Ltd"
|
||||||
|
PDF_COMPANY_NAME: str = "CELTIC LIFE SCIENCE PVT LTD"
|
||||||
|
PDF_COMPANY_ADDRESS: str = "PLOT NO -D/3, KHARVEL NAGAR, UNIT-3, BHUBANESWAR ODISHA-751001"
|
||||||
|
PDF_COMPANY_WEBSITE: str = "www.celticlifescience.com"
|
||||||
|
PDF_COMPANY_EMAIL: str = "info@celticlifescience.com"
|
||||||
|
PDF_COMPANY_PHONE: str = "9090024999"
|
||||||
|
API_V1_PREFIX: str = "/api/v1"
|
||||||
|
ENVIRONMENT: str = "development"
|
||||||
|
DEBUG: bool = False
|
||||||
|
|
||||||
|
# --- Database ------------------------------------------------------
|
||||||
|
DATABASE_URL: str = "postgresql+asyncpg://pharma:pharma@localhost:5432/pharma"
|
||||||
|
DB_ECHO: bool = False
|
||||||
|
|
||||||
|
# --- Authentication ------------------------------------------------
|
||||||
|
# SECRET_KEY MUST be overridden in production.
|
||||||
|
SECRET_KEY: str = "change-me-in-production-this-is-not-a-secret"
|
||||||
|
JWT_ALGORITHM: str = "HS256"
|
||||||
|
ACCESS_TOKEN_EXPIRE_MINUTES: int = 15
|
||||||
|
REFRESH_TOKEN_EXPIRE_DAYS: int = 7
|
||||||
|
LOGIN_MAX_FAILED_ATTEMPTS: int = 10
|
||||||
|
|
||||||
|
# Business timezone: "today" and visit-time checks use this, not the server's UTC clock.
|
||||||
|
APP_TIMEZONE: str = "Asia/Kolkata"
|
||||||
|
|
||||||
|
# --- Business rules (see report §21 — confirm with client) ----------
|
||||||
|
# A10 / Q8: how many days back an MR may file a report.
|
||||||
|
BACKDATING_WINDOW_DAYS: int = Field(default=7, ge=0, le=90)
|
||||||
|
# A16 / Q9: report for date D must be submitted by end of D + this many days.
|
||||||
|
SUBMISSION_DEADLINE_DAYS: int = Field(default=1, ge=0, le=30)
|
||||||
|
# V8: minimum length of a manager's return reason.
|
||||||
|
MIN_RETURN_REASON_LENGTH: int = 10
|
||||||
|
|
||||||
|
# --- Storage -------------------------------------------------------
|
||||||
|
PDF_STORAGE_PATH: str = "./storage/pdf"
|
||||||
|
|
||||||
|
# --- CORS ----------------------------------------------------------
|
||||||
|
CORS_ORIGINS: list[str] = Field(
|
||||||
|
default_factory=lambda: ["https://celtic.upskalor.com", "https://www.celtic.upskalor.com", "http://localhost:5173", "http://localhost:3000"]
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def sync_database_url(self) -> str:
|
||||||
|
"""Alembic runs synchronously through psycopg, not the async API driver."""
|
||||||
|
return self.DATABASE_URL.replace("+asyncpg", "+psycopg")
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def get_settings() -> Settings:
|
||||||
|
return Settings()
|
||||||
|
|
||||||
|
|
||||||
|
settings = get_settings()
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"""Approval workflow for the company forms that carry an Area Manager signature.
|
||||||
|
|
||||||
|
draft --request(MR)--> pending --approve(AM)--> approved
|
||||||
|
pending / approved --any change to the rows--> draft (a signature never covers edited data)
|
||||||
|
|
||||||
|
Every MR has their own copy of each form, so approval is per (form, MR). The request goes to the Area
|
||||||
|
Manager who manages that MR's headquarters, and nobody else can approve it. Only a form that has
|
||||||
|
rows can be sent, and only a form that has been sent can be approved.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from sqlalchemy import select, text
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth.dependencies import active_hq_ids_for_am
|
||||||
|
from app.common.enums import Role
|
||||||
|
from app.common.exceptions import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||||
|
from app.csv_data.models import FormApproval
|
||||||
|
from app.organization.models import AMHeadquarters, Headquarters
|
||||||
|
from app.users.models import User
|
||||||
|
|
||||||
|
APPROVAL_TABLES = {"standard_tour_plan", "tour_plan", "fare_chart"}
|
||||||
|
|
||||||
|
|
||||||
|
async def owners_in_scope(db: AsyncSession, user: User) -> list[User]:
|
||||||
|
"""The MRs whose forms this user may see: themselves, the MRs of their headquarters, or (admin) all."""
|
||||||
|
stmt = select(User).where(User.role == Role.MR, User.is_active.is_(True)).order_by(User.full_name)
|
||||||
|
if user.role == Role.MR:
|
||||||
|
stmt = stmt.where(User.id == user.id)
|
||||||
|
elif user.role == Role.AM:
|
||||||
|
stmt = stmt.where(User.headquarters_id.in_(await active_hq_ids_for_am(db, user.id)))
|
||||||
|
elif user.role != Role.ADMIN:
|
||||||
|
return []
|
||||||
|
return list((await db.execute(stmt)).scalars())
|
||||||
|
|
||||||
|
|
||||||
|
async def assigned_area_manager(db: AsyncSession, owner: User) -> uuid.UUID | None:
|
||||||
|
if owner.headquarters_id is None:
|
||||||
|
return None
|
||||||
|
stmt = select(AMHeadquarters.area_manager_user_id).where(
|
||||||
|
AMHeadquarters.headquarters_id == owner.headquarters_id, AMHeadquarters.effective_to.is_(None)
|
||||||
|
)
|
||||||
|
return (await db.execute(stmt)).scalars().first()
|
||||||
|
|
||||||
|
|
||||||
|
async def assert_owner_in_scope(db: AsyncSession, user: User, owner_id: uuid.UUID) -> User:
|
||||||
|
"""The MR `owner_id`, if `user` is allowed to see their forms; anything else is refused."""
|
||||||
|
for owner in await owners_in_scope(db, user):
|
||||||
|
if owner.id == owner_id:
|
||||||
|
return owner
|
||||||
|
if user.role == Role.ADMIN or (await db.get(User, owner_id)) is None:
|
||||||
|
raise NotFoundError("Medical representative not found", {"id": str(owner_id)})
|
||||||
|
raise ForbiddenError("This form belongs to a medical representative outside your headquarters")
|
||||||
|
|
||||||
|
|
||||||
|
async def get_approval(db: AsyncSession, table_name: str, owner_id: uuid.UUID) -> FormApproval | None:
|
||||||
|
return await db.get(FormApproval, (table_name, owner_id))
|
||||||
|
|
||||||
|
|
||||||
|
async def _get_or_create(db: AsyncSession, table_name: str, owner_id: uuid.UUID) -> FormApproval:
|
||||||
|
row = await get_approval(db, table_name, owner_id)
|
||||||
|
if row is None:
|
||||||
|
row = FormApproval(table_name=table_name, owner_user_id=owner_id, status="draft")
|
||||||
|
db.add(row)
|
||||||
|
await db.flush()
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
async def list_approvals(db: AsyncSession, user: User) -> list[tuple[FormApproval, User, str | None]]:
|
||||||
|
"""(approval, MR, headquarters name) for what `user` can see.
|
||||||
|
|
||||||
|
An MR always gets all three forms ("draft" until they act); an Area Manager or admin only
|
||||||
|
gets forms that have been sent, since a draft is nothing for them to act on.
|
||||||
|
"""
|
||||||
|
owners = {o.id: o for o in await owners_in_scope(db, user)}
|
||||||
|
hq_names = {h.id: h.name for h in (await db.execute(select(Headquarters))).scalars()}
|
||||||
|
existing = {
|
||||||
|
(r.table_name, r.owner_user_id): r
|
||||||
|
for r in (await db.execute(select(FormApproval).where(FormApproval.owner_user_id.in_(owners)))).scalars()
|
||||||
|
}
|
||||||
|
out: list[tuple[FormApproval, User, str | None]] = []
|
||||||
|
if user.role == Role.MR:
|
||||||
|
for name in sorted(APPROVAL_TABLES):
|
||||||
|
out.append((existing.get((name, user.id)) or FormApproval(table_name=name, owner_user_id=user.id, status="draft"), user, hq_names.get(user.headquarters_id)))
|
||||||
|
return out
|
||||||
|
for (name, owner_id), row in sorted(existing.items()):
|
||||||
|
if row.status != "draft":
|
||||||
|
out.append((row, owners[owner_id], hq_names.get(owners[owner_id].headquarters_id)))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
async def _row_count(db: AsyncSession, table_name: str, owner_id: uuid.UUID) -> int:
|
||||||
|
# table_name is only ever one of the fixed APPROVAL_TABLES, never user input.
|
||||||
|
return (
|
||||||
|
await db.execute(text(f'SELECT COUNT(*) FROM "{table_name}" WHERE owner_user_id = :o'), {"o": owner_id})
|
||||||
|
).scalar_one()
|
||||||
|
|
||||||
|
|
||||||
|
async def request_approval(db: AsyncSession, table_name: str, actor: User) -> FormApproval:
|
||||||
|
if await assigned_area_manager(db, actor) is None:
|
||||||
|
raise ValidationError("No Area Manager is assigned to your headquarters yet. Ask the administrator to assign one.")
|
||||||
|
row = await _get_or_create(db, table_name, actor.id)
|
||||||
|
if row.status == "pending":
|
||||||
|
return row # already with the Area Manager — a second click changes nothing
|
||||||
|
if row.status == "approved":
|
||||||
|
raise ConflictError("This form is already approved. Change a row to send it again.")
|
||||||
|
if await _row_count(db, table_name, actor.id) == 0:
|
||||||
|
raise ValidationError("Add at least one row before sending the form for approval")
|
||||||
|
row.status = "pending"
|
||||||
|
row.requested_by_user_id = actor.id
|
||||||
|
await db.commit()
|
||||||
|
await db.refresh(row)
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
async def approve(db: AsyncSession, table_name: str, owner_id: uuid.UUID, actor: User) -> FormApproval:
|
||||||
|
await assert_owner_in_scope(db, actor, owner_id) # only the Area Manager assigned to this MR's headquarters
|
||||||
|
row = await _get_or_create(db, table_name, owner_id)
|
||||||
|
if row.status == "approved":
|
||||||
|
return row # a double click
|
||||||
|
if row.status != "pending" or await _row_count(db, table_name, owner_id) == 0:
|
||||||
|
raise ConflictError("Nothing is waiting for approval on this form")
|
||||||
|
row.status = "approved"
|
||||||
|
row.approved_by_user_id = actor.id
|
||||||
|
row.approved_by_name = actor.full_name
|
||||||
|
await db.commit()
|
||||||
|
await db.refresh(row)
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
async def invalidate(db: AsyncSession, table_name: str, owner_id: uuid.UUID | None) -> None:
|
||||||
|
"""The MR's rows changed: any earlier approval no longer applies. The caller commits."""
|
||||||
|
if table_name not in APPROVAL_TABLES or owner_id is None:
|
||||||
|
return
|
||||||
|
row = await get_approval(db, table_name, owner_id)
|
||||||
|
if row is not None and row.status != "draft":
|
||||||
|
row.status = "draft"
|
||||||
|
row.approved_by_user_id = None
|
||||||
|
row.approved_by_name = None
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
"""Allow-listed imported CSV tables and their database columns."""
|
||||||
|
|
||||||
|
TABLES: dict[str, tuple[str, ...]] = {
|
||||||
|
"sales_projection": ("name", "headquarter", "report_date", "month", "serial_no", "product_name", "pts", "secondary_qty", "value", "closing", "secondary_value", "aug_sales", "value_2"),
|
||||||
|
"weekly_report": ("employee_name", "report_date", "headquarter", "month", "no_of_days_worked", "no_of_doctor_called", "no_of_chemist_called", "pob_booked", "secondary_sales", "pob_objective", "secondary_objective", "product_offer_scheme_booked", "product_offer_scheme_objective"),
|
||||||
|
"field_activity_report": ("name", "headquarter", "month", "report_date", "station_worked", "no_of_doctors_called", "no_of_chemists_pds_called", "doctor_call_avg", "chemist_call_avg"),
|
||||||
|
"fare_chart": ("name", "headquarter", "serial_no", "report_date", "from_location", "to_location", "kilometers_km"),
|
||||||
|
"daily_call_report_csv": ("name", "headquarter", "report_date", "month", "doctor_sr_no", "doctor_name", "qualification", "product_promote", "product_sample", "remarks", "chemist_sr_no", "chemist_name", "pob", "stockist_visit", "order_value"),
|
||||||
|
"core_dr_call_conversion": ("name", "headquarter", "month", "doctor_name", "date_of_visit", "product_targeted", "status"),
|
||||||
|
"area_covered": ("name", "headquarter", "month", "sale_status", "area_to_cover", "sale_objective", "status"),
|
||||||
|
"sales_and_stock_statement": ("name", "headquarter", "report_date", "month", "serial_no", "product_name", "opening", "receipt", "sale", "closing", "value_in_pts"),
|
||||||
|
"tour_plan": ("name", "headquarter", "serial_no", "report_date", "from_location", "to_location", "pob", "stockiest_visit"),
|
||||||
|
"standard_tour_plan": ("name", "headquarter", "serial_no", "place"),
|
||||||
|
}
|
||||||
|
|
||||||
|
CSV_LABELS = {
|
||||||
|
"weekly_report": "Weekly Report",
|
||||||
|
"field_activity_report": "Field Activity Report",
|
||||||
|
"fare_chart": "Fare Chart",
|
||||||
|
"daily_call_report_csv": "Daily Call Report CSV",
|
||||||
|
"core_dr_call_conversion": "Core Doctor Call Conversion",
|
||||||
|
"area_covered": "Area Covered",
|
||||||
|
"sales_and_stock_statement": "Sales and Stock Statement",
|
||||||
|
"tour_plan": "Tour Plan",
|
||||||
|
"standard_tour_plan": "Standard Tour Plan",
|
||||||
|
"sales_projection": "Sales Projection",
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""Approval state of the company forms that carry an Area Manager signature."""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import DateTime, ForeignKey, String, func
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from app.database.base import Base
|
||||||
|
|
||||||
|
#: draft = not sent yet, pending = the MR asked for approval, approved = the Area Manager signed.
|
||||||
|
FORM_APPROVAL_STATUSES = ("draft", "pending", "approved")
|
||||||
|
|
||||||
|
|
||||||
|
class FormApproval(Base):
|
||||||
|
"""One row per (approval form, MR): each MR's tour plan, standard tour plan and fare chart is approved on its own."""
|
||||||
|
|
||||||
|
__tablename__ = "form_approval"
|
||||||
|
|
||||||
|
table_name: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||||
|
#: The MR whose rows these are.
|
||||||
|
owner_user_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="CASCADE"), primary_key=True
|
||||||
|
)
|
||||||
|
status: Mapped[str] = mapped_column(String(10), nullable=False, default="draft", server_default="draft")
|
||||||
|
requested_by_user_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="SET NULL")
|
||||||
|
)
|
||||||
|
approved_by_user_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="SET NULL")
|
||||||
|
)
|
||||||
|
#: The name printed on the PDF. A snapshot, so renaming the user never rewrites a signature.
|
||||||
|
approved_by_name: Mapped[str | None] = mapped_column(String(200))
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), nullable=False
|
||||||
|
)
|
||||||
@@ -0,0 +1,493 @@
|
|||||||
|
import re
|
||||||
|
import uuid
|
||||||
|
from collections.abc import Iterable
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Body, Depends, Query, status
|
||||||
|
from fastapi.responses import Response
|
||||||
|
from sqlalchemy import select, text
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth.dependencies import require_role
|
||||||
|
from app.common.enums import Role
|
||||||
|
from app.common.exceptions import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||||
|
from app.config.settings import settings
|
||||||
|
from app.csv_data import approval as approvals
|
||||||
|
from app.csv_data.config import CSV_LABELS, TABLES
|
||||||
|
from app.database.session import get_db
|
||||||
|
from app.users.models import User
|
||||||
|
from app.organization.models import Headquarters
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/csv-data", tags=["CSV data"])
|
||||||
|
SERIAL_COLUMNS = {"serial_no", "doctor_sr_no", "chemist_sr_no"}
|
||||||
|
IDENTITY_COLUMNS = {"name", "employee_name", "headquarter"}
|
||||||
|
APPROVAL_TABLES = approvals.APPROVAL_TABLES
|
||||||
|
HIDDEN_TABLES = {"daily_call_report_csv"}
|
||||||
|
#: Forms where every row belongs to one MR (and is approved by that MR's Area Manager).
|
||||||
|
OWNED_TABLES = APPROVAL_TABLES
|
||||||
|
|
||||||
|
|
||||||
|
def _table(table_name: str) -> tuple[str, ...]:
|
||||||
|
if table_name not in TABLES:
|
||||||
|
raise NotFoundError("CSV table not found", {"table": table_name})
|
||||||
|
return TABLES[table_name]
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_payload(table_name: str, payload: dict[str, object]) -> dict[str, str | None]:
|
||||||
|
columns = _table(table_name)
|
||||||
|
unknown = set(payload) - set(columns)
|
||||||
|
if unknown:
|
||||||
|
raise ValidationError("Unknown CSV column", {"columns": sorted(unknown)})
|
||||||
|
return {column: None if payload.get(column) is None else str(payload.get(column, "")) for column in columns}
|
||||||
|
|
||||||
|
|
||||||
|
def _has_user_data(table_name: str, values: dict[str, str | None]) -> bool:
|
||||||
|
return any(value and column not in SERIAL_COLUMNS for column, value in values.items())
|
||||||
|
|
||||||
|
|
||||||
|
async def _reject_repeat(
|
||||||
|
table_name: str, values: dict[str, str | None], db: AsyncSession, owner_id: uuid.UUID | None = None
|
||||||
|
) -> None:
|
||||||
|
"""A row identical to one already in the form is a repeat (a double click), not new data."""
|
||||||
|
compared = [c for c in _table(table_name) if c not in SERIAL_COLUMNS]
|
||||||
|
conditions = " AND ".join(f"COALESCE(\"{c}\", '') = :c_{i}" for i, c in enumerate(compared))
|
||||||
|
params: dict[str, object] = {f"c_{i}": (values.get(c) or "") for i, c in enumerate(compared)}
|
||||||
|
if owner_id is not None:
|
||||||
|
conditions += " AND owner_user_id = :owner"
|
||||||
|
params["owner"] = owner_id
|
||||||
|
if (await db.execute(text(f'SELECT 1 FROM "{table_name}" WHERE {conditions} LIMIT 1'), params)).first():
|
||||||
|
raise ConflictError("An identical row already exists in this form")
|
||||||
|
|
||||||
|
|
||||||
|
async def _renumber_rows(table_name: str, db: AsyncSession) -> None:
|
||||||
|
columns = _table(table_name)
|
||||||
|
# An MR's own form is numbered 1, 2, 3… whoever else has rows in the same table.
|
||||||
|
partition = "PARTITION BY owner_user_id " if table_name in OWNED_TABLES else ""
|
||||||
|
serial_updates = ""
|
||||||
|
for column in columns:
|
||||||
|
if column in SERIAL_COLUMNS:
|
||||||
|
serial_updates += f', "{column}" = numbered.serial::text'
|
||||||
|
await db.execute(
|
||||||
|
text(
|
||||||
|
f'''WITH numbered AS (
|
||||||
|
SELECT id,
|
||||||
|
ROW_NUMBER() OVER (ORDER BY source_row_number, id) AS row_number,
|
||||||
|
ROW_NUMBER() OVER ({partition}ORDER BY source_row_number, id) AS serial
|
||||||
|
FROM "{table_name}"
|
||||||
|
)
|
||||||
|
UPDATE "{table_name}" AS target
|
||||||
|
SET source_row_number = numbered.row_number{serial_updates}
|
||||||
|
FROM numbered
|
||||||
|
WHERE target.id = numbered.id'''
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def _apply_mr_identity(
|
||||||
|
values: dict[str, str | None], subject: User | None, db: AsyncSession
|
||||||
|
) -> dict[str, str | None]:
|
||||||
|
"""Fill NAME / HEADQUARTER from the MR the row is for (the signed-in MR, or the one an admin picked)."""
|
||||||
|
if subject is None or subject.role != Role.MR:
|
||||||
|
return values
|
||||||
|
headquarters_name = None
|
||||||
|
if subject.headquarters_id:
|
||||||
|
headquarters = await db.get(Headquarters, subject.headquarters_id)
|
||||||
|
headquarters_name = headquarters.name if headquarters else None
|
||||||
|
for column in values:
|
||||||
|
if column in {"name", "employee_name"}:
|
||||||
|
values[column] = subject.full_name
|
||||||
|
elif column == "headquarter":
|
||||||
|
values[column] = headquarters_name
|
||||||
|
return values
|
||||||
|
|
||||||
|
|
||||||
|
async def _present_rows_for_user(
|
||||||
|
rows: list[dict[str, object]], current_user: User, db: AsyncSession
|
||||||
|
) -> list[dict[str, object]]:
|
||||||
|
"""Show account identity from the session without changing imported data.
|
||||||
|
|
||||||
|
Admins must see the source values and every row. MRs use the imported rows as
|
||||||
|
their working data, but identity columns must always reflect the logged-in MR.
|
||||||
|
"""
|
||||||
|
if current_user.role != Role.MR:
|
||||||
|
return rows
|
||||||
|
|
||||||
|
headquarters_name = None
|
||||||
|
if current_user.headquarters_id:
|
||||||
|
headquarters = await db.get(Headquarters, current_user.headquarters_id)
|
||||||
|
headquarters_name = headquarters.name if headquarters else None
|
||||||
|
|
||||||
|
presented: list[dict[str, object]] = []
|
||||||
|
for row in rows:
|
||||||
|
item = dict(row)
|
||||||
|
if "name" in item:
|
||||||
|
item["name"] = current_user.full_name
|
||||||
|
if "employee_name" in item:
|
||||||
|
item["employee_name"] = current_user.full_name
|
||||||
|
if "headquarter" in item:
|
||||||
|
item["headquarter"] = headquarters_name or ""
|
||||||
|
presented.append(item)
|
||||||
|
return presented
|
||||||
|
|
||||||
|
|
||||||
|
async def _apply_sales_projection_product(
|
||||||
|
values: dict[str, str | None], db: AsyncSession, current_user: User | None = None
|
||||||
|
) -> dict[str, str | None]:
|
||||||
|
if values.get("product_name") is None:
|
||||||
|
return values
|
||||||
|
if current_user is not None and current_user.role == Role.ADMIN:
|
||||||
|
# Admin maintains the product list itself: any product name and PTS may be entered.
|
||||||
|
if not (values.get("product_name") or "").strip():
|
||||||
|
raise ValidationError("Enter a product name")
|
||||||
|
return values
|
||||||
|
result = await db.execute(
|
||||||
|
text(
|
||||||
|
'SELECT pts FROM "sales_projection" '
|
||||||
|
'WHERE product_name = :product_name LIMIT 1'
|
||||||
|
),
|
||||||
|
{"product_name": values["product_name"]},
|
||||||
|
)
|
||||||
|
pts = result.scalar_one_or_none()
|
||||||
|
if pts is None:
|
||||||
|
raise ValidationError(
|
||||||
|
"Choose a product from the Sales Projection product list",
|
||||||
|
{"product_name": values["product_name"]},
|
||||||
|
)
|
||||||
|
values["pts"] = str(pts)
|
||||||
|
return values
|
||||||
|
|
||||||
|
|
||||||
|
def _select(table_name: str, columns: Iterable[str]) -> str:
|
||||||
|
selected = ", ".join(f'"{column}"' for column in columns)
|
||||||
|
return f'SELECT id, source_row_number, {selected} FROM "{table_name}"'
|
||||||
|
|
||||||
|
|
||||||
|
async def _owner_condition(
|
||||||
|
table_name: str, current_user: User, db: AsyncSession, owner_id: uuid.UUID | None
|
||||||
|
) -> tuple[list[str], dict[str, object]]:
|
||||||
|
"""Limit an approval form's rows to the MRs this user may see: an MR sees only their own,
|
||||||
|
an Area Manager only the MRs of their headquarters, an admin anyone (or one chosen MR)."""
|
||||||
|
if table_name not in OWNED_TABLES:
|
||||||
|
return [], {}
|
||||||
|
if current_user.role == Role.MR:
|
||||||
|
if owner_id not in (None, current_user.id):
|
||||||
|
raise ForbiddenError("You can only see your own forms")
|
||||||
|
return ["owner_user_id = :owner"], {"owner": current_user.id}
|
||||||
|
if owner_id is not None:
|
||||||
|
await approvals.assert_owner_in_scope(db, current_user, owner_id)
|
||||||
|
return ["owner_user_id = :owner"], {"owner": owner_id}
|
||||||
|
if current_user.role == Role.AM:
|
||||||
|
return ["owner_user_id = ANY(:owners)"], {"owners": [o.id for o in await approvals.owners_in_scope(db, current_user)]}
|
||||||
|
return [], {}
|
||||||
|
|
||||||
|
|
||||||
|
async def _row_owner(table_name: str, row_id: uuid.UUID, current_user: User, db: AsyncSession) -> uuid.UUID | None:
|
||||||
|
"""Who owns this row, after checking `current_user` is allowed to touch it."""
|
||||||
|
if table_name not in OWNED_TABLES:
|
||||||
|
return None
|
||||||
|
found = (await db.execute(text(f'SELECT owner_user_id FROM "{table_name}" WHERE id = :id'), {"id": row_id})).first()
|
||||||
|
if found is None:
|
||||||
|
raise NotFoundError("CSV row not found", {"id": str(row_id)})
|
||||||
|
owner_id = found[0]
|
||||||
|
if current_user.role == Role.MR and owner_id != current_user.id:
|
||||||
|
raise ForbiddenError("This row belongs to another medical representative")
|
||||||
|
if current_user.role == Role.AM:
|
||||||
|
if owner_id is None:
|
||||||
|
raise ForbiddenError("This row is outside your headquarters")
|
||||||
|
await approvals.assert_owner_in_scope(db, current_user, owner_id)
|
||||||
|
return owner_id
|
||||||
|
|
||||||
|
|
||||||
|
def _month_filter(table_name: str, month: str | None) -> tuple[list[str], dict[str, object]]:
|
||||||
|
if not month or not month.strip():
|
||||||
|
return [], {}
|
||||||
|
if "month" not in _table(table_name):
|
||||||
|
raise ValidationError("This form has no month to filter by", {"table": table_name})
|
||||||
|
return ["lower(btrim(COALESCE(\"month\", ''))) = :month"], {"month": month.strip().lower()}
|
||||||
|
|
||||||
|
|
||||||
|
async def _load_rows(
|
||||||
|
table_name: str, db: AsyncSession, current_user: User, owner_id: uuid.UUID | None = None, month: str | None = None
|
||||||
|
) -> list[dict[str, object]]:
|
||||||
|
columns = _table(table_name)
|
||||||
|
conditions, params = await _owner_condition(table_name, current_user, db, owner_id)
|
||||||
|
more, extra = _month_filter(table_name, month)
|
||||||
|
where = f" WHERE {' AND '.join(conditions + more)}" if conditions or more else ""
|
||||||
|
result = await db.execute(text(f"{_select(table_name, columns)}{where} ORDER BY source_row_number"), {**params, **extra})
|
||||||
|
return await _present_rows_for_user([dict(row) for row in result.mappings().all()], current_user, db)
|
||||||
|
|
||||||
|
|
||||||
|
def _available_csv_tables(current_user: User) -> list[str]:
|
||||||
|
visible = [name for name in TABLES if name not in HIDDEN_TABLES]
|
||||||
|
if current_user.role == Role.AM:
|
||||||
|
return [name for name in visible if name in APPROVAL_TABLES]
|
||||||
|
return visible
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_table_access(table_name: str, current_user: User) -> None:
|
||||||
|
if table_name in HIDDEN_TABLES:
|
||||||
|
raise ForbiddenError("This CSV form is not available for export.", {"table": table_name})
|
||||||
|
if current_user.role == Role.AM and table_name not in APPROVAL_TABLES:
|
||||||
|
raise ForbiddenError("Area Manager can only access approval forms.", {"table": table_name})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/tables")
|
||||||
|
async def list_csv_tables(current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM))) -> list[dict[str, object]]:
|
||||||
|
return [{"name": name, "label": CSV_LABELS[name], "columns": list(TABLES[name])} for name in _available_csv_tables(current_user)]
|
||||||
|
|
||||||
|
|
||||||
|
async def _signature(
|
||||||
|
table_name: str, owner_id: uuid.UUID | None, db: AsyncSession
|
||||||
|
) -> tuple[str | None, str | None, str | None]:
|
||||||
|
"""(status, approver name, approval date/time) for the PDF's signature — decided here, never by the browser.
|
||||||
|
|
||||||
|
It is the approval of the one MR whose rows the PDF holds; a PDF mixing several MRs is never signed."""
|
||||||
|
if table_name not in APPROVAL_TABLES:
|
||||||
|
return None, None, None
|
||||||
|
row = await approvals.get_approval(db, table_name, owner_id) if owner_id else None
|
||||||
|
if row is None or row.status != "approved":
|
||||||
|
return "pending", None, None
|
||||||
|
when = row.updated_at.astimezone(ZoneInfo(settings.APP_TIMEZONE)).strftime("%d/%m/%Y %H:%M") if row.updated_at else None
|
||||||
|
return "approved", row.approved_by_name, when
|
||||||
|
|
||||||
|
|
||||||
|
def _approval_out(row, owner: User, headquarters_name: str | None = None) -> dict[str, object]:
|
||||||
|
return {
|
||||||
|
"table_name": row.table_name,
|
||||||
|
"owner_user_id": str(owner.id),
|
||||||
|
"owner_name": owner.full_name,
|
||||||
|
"headquarters_name": headquarters_name,
|
||||||
|
"status": row.status,
|
||||||
|
"approved_by_name": row.approved_by_name,
|
||||||
|
"updated_at": row.updated_at.isoformat() if row.updated_at else None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def _hq_name(db: AsyncSession, user: User) -> str | None:
|
||||||
|
headquarters = await db.get(Headquarters, user.headquarters_id) if user.headquarters_id else None
|
||||||
|
return headquarters.name if headquarters else None
|
||||||
|
|
||||||
|
|
||||||
|
def _approval_table(table_name: str) -> str:
|
||||||
|
if table_name not in APPROVAL_TABLES:
|
||||||
|
raise NotFoundError("This form has no approval step", {"table": table_name})
|
||||||
|
return table_name
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/approvals")
|
||||||
|
async def list_form_approvals(
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM)),
|
||||||
|
) -> list[dict[str, object]]:
|
||||||
|
"""Approval state of the forms that carry an Area Manager signature, limited to the MRs this user may see."""
|
||||||
|
return [_approval_out(r, owner, hq) for r, owner, hq in await approvals.list_approvals(db, current_user)]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/owners")
|
||||||
|
async def list_form_owners(
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM)),
|
||||||
|
) -> list[dict[str, object]]:
|
||||||
|
"""The medical representatives whose forms this user may open."""
|
||||||
|
hq = {h.id: h.name for h in (await db.execute(select(Headquarters))).scalars()}
|
||||||
|
return [
|
||||||
|
{"id": str(o.id), "name": o.full_name, "employee_code": o.employee_code, "headquarters_name": hq.get(o.headquarters_id)}
|
||||||
|
for o in await approvals.owners_in_scope(db, current_user)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{table_name}/approval/request")
|
||||||
|
async def request_form_approval(
|
||||||
|
table_name: str,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_role(Role.MR)),
|
||||||
|
) -> dict[str, object]:
|
||||||
|
"""The MR sends a form to the Area Manager."""
|
||||||
|
row = await approvals.request_approval(db, _approval_table(table_name), current_user)
|
||||||
|
return _approval_out(row, current_user, await _hq_name(db, current_user))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{table_name}/approval/approve")
|
||||||
|
async def approve_form(
|
||||||
|
table_name: str,
|
||||||
|
owner_id: uuid.UUID = Query(description="The MR whose form is being approved"),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_role(Role.AM)),
|
||||||
|
) -> dict[str, object]:
|
||||||
|
"""The Area Manager signs an MR's form — only the one who manages that MR's headquarters."""
|
||||||
|
row = await approvals.approve(db, _approval_table(table_name), owner_id, current_user)
|
||||||
|
owner = await db.get(User, owner_id)
|
||||||
|
return _approval_out(row, owner, await _hq_name(db, owner))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{table_name}/rows")
|
||||||
|
async def list_csv_rows(
|
||||||
|
table_name: str,
|
||||||
|
owner_id: uuid.UUID | None = None,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM)),
|
||||||
|
) -> list[dict[str, object]]:
|
||||||
|
_ensure_table_access(table_name, current_user)
|
||||||
|
return await _load_rows(table_name, db, current_user, owner_id)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{table_name}/rows", status_code=status.HTTP_201_CREATED)
|
||||||
|
async def create_csv_row(
|
||||||
|
table_name: str,
|
||||||
|
payload: dict[str, object] = Body(...),
|
||||||
|
owner_id: uuid.UUID | None = None,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_role(Role.MR, Role.ADMIN)),
|
||||||
|
) -> dict[str, object]:
|
||||||
|
columns = _table(table_name)
|
||||||
|
values = _clean_payload(table_name, payload)
|
||||||
|
owner: User | None = None
|
||||||
|
if table_name in OWNED_TABLES:
|
||||||
|
if current_user.role == Role.MR:
|
||||||
|
owner = current_user
|
||||||
|
elif owner_id is None:
|
||||||
|
raise ValidationError("Choose which medical representative this row is for")
|
||||||
|
else:
|
||||||
|
owner = await approvals.assert_owner_in_scope(db, current_user, owner_id)
|
||||||
|
values = await _apply_mr_identity(values, owner or current_user, db)
|
||||||
|
if table_name == "sales_projection":
|
||||||
|
values = await _apply_sales_projection_product(values, db, current_user)
|
||||||
|
if not _has_user_data(table_name, values):
|
||||||
|
raise ValidationError("Add at least one value before creating a row")
|
||||||
|
await _reject_repeat(table_name, values, db, owner.id if owner else None)
|
||||||
|
next_row = (await db.execute(text(f'SELECT COALESCE(MAX(source_row_number), 0) + 1 FROM "{table_name}"'))).scalar_one()
|
||||||
|
for column in columns:
|
||||||
|
if column in SERIAL_COLUMNS:
|
||||||
|
values[column] = str(next_row)
|
||||||
|
extra_ids, extra_params = (["owner_user_id"], [":owner_user_id"]) if owner else ([], [])
|
||||||
|
identifiers = ", ".join(["id", "source_row_number", *extra_ids, *[f'"{column}"' for column in columns]])
|
||||||
|
parameters = ", ".join([":id", ":source_row_number", *extra_params, *[f":{column}" for column in columns]])
|
||||||
|
values.update(id=uuid.uuid4(), source_row_number=next_row)
|
||||||
|
if owner:
|
||||||
|
values["owner_user_id"] = owner.id
|
||||||
|
result = await db.execute(text(f'INSERT INTO "{table_name}" ({identifiers}) VALUES ({parameters}) RETURNING id'), values)
|
||||||
|
row_id = result.scalar_one()
|
||||||
|
await _renumber_rows(table_name, db)
|
||||||
|
await approvals.invalidate(db, table_name, owner.id if owner else None)
|
||||||
|
await db.commit()
|
||||||
|
return await _get_row(table_name, row_id, db)
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/{table_name}/rows/{row_id}")
|
||||||
|
async def update_csv_row(table_name: str, row_id: uuid.UUID, payload: dict[str, object] = Body(...), db: AsyncSession = Depends(get_db), current_user: User = Depends(require_role(Role.MR, Role.ADMIN))) -> dict[str, object]:
|
||||||
|
values = _clean_payload(table_name, payload)
|
||||||
|
row_owner = await _row_owner(table_name, row_id, current_user, db)
|
||||||
|
values = await _apply_mr_identity(values, current_user, db)
|
||||||
|
if table_name == "sales_projection":
|
||||||
|
values = await _apply_sales_projection_product(values, db, current_user)
|
||||||
|
changes = {column: value for column, value in values.items() if column in payload}
|
||||||
|
if not changes:
|
||||||
|
raise ValidationError("At least one CSV column is required")
|
||||||
|
if not _has_user_data(table_name, {**values, **changes}):
|
||||||
|
raise ValidationError("A row must contain at least one value")
|
||||||
|
changes = {column: value for column, value in changes.items() if column not in SERIAL_COLUMNS}
|
||||||
|
if not changes:
|
||||||
|
raise ValidationError("Serial numbers are generated automatically")
|
||||||
|
assignments = ", ".join(f'"{column}" = :{column}' for column in changes)
|
||||||
|
result = await db.execute(text(f'UPDATE "{table_name}" SET {assignments} WHERE id = :id RETURNING id'), {**changes, "id": row_id})
|
||||||
|
if result.scalar_one_or_none() is None:
|
||||||
|
raise NotFoundError("CSV row not found", {"id": str(row_id)})
|
||||||
|
await approvals.invalidate(db, table_name, row_owner)
|
||||||
|
await db.commit()
|
||||||
|
return await _get_row(table_name, row_id, db)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{table_name}/rows/{row_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
async def delete_csv_row(table_name: str, row_id: uuid.UUID, db: AsyncSession = Depends(get_db), current_user: User = Depends(require_role(Role.MR, Role.ADMIN))) -> None:
|
||||||
|
_table(table_name)
|
||||||
|
row_owner = await _row_owner(table_name, row_id, current_user, db)
|
||||||
|
result = await db.execute(text(f'DELETE FROM "{table_name}" WHERE id = :id'), {"id": row_id})
|
||||||
|
if result.rowcount == 0:
|
||||||
|
raise NotFoundError("CSV row not found", {"id": str(row_id)})
|
||||||
|
await _renumber_rows(table_name, db)
|
||||||
|
await approvals.invalidate(db, table_name, row_owner)
|
||||||
|
await db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
async def _get_row(table_name: str, row_id: uuid.UUID, db: AsyncSession) -> dict[str, object]:
|
||||||
|
columns = _table(table_name)
|
||||||
|
result = await db.execute(text(f'{_select(table_name, columns)} WHERE id = :id'), {"id": row_id})
|
||||||
|
row = result.mappings().one_or_none()
|
||||||
|
if row is None:
|
||||||
|
raise NotFoundError("CSV row not found", {"id": str(row_id)})
|
||||||
|
return dict(row)
|
||||||
|
|
||||||
|
|
||||||
|
def _pdf_bytes(
|
||||||
|
table_name: str,
|
||||||
|
table_label: str,
|
||||||
|
row: dict[str, object],
|
||||||
|
approval_status: str | None = None,
|
||||||
|
am_name: str | None = None,
|
||||||
|
approved_at: str | None = None,
|
||||||
|
) -> bytes:
|
||||||
|
from app.pdf.service import csv_table_pdf_bytes
|
||||||
|
return csv_table_pdf_bytes(
|
||||||
|
table_name,
|
||||||
|
table_label,
|
||||||
|
_table(table_name),
|
||||||
|
[row],
|
||||||
|
approval_status,
|
||||||
|
am_name,
|
||||||
|
approved_at=approved_at,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{table_name}/rows/{row_id}/pdf")
|
||||||
|
async def download_csv_row_pdf(
|
||||||
|
table_name: str,
|
||||||
|
row_id: uuid.UUID,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM)),
|
||||||
|
) -> Response:
|
||||||
|
_ensure_table_access(table_name, current_user)
|
||||||
|
row_owner = await _row_owner(table_name, row_id, current_user, db)
|
||||||
|
row = await _get_row(table_name, row_id, db)
|
||||||
|
row = (await _present_rows_for_user([row], current_user, db))[0]
|
||||||
|
approval_status, am_name, approved_at = await _signature(table_name, row_owner, db)
|
||||||
|
return Response(
|
||||||
|
_pdf_bytes(table_name, CSV_LABELS[table_name], row, approval_status, am_name, approved_at),
|
||||||
|
media_type="application/pdf",
|
||||||
|
headers={"Content-Disposition": f'attachment; filename="{table_name}-{row_id}.pdf"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{table_name}/pdf")
|
||||||
|
async def download_csv_table_pdfs(
|
||||||
|
table_name: str,
|
||||||
|
owner_id: uuid.UUID | None = None,
|
||||||
|
month: str | None = None,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM)),
|
||||||
|
) -> Response:
|
||||||
|
"""The whole form, or only one month of it (for the forms that have a month)."""
|
||||||
|
_ensure_table_access(table_name, current_user)
|
||||||
|
columns = _table(table_name)
|
||||||
|
rows = await _load_rows(table_name, db, current_user, owner_id, month)
|
||||||
|
if month and month.strip() and not rows:
|
||||||
|
raise NotFoundError(f"There are no rows for {month.strip()} in this form", {"month": month})
|
||||||
|
# The signature is that of the single MR whose rows these are; a PDF of several MRs is unsigned.
|
||||||
|
subject = current_user.id if current_user.role == Role.MR else owner_id
|
||||||
|
approval_status, am_name, approved_at = await _signature(table_name, subject, db)
|
||||||
|
from app.pdf.service import csv_table_pdf_bytes
|
||||||
|
suffix = re.sub(r"[^a-z]", "", month.lower()) if month else ""
|
||||||
|
filename = f"{table_name}-{suffix}.pdf" if suffix else f"{table_name}.pdf"
|
||||||
|
pdf = csv_table_pdf_bytes(
|
||||||
|
table_name,
|
||||||
|
CSV_LABELS[table_name],
|
||||||
|
columns,
|
||||||
|
rows,
|
||||||
|
approval_status,
|
||||||
|
am_name,
|
||||||
|
approved_at=approved_at,
|
||||||
|
)
|
||||||
|
return Response(
|
||||||
|
pdf,
|
||||||
|
media_type="application/pdf",
|
||||||
|
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
|
||||||
|
)
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
"""Single import point for every ORM model.
|
||||||
|
|
||||||
|
Alembic autogenerate and SQLAlchemy's string-based relationship resolution both need
|
||||||
|
every mapper registered before use. Import this module, never individual model
|
||||||
|
modules, when you need "all of them".
|
||||||
|
"""
|
||||||
|
|
||||||
|
from app.audit.models import AuditLog
|
||||||
|
from app.auth.models import RefreshToken
|
||||||
|
from app.chemists.models import Chemist, ChemistAssignment
|
||||||
|
from app.csv_data.models import FormApproval
|
||||||
|
from app.database.base import Base
|
||||||
|
from app.doctors.models import Doctor, DoctorAssignment
|
||||||
|
from app.organization.models import AMHeadquarters, Company, Headquarters
|
||||||
|
from app.products.models import Product
|
||||||
|
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall
|
||||||
|
from app.users.models import User
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"Base",
|
||||||
|
"AuditLog",
|
||||||
|
"RefreshToken",
|
||||||
|
"Chemist",
|
||||||
|
"FormApproval",
|
||||||
|
"ChemistAssignment",
|
||||||
|
"Doctor",
|
||||||
|
"DoctorAssignment",
|
||||||
|
"AMHeadquarters",
|
||||||
|
"Company",
|
||||||
|
"Headquarters",
|
||||||
|
"ChemistCall",
|
||||||
|
"DailyCallReport",
|
||||||
|
"DoctorCall",
|
||||||
|
"User",
|
||||||
|
"Product",
|
||||||
|
]
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
"""Declarative base and shared column mixins."""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import DateTime, func
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
||||||
|
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||||
|
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class UUIDMixin:
|
||||||
|
id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), primary_key=True, default=uuid.uuid4
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TimestampMixin:
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||||
|
)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True),
|
||||||
|
server_default=func.now(),
|
||||||
|
onupdate=func.now(),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"""Engine, session factory and the `get_db` request dependency.
|
||||||
|
|
||||||
|
One transaction per request: the dependency opens a session, the service layer
|
||||||
|
commits on success, and any escaping exception rolls the whole request back — so a
|
||||||
|
state change and its audit row can never be persisted separately.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import AsyncGenerator
|
||||||
|
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||||
|
|
||||||
|
from app.config.settings import settings
|
||||||
|
|
||||||
|
engine = create_async_engine(
|
||||||
|
settings.DATABASE_URL,
|
||||||
|
echo=settings.DB_ECHO,
|
||||||
|
pool_pre_ping=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
AsyncSessionLocal = async_sessionmaker(
|
||||||
|
bind=engine,
|
||||||
|
class_=AsyncSession,
|
||||||
|
expire_on_commit=False,
|
||||||
|
autoflush=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||||
|
async with AsyncSessionLocal() as session:
|
||||||
|
try:
|
||||||
|
yield session
|
||||||
|
except Exception:
|
||||||
|
await session.rollback()
|
||||||
|
raise
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"""Doctor master data and doctor → MR assignment.
|
||||||
|
|
||||||
|
Master data belongs to a HEADQUARTERS, not to an MR (A2). Assignment is a separate,
|
||||||
|
dated table so that when an MR leaves, the doctor list survives.
|
||||||
|
|
||||||
|
`core_doctor_conversion` was not created as a table (report §13.2): it would store
|
||||||
|
one enum per call, which is a column — `doctor.is_core_doctor` +
|
||||||
|
`doctor_call.conversion_status`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from sqlalchemy import Boolean, Date, ForeignKey, Index, String, UniqueConstraint, text
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
|
from app.database.base import Base, TimestampMixin, UUIDMixin
|
||||||
|
|
||||||
|
|
||||||
|
class Doctor(Base, UUIDMixin, TimestampMixin):
|
||||||
|
__tablename__ = "doctor"
|
||||||
|
__table_args__ = (
|
||||||
|
# Deduplication guard: two MRs must not create two records for one doctor.
|
||||||
|
UniqueConstraint(
|
||||||
|
"headquarters_id", "name", "clinic_address", name="uq_doctor_hq_name_clinic"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
headquarters_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("headquarters.id", ondelete="RESTRICT"), nullable=False
|
||||||
|
)
|
||||||
|
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||||
|
speciality: Mapped[str | None] = mapped_column(String(100))
|
||||||
|
qualification: Mapped[str | None] = mapped_column(String(100))
|
||||||
|
clinic_address: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
|
contact_number: Mapped[str | None] = mapped_column(String(20))
|
||||||
|
#: Core doctors are the high-value targets tracked for conversion.
|
||||||
|
is_core_doctor: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||||
|
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||||
|
|
||||||
|
assignments: Mapped[list["DoctorAssignment"]] = relationship(back_populates="doctor")
|
||||||
|
|
||||||
|
|
||||||
|
class DoctorAssignment(Base, UUIDMixin, TimestampMixin):
|
||||||
|
__tablename__ = "doctor_assignment"
|
||||||
|
__table_args__ = (
|
||||||
|
Index(
|
||||||
|
"uq_active_doctor_assignment",
|
||||||
|
"doctor_id",
|
||||||
|
unique=True,
|
||||||
|
postgresql_where=text("effective_to IS NULL"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
doctor_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("doctor.id", ondelete="CASCADE"), nullable=False
|
||||||
|
)
|
||||||
|
mr_user_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT"), nullable=False
|
||||||
|
)
|
||||||
|
effective_from: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
effective_to: Mapped[date | None] = mapped_column(Date)
|
||||||
|
|
||||||
|
doctor: Mapped["Doctor"] = relationship(back_populates="assignments")
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import uuid
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Request, status
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth.dependencies import client_ip, get_current_user, require_role
|
||||||
|
from app.common.enums import Role
|
||||||
|
from app.database.session import get_db
|
||||||
|
from app.doctors.models import Doctor
|
||||||
|
from app.doctors.schemas import AssignToMR, DoctorCreate, DoctorRead, DoctorUpdate
|
||||||
|
from app.doctors.service import DoctorService
|
||||||
|
from app.users.models import User
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/doctors", tags=["doctors"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=list[DoctorRead])
|
||||||
|
async def list_doctors(
|
||||||
|
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
||||||
|
) -> list[Doctor]:
|
||||||
|
"""S5 — an MR gets only their assigned doctors; managers get their HQ scope."""
|
||||||
|
return await DoctorService(db).list_for(current_user)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=DoctorRead, status_code=status.HTTP_201_CREATED)
|
||||||
|
async def create_doctor(
|
||||||
|
payload: DoctorCreate,
|
||||||
|
request: Request,
|
||||||
|
current_user: User = Depends(require_role(Role.ADMIN)),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> Doctor:
|
||||||
|
"""Only an Administrator can create a doctor (MR, AM and GM cannot)."""
|
||||||
|
return await DoctorService(db).create(payload, current_user, client_ip(request))
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/{doctor_id}", response_model=DoctorRead)
|
||||||
|
async def update_doctor(
|
||||||
|
doctor_id: uuid.UUID,
|
||||||
|
payload: DoctorUpdate,
|
||||||
|
request: Request,
|
||||||
|
current_user: User = Depends(require_role(Role.ADMIN)),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> Doctor:
|
||||||
|
return await DoctorService(db).update(doctor_id, payload, current_user, client_ip(request))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{doctor_id}/assign", status_code=status.HTTP_201_CREATED)
|
||||||
|
async def assign_doctor(
|
||||||
|
doctor_id: uuid.UUID,
|
||||||
|
payload: AssignToMR,
|
||||||
|
request: Request,
|
||||||
|
current_user: User = Depends(require_role(Role.ADMIN, Role.GM, Role.AM)),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""An AM may assign only within their own headquarters — enforced by data scope."""
|
||||||
|
assignment = await DoctorService(db).assign_to_mr(
|
||||||
|
doctor_id, payload.mr_user_id, payload.effective_from, current_user, client_ip(request)
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"id": assignment.id,
|
||||||
|
"doctor_id": assignment.doctor_id,
|
||||||
|
"mr_user_id": assignment.mr_user_id,
|
||||||
|
"effective_from": assignment.effective_from,
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
|
|
||||||
|
class DoctorCreate(BaseModel):
|
||||||
|
headquarters_id: uuid.UUID
|
||||||
|
name: str = Field(min_length=2, max_length=200)
|
||||||
|
clinic_address: str = Field(min_length=2, max_length=500)
|
||||||
|
speciality: str | None = Field(default=None, max_length=100)
|
||||||
|
qualification: str | None = Field(default=None, max_length=100)
|
||||||
|
contact_number: str | None = Field(default=None, max_length=20)
|
||||||
|
is_core_doctor: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class DoctorUpdate(BaseModel):
|
||||||
|
name: str | None = Field(default=None, min_length=2, max_length=200)
|
||||||
|
clinic_address: str | None = Field(default=None, min_length=2, max_length=500)
|
||||||
|
speciality: str | None = Field(default=None, max_length=100)
|
||||||
|
qualification: str | None = Field(default=None, max_length=100)
|
||||||
|
contact_number: str | None = Field(default=None, max_length=20)
|
||||||
|
is_core_doctor: bool | None = None
|
||||||
|
is_active: bool | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class DoctorRead(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: uuid.UUID
|
||||||
|
headquarters_id: uuid.UUID
|
||||||
|
name: str
|
||||||
|
clinic_address: str
|
||||||
|
speciality: str | None
|
||||||
|
qualification: str | None
|
||||||
|
contact_number: str | None
|
||||||
|
is_core_doctor: bool
|
||||||
|
is_active: bool
|
||||||
|
|
||||||
|
|
||||||
|
class AssignToMR(BaseModel):
|
||||||
|
mr_user_id: uuid.UUID
|
||||||
|
effective_from: date | None = None
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.audit.service import AuditService
|
||||||
|
from app.auth.dependencies import assert_can_view_hq, visible_hq_ids
|
||||||
|
from app.common.enums import AuditAction, EntityType, Role
|
||||||
|
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
|
||||||
|
from app.common.utils import snapshot
|
||||||
|
from app.doctors.models import Doctor, DoctorAssignment
|
||||||
|
from app.doctors.schemas import DoctorCreate, DoctorUpdate
|
||||||
|
from app.users.models import User
|
||||||
|
|
||||||
|
_AUDIT_FIELDS = ["name", "clinic_address", "speciality", "is_core_doctor", "is_active"]
|
||||||
|
|
||||||
|
|
||||||
|
class DoctorService:
|
||||||
|
def __init__(self, db: AsyncSession) -> None:
|
||||||
|
self.db = db
|
||||||
|
self.audit = AuditService(db)
|
||||||
|
|
||||||
|
async def create(self, data: DoctorCreate, actor: User, ip: str | None = None) -> Doctor:
|
||||||
|
# A2/A3 — masters are owned by ADMIN/GM. An MR cannot create a doctor.
|
||||||
|
await assert_can_view_hq(self.db, actor, data.headquarters_id)
|
||||||
|
|
||||||
|
doctor = Doctor(**data.model_dump())
|
||||||
|
self.db.add(doctor)
|
||||||
|
try:
|
||||||
|
await self.db.flush()
|
||||||
|
except IntegrityError as exc:
|
||||||
|
await self.db.rollback()
|
||||||
|
raise ConflictError(
|
||||||
|
"A doctor with this name already exists at this clinic in this headquarters",
|
||||||
|
{"cause": "uq_doctor_hq_name_clinic"},
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
await self.audit.log(
|
||||||
|
actor_user_id=actor.id,
|
||||||
|
entity_type=EntityType.DOCTOR,
|
||||||
|
entity_id=doctor.id,
|
||||||
|
action=AuditAction.CREATE,
|
||||||
|
after=snapshot(doctor, _AUDIT_FIELDS),
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
|
await self.db.commit()
|
||||||
|
return doctor
|
||||||
|
|
||||||
|
async def update(
|
||||||
|
self, doctor_id: uuid.UUID, data: DoctorUpdate, actor: User, ip: str | None = None
|
||||||
|
) -> Doctor:
|
||||||
|
doctor = await self.db.get(Doctor, doctor_id)
|
||||||
|
if doctor is None:
|
||||||
|
raise NotFoundError("Doctor not found")
|
||||||
|
await assert_can_view_hq(self.db, actor, doctor.headquarters_id)
|
||||||
|
|
||||||
|
before = snapshot(doctor, _AUDIT_FIELDS)
|
||||||
|
for field, value in data.model_dump(exclude_unset=True).items():
|
||||||
|
setattr(doctor, field, value)
|
||||||
|
|
||||||
|
await self.audit.log(
|
||||||
|
actor_user_id=actor.id,
|
||||||
|
entity_type=EntityType.DOCTOR,
|
||||||
|
entity_id=doctor.id,
|
||||||
|
action=AuditAction.UPDATE,
|
||||||
|
before=before,
|
||||||
|
after=snapshot(doctor, _AUDIT_FIELDS),
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
|
await self.db.commit()
|
||||||
|
return doctor
|
||||||
|
|
||||||
|
async def list_for(self, actor: User) -> list[Doctor]:
|
||||||
|
"""An MR sees ONLY doctors currently assigned to them (R5)."""
|
||||||
|
if actor.role == Role.MR:
|
||||||
|
stmt = (
|
||||||
|
select(Doctor)
|
||||||
|
.join(DoctorAssignment, DoctorAssignment.doctor_id == Doctor.id)
|
||||||
|
.where(
|
||||||
|
DoctorAssignment.mr_user_id == actor.id,
|
||||||
|
DoctorAssignment.effective_to.is_(None),
|
||||||
|
Doctor.is_active.is_(True),
|
||||||
|
)
|
||||||
|
.order_by(Doctor.name)
|
||||||
|
)
|
||||||
|
return list((await self.db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
|
allowed = await visible_hq_ids(self.db, actor)
|
||||||
|
stmt = select(Doctor).order_by(Doctor.name)
|
||||||
|
if allowed is not None:
|
||||||
|
stmt = stmt.where(Doctor.headquarters_id.in_(allowed or [None]))
|
||||||
|
return list((await self.db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
|
async def assign_to_mr(
|
||||||
|
self,
|
||||||
|
doctor_id: uuid.UUID,
|
||||||
|
mr_user_id: uuid.UUID,
|
||||||
|
effective_from: date | None,
|
||||||
|
actor: User,
|
||||||
|
ip: str | None = None,
|
||||||
|
) -> DoctorAssignment:
|
||||||
|
doctor = await self.db.get(Doctor, doctor_id)
|
||||||
|
if doctor is None:
|
||||||
|
raise NotFoundError("Doctor not found")
|
||||||
|
await assert_can_view_hq(self.db, actor, doctor.headquarters_id)
|
||||||
|
|
||||||
|
mr = await self.db.get(User, mr_user_id)
|
||||||
|
if mr is None:
|
||||||
|
raise NotFoundError("MR not found")
|
||||||
|
if mr.role != Role.MR:
|
||||||
|
raise ValidationError("Doctors can only be assigned to an MR")
|
||||||
|
# An MR may only be given doctors from their own headquarters.
|
||||||
|
if mr.headquarters_id != doctor.headquarters_id:
|
||||||
|
raise ValidationError(
|
||||||
|
"MR and doctor belong to different headquarters",
|
||||||
|
{
|
||||||
|
"mr_headquarters_id": str(mr.headquarters_id),
|
||||||
|
"doctor_headquarters_id": str(doctor.headquarters_id),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
start = effective_from or date.today()
|
||||||
|
existing = (
|
||||||
|
await self.db.execute(
|
||||||
|
select(DoctorAssignment).where(
|
||||||
|
DoctorAssignment.doctor_id == doctor_id,
|
||||||
|
DoctorAssignment.effective_to.is_(None),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
for row in existing:
|
||||||
|
if row.mr_user_id == mr_user_id:
|
||||||
|
return row
|
||||||
|
row.effective_to = start
|
||||||
|
await self.db.flush()
|
||||||
|
|
||||||
|
assignment = DoctorAssignment(
|
||||||
|
doctor_id=doctor_id, mr_user_id=mr_user_id, effective_from=start
|
||||||
|
)
|
||||||
|
self.db.add(assignment)
|
||||||
|
await self.audit.log(
|
||||||
|
actor_user_id=actor.id,
|
||||||
|
entity_type=EntityType.DOCTOR,
|
||||||
|
entity_id=doctor_id,
|
||||||
|
action=AuditAction.ASSIGN,
|
||||||
|
after={"mr_user_id": str(mr_user_id), "effective_from": start.isoformat()},
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
|
await self.db.commit()
|
||||||
|
return assignment
|
||||||
+113
@@ -0,0 +1,113 @@
|
|||||||
|
"""Application factory: router mount, middleware, exception handlers."""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from collections.abc import AsyncIterator
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
|
from fastapi import FastAPI, Request
|
||||||
|
from fastapi.encoders import jsonable_encoder
|
||||||
|
from fastapi.exceptions import RequestValidationError
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
|
||||||
|
from app.api.v1.router import api_router
|
||||||
|
from app.common.exceptions import AppError
|
||||||
|
from app.config.settings import settings
|
||||||
|
from app.database import all_models # noqa: F401 - registers every mapper
|
||||||
|
from app.pdf.service import pdf_engine_ready
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.DEBUG if settings.DEBUG else logging.INFO,
|
||||||
|
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _preflight() -> None:
|
||||||
|
"""Refuse to start a production instance that would silently misbehave."""
|
||||||
|
production = settings.ENVIRONMENT.lower() == "production"
|
||||||
|
if not pdf_engine_ready():
|
||||||
|
if production:
|
||||||
|
raise RuntimeError("WeasyPrint system libraries are required in production")
|
||||||
|
logger.warning("WeasyPrint is unavailable: PDFs will be plain text, not the form layout.")
|
||||||
|
weak_key = settings.SECRET_KEY.startswith("change-me") or len(settings.SECRET_KEY) < 32
|
||||||
|
if production and weak_key:
|
||||||
|
raise RuntimeError("SECRET_KEY must be a random value of at least 32 characters")
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
||||||
|
_preflight()
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
def create_app() -> FastAPI:
|
||||||
|
app = FastAPI(
|
||||||
|
lifespan=lifespan,
|
||||||
|
title=settings.APP_NAME,
|
||||||
|
version="0.1.0",
|
||||||
|
description=(
|
||||||
|
"Pharmaceutical field-force reporting — MVP. "
|
||||||
|
"Daily Call Reports with AM final approval, GM monitoring, "
|
||||||
|
"locked PDFs and audit trails."
|
||||||
|
),
|
||||||
|
docs_url="/docs",
|
||||||
|
redoc_url="/redoc",
|
||||||
|
openapi_url="/openapi.json",
|
||||||
|
)
|
||||||
|
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=settings.CORS_ORIGINS,
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---- one consistent error envelope -------------------------------
|
||||||
|
@app.exception_handler(AppError)
|
||||||
|
async def app_error_handler(_: Request, exc: AppError) -> JSONResponse:
|
||||||
|
return JSONResponse(status_code=exc.status_code, content=exc.to_dict())
|
||||||
|
|
||||||
|
@app.exception_handler(RequestValidationError)
|
||||||
|
async def validation_handler(_: Request, exc: RequestValidationError) -> JSONResponse:
|
||||||
|
# Pydantic puts the original exception object in `ctx`, which is not JSON
|
||||||
|
# serialisable — strip it, or the error handler itself becomes a 500.
|
||||||
|
errors = [
|
||||||
|
{k: v for k, v in error.items() if k != "ctx"}
|
||||||
|
| (
|
||||||
|
{"reason": str(error["ctx"].get("error"))}
|
||||||
|
if isinstance(error.get("ctx"), dict) and "error" in error["ctx"]
|
||||||
|
else {}
|
||||||
|
)
|
||||||
|
for error in exc.errors()
|
||||||
|
]
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=422,
|
||||||
|
content=jsonable_encoder(
|
||||||
|
{
|
||||||
|
"error": {
|
||||||
|
"code": "VALIDATION_ERROR",
|
||||||
|
"message": "Request payload failed validation",
|
||||||
|
"details": {"errors": errors},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
app.include_router(api_router, prefix=settings.API_V1_PREFIX)
|
||||||
|
|
||||||
|
@app.get("/health", tags=["meta"])
|
||||||
|
async def health() -> dict[str, str]:
|
||||||
|
return {
|
||||||
|
"status": "ok",
|
||||||
|
"environment": settings.ENVIRONMENT,
|
||||||
|
"pdf_engine": "weasyprint" if pdf_engine_ready() else "fallback",
|
||||||
|
}
|
||||||
|
|
||||||
|
return app
|
||||||
|
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
"""Company, Headquarters and the Area-Manager ↔ Headquarters mapping.
|
||||||
|
|
||||||
|
Design notes (report §13.2):
|
||||||
|
- `area_territory` was merged into `headquarters` — the brief states HQ *is* the
|
||||||
|
territory, and two tables for one concept invites drift.
|
||||||
|
- An MR's Area Manager is DERIVED through the headquarters, not stored on the MR.
|
||||||
|
An HQ handover therefore re-points every MR in that HQ with no data migration.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from sqlalchemy import Date, ForeignKey, Index, String, UniqueConstraint, text
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
|
from app.database.base import Base, TimestampMixin, UUIDMixin
|
||||||
|
|
||||||
|
|
||||||
|
class Company(Base, UUIDMixin, TimestampMixin):
|
||||||
|
"""Tenant root. Single company in the MVP (A17), but `company_id` is carried on
|
||||||
|
every table so multi-tenancy needs no migration later."""
|
||||||
|
|
||||||
|
__tablename__ = "company"
|
||||||
|
|
||||||
|
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||||
|
address: Mapped[str | None] = mapped_column(String(500))
|
||||||
|
is_active: Mapped[bool] = mapped_column(default=True, nullable=False)
|
||||||
|
|
||||||
|
headquarters: Mapped[list["Headquarters"]] = relationship(back_populates="company")
|
||||||
|
|
||||||
|
|
||||||
|
class Headquarters(Base, UUIDMixin, TimestampMixin):
|
||||||
|
"""A territory/location. NOT a login role (R8)."""
|
||||||
|
|
||||||
|
__tablename__ = "headquarters"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("company_id", "code", name="uq_hq_company_code"),
|
||||||
|
)
|
||||||
|
|
||||||
|
company_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("company.id", ondelete="RESTRICT"), nullable=False
|
||||||
|
)
|
||||||
|
code: Mapped[str] = mapped_column(String(20), nullable=False)
|
||||||
|
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||||
|
district: Mapped[str | None] = mapped_column(String(100))
|
||||||
|
state: Mapped[str | None] = mapped_column(String(100))
|
||||||
|
is_active: Mapped[bool] = mapped_column(default=True, nullable=False)
|
||||||
|
|
||||||
|
company: Mapped["Company"] = relationship(back_populates="headquarters")
|
||||||
|
am_mappings: Mapped[list["AMHeadquarters"]] = relationship(
|
||||||
|
back_populates="headquarters"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AMHeadquarters(Base, UUIDMixin, TimestampMixin):
|
||||||
|
"""Which Area Manager currently manages which headquarters.
|
||||||
|
|
||||||
|
`effective_to IS NULL` means "current". A partial unique index guarantees at most
|
||||||
|
one active Area Manager per headquarters at any time.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "am_headquarters"
|
||||||
|
__table_args__ = (
|
||||||
|
Index(
|
||||||
|
"uq_active_am_per_hq",
|
||||||
|
"headquarters_id",
|
||||||
|
unique=True,
|
||||||
|
postgresql_where=text("effective_to IS NULL"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
area_manager_user_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="RESTRICT"), nullable=False
|
||||||
|
)
|
||||||
|
headquarters_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True),
|
||||||
|
ForeignKey("headquarters.id", ondelete="RESTRICT"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
effective_from: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
effective_to: Mapped[date | None] = mapped_column(Date)
|
||||||
|
|
||||||
|
headquarters: Mapped["Headquarters"] = relationship(back_populates="am_mappings")
|
||||||
|
area_manager: Mapped["User"] = relationship() # noqa: F821
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import uuid
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Request, status
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.auth.dependencies import client_ip, get_current_user, require_role
|
||||||
|
from app.common.enums import Role
|
||||||
|
from app.database.session import get_db
|
||||||
|
from app.organization.models import Headquarters
|
||||||
|
from app.organization.schemas import (
|
||||||
|
AMHeadquartersRead,
|
||||||
|
AssignAreaManager,
|
||||||
|
HeadquartersCreate,
|
||||||
|
HeadquartersRead,
|
||||||
|
SetAreaManagerHeadquarters,
|
||||||
|
)
|
||||||
|
from app.organization.service import OrganizationService
|
||||||
|
from app.users.models import User
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/headquarters", tags=["organization"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=list[HeadquartersRead])
|
||||||
|
async def list_headquarters(
|
||||||
|
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
||||||
|
) -> list[Headquarters]:
|
||||||
|
"""Scoped: an MR sees their own HQ, an AM sees theirs, GM/Admin see all."""
|
||||||
|
return await OrganizationService(db).list_headquarters(current_user)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/area-managers", response_model=list[AMHeadquartersRead])
|
||||||
|
async def list_area_manager_mappings(
|
||||||
|
current_user: User = Depends(require_role(Role.ADMIN, Role.GM)),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Which Area Manager currently manages which headquarters (one row per pair)."""
|
||||||
|
return await OrganizationService(db).list_area_manager_mappings(current_user)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/area-managers/{area_manager_user_id}", response_model=list[AMHeadquartersRead])
|
||||||
|
async def set_area_manager_headquarters(
|
||||||
|
area_manager_user_id: uuid.UUID,
|
||||||
|
payload: SetAreaManagerHeadquarters,
|
||||||
|
request: Request,
|
||||||
|
current_user: User = Depends(require_role(Role.ADMIN)),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""Replace the set of headquarters an Area Manager manages (any number)."""
|
||||||
|
return await OrganizationService(db).set_area_manager_headquarters(
|
||||||
|
area_manager_user_id,
|
||||||
|
payload.headquarters_ids,
|
||||||
|
payload.effective_from,
|
||||||
|
current_user,
|
||||||
|
client_ip(request),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=HeadquartersRead, status_code=status.HTTP_201_CREATED)
|
||||||
|
async def create_headquarters(
|
||||||
|
payload: HeadquartersCreate,
|
||||||
|
request: Request,
|
||||||
|
current_user: User = Depends(require_role(Role.ADMIN)),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> Headquarters:
|
||||||
|
return await OrganizationService(db).create_headquarters(
|
||||||
|
payload, current_user, client_ip(request)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/{headquarters_id}/area-manager",
|
||||||
|
response_model=AMHeadquartersRead,
|
||||||
|
status_code=status.HTTP_201_CREATED,
|
||||||
|
)
|
||||||
|
async def assign_area_manager(
|
||||||
|
headquarters_id: uuid.UUID,
|
||||||
|
payload: AssignAreaManager,
|
||||||
|
request: Request,
|
||||||
|
current_user: User = Depends(require_role(Role.ADMIN)),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
):
|
||||||
|
return await OrganizationService(db).assign_area_manager(
|
||||||
|
headquarters_id,
|
||||||
|
payload.area_manager_user_id,
|
||||||
|
payload.effective_from,
|
||||||
|
current_user,
|
||||||
|
client_ip(request),
|
||||||
|
)
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
|
|
||||||
|
class CompanyCreate(BaseModel):
|
||||||
|
name: str = Field(min_length=2, max_length=200)
|
||||||
|
address: str | None = Field(default=None, max_length=500)
|
||||||
|
|
||||||
|
|
||||||
|
class CompanyRead(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: uuid.UUID
|
||||||
|
name: str
|
||||||
|
address: str | None
|
||||||
|
is_active: bool
|
||||||
|
|
||||||
|
|
||||||
|
class HeadquartersCreate(BaseModel):
|
||||||
|
code: str = Field(min_length=1, max_length=20)
|
||||||
|
name: str = Field(min_length=2, max_length=200)
|
||||||
|
district: str | None = Field(default=None, max_length=100)
|
||||||
|
state: str | None = Field(default=None, max_length=100)
|
||||||
|
|
||||||
|
|
||||||
|
class HeadquartersRead(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: uuid.UUID
|
||||||
|
company_id: uuid.UUID
|
||||||
|
code: str
|
||||||
|
name: str
|
||||||
|
district: str | None
|
||||||
|
state: str | None
|
||||||
|
is_active: bool
|
||||||
|
|
||||||
|
|
||||||
|
class AssignAreaManager(BaseModel):
|
||||||
|
area_manager_user_id: uuid.UUID
|
||||||
|
effective_from: date | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class SetAreaManagerHeadquarters(BaseModel):
|
||||||
|
"""The complete list of headquarters an Area Manager should manage (may be empty)."""
|
||||||
|
|
||||||
|
headquarters_ids: list[uuid.UUID] = Field(default_factory=list, max_length=500)
|
||||||
|
effective_from: date | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class AMHeadquartersRead(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: uuid.UUID
|
||||||
|
area_manager_user_id: uuid.UUID
|
||||||
|
headquarters_id: uuid.UUID
|
||||||
|
effective_from: date
|
||||||
|
effective_to: date | None
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
import uuid
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.audit.service import AuditService
|
||||||
|
from app.auth.dependencies import visible_hq_ids
|
||||||
|
from app.common.enums import AuditAction, EntityType, Role
|
||||||
|
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
|
||||||
|
from app.organization.models import AMHeadquarters, Company, Headquarters
|
||||||
|
from app.organization.schemas import HeadquartersCreate
|
||||||
|
from app.users.models import User
|
||||||
|
|
||||||
|
|
||||||
|
class OrganizationService:
|
||||||
|
def __init__(self, db: AsyncSession) -> None:
|
||||||
|
self.db = db
|
||||||
|
self.audit = AuditService(db)
|
||||||
|
|
||||||
|
async def create_headquarters(
|
||||||
|
self, data: HeadquartersCreate, actor: User, ip: str | None = None
|
||||||
|
) -> Headquarters:
|
||||||
|
if await self.db.get(Company, actor.company_id) is None:
|
||||||
|
raise NotFoundError("Company not found")
|
||||||
|
|
||||||
|
hq = Headquarters(
|
||||||
|
company_id=actor.company_id,
|
||||||
|
code=data.code.upper(),
|
||||||
|
name=data.name,
|
||||||
|
district=data.district,
|
||||||
|
state=data.state,
|
||||||
|
)
|
||||||
|
self.db.add(hq)
|
||||||
|
try:
|
||||||
|
await self.db.flush()
|
||||||
|
except IntegrityError as exc:
|
||||||
|
await self.db.rollback()
|
||||||
|
raise ConflictError(
|
||||||
|
"A headquarters with this code already exists", {"code": data.code}
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
await self.audit.log(
|
||||||
|
actor_user_id=actor.id,
|
||||||
|
entity_type=EntityType.HEADQUARTERS,
|
||||||
|
entity_id=hq.id,
|
||||||
|
action=AuditAction.CREATE,
|
||||||
|
after={"code": hq.code, "name": hq.name},
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
|
await self.db.commit()
|
||||||
|
return hq
|
||||||
|
|
||||||
|
async def list_headquarters(self, actor: User) -> list[Headquarters]:
|
||||||
|
allowed = await visible_hq_ids(self.db, actor)
|
||||||
|
stmt = select(Headquarters).where(Headquarters.company_id == actor.company_id)
|
||||||
|
if allowed is not None:
|
||||||
|
stmt = stmt.where(Headquarters.id.in_(allowed or [None]))
|
||||||
|
return list((await self.db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
|
async def list_area_manager_mappings(self, actor: User) -> list[AMHeadquarters]:
|
||||||
|
"""Current (open) Area Manager to headquarters mappings, for display."""
|
||||||
|
stmt = (
|
||||||
|
select(AMHeadquarters)
|
||||||
|
.join(Headquarters, Headquarters.id == AMHeadquarters.headquarters_id)
|
||||||
|
.where(
|
||||||
|
Headquarters.company_id == actor.company_id,
|
||||||
|
AMHeadquarters.effective_to.is_(None),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return list((await self.db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
|
async def set_area_manager_headquarters(
|
||||||
|
self,
|
||||||
|
am_user_id: uuid.UUID,
|
||||||
|
headquarters_ids: list[uuid.UUID],
|
||||||
|
effective_from: date | None,
|
||||||
|
actor: User,
|
||||||
|
ip: str | None = None,
|
||||||
|
) -> list[AMHeadquarters]:
|
||||||
|
"""Make `headquarters_ids` exactly the set of headquarters this AM manages.
|
||||||
|
|
||||||
|
Headquarters missing from the list are released, new ones are added. If a new
|
||||||
|
headquarters already has another AM, that mapping is closed first (one active AM
|
||||||
|
per headquarters stays true). An AM may manage any number of headquarters.
|
||||||
|
"""
|
||||||
|
manager = await self.db.get(User, am_user_id)
|
||||||
|
if manager is None or manager.company_id != actor.company_id:
|
||||||
|
raise NotFoundError("User not found")
|
||||||
|
if manager.role != Role.AM:
|
||||||
|
raise ValidationError(
|
||||||
|
"Only a user with the AM role can manage a headquarters",
|
||||||
|
{"user_role": manager.role.value},
|
||||||
|
)
|
||||||
|
|
||||||
|
wanted = set(headquarters_ids)
|
||||||
|
if wanted:
|
||||||
|
found = set(
|
||||||
|
(
|
||||||
|
await self.db.execute(
|
||||||
|
select(Headquarters.id).where(
|
||||||
|
Headquarters.id.in_(wanted),
|
||||||
|
Headquarters.company_id == actor.company_id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
).scalars()
|
||||||
|
)
|
||||||
|
if found != wanted:
|
||||||
|
raise NotFoundError("Headquarters not found")
|
||||||
|
|
||||||
|
start = effective_from or date.today()
|
||||||
|
mine = {
|
||||||
|
row.headquarters_id: row
|
||||||
|
for row in (
|
||||||
|
await self.db.execute(
|
||||||
|
select(AMHeadquarters).where(
|
||||||
|
AMHeadquarters.area_manager_user_id == am_user_id,
|
||||||
|
AMHeadquarters.effective_to.is_(None),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
).scalars()
|
||||||
|
}
|
||||||
|
|
||||||
|
released = set(mine) - wanted
|
||||||
|
added = wanted - set(mine)
|
||||||
|
for hq_id in released:
|
||||||
|
mine[hq_id].effective_to = start
|
||||||
|
|
||||||
|
if added:
|
||||||
|
for row in (
|
||||||
|
await self.db.execute(
|
||||||
|
select(AMHeadquarters).where(
|
||||||
|
AMHeadquarters.headquarters_id.in_(added),
|
||||||
|
AMHeadquarters.effective_to.is_(None),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
).scalars():
|
||||||
|
row.effective_to = start
|
||||||
|
await self.db.flush()
|
||||||
|
|
||||||
|
for hq_id in added:
|
||||||
|
self.db.add(
|
||||||
|
AMHeadquarters(
|
||||||
|
area_manager_user_id=am_user_id,
|
||||||
|
headquarters_id=hq_id,
|
||||||
|
effective_from=start,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
if added or released:
|
||||||
|
await self.audit.log(
|
||||||
|
actor_user_id=actor.id,
|
||||||
|
entity_type=EntityType.USER,
|
||||||
|
entity_id=am_user_id,
|
||||||
|
action=AuditAction.ASSIGN,
|
||||||
|
before={"headquarters_ids": sorted(str(h) for h in mine)},
|
||||||
|
after={"headquarters_ids": sorted(str(h) for h in wanted)},
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
|
await self.db.commit()
|
||||||
|
return await self.list_area_manager_mappings_for(am_user_id)
|
||||||
|
|
||||||
|
async def list_area_manager_mappings_for(self, am_user_id: uuid.UUID) -> list[AMHeadquarters]:
|
||||||
|
stmt = select(AMHeadquarters).where(
|
||||||
|
AMHeadquarters.area_manager_user_id == am_user_id,
|
||||||
|
AMHeadquarters.effective_to.is_(None),
|
||||||
|
)
|
||||||
|
return list((await self.db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
|
async def assign_area_manager(
|
||||||
|
self,
|
||||||
|
headquarters_id: uuid.UUID,
|
||||||
|
am_user_id: uuid.UUID,
|
||||||
|
effective_from: date | None,
|
||||||
|
actor: User,
|
||||||
|
ip: str | None = None,
|
||||||
|
) -> AMHeadquarters:
|
||||||
|
"""Assign an AM to an HQ, closing any existing active mapping first.
|
||||||
|
|
||||||
|
The partial unique index `uq_active_am_per_hq` is the real guarantee that only
|
||||||
|
one Area Manager is active per headquarters at a time.
|
||||||
|
"""
|
||||||
|
hq = await self.db.get(Headquarters, headquarters_id)
|
||||||
|
if hq is None:
|
||||||
|
raise NotFoundError("Headquarters not found")
|
||||||
|
|
||||||
|
manager = await self.db.get(User, am_user_id)
|
||||||
|
if manager is None:
|
||||||
|
raise NotFoundError("User not found")
|
||||||
|
if manager.role != Role.AM:
|
||||||
|
raise ValidationError(
|
||||||
|
"Only a user with the AM role can manage a headquarters",
|
||||||
|
{"user_role": manager.role.value},
|
||||||
|
)
|
||||||
|
|
||||||
|
start = effective_from or date.today()
|
||||||
|
|
||||||
|
existing = (
|
||||||
|
await self.db.execute(
|
||||||
|
select(AMHeadquarters).where(
|
||||||
|
AMHeadquarters.headquarters_id == headquarters_id,
|
||||||
|
AMHeadquarters.effective_to.is_(None),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
for row in existing:
|
||||||
|
if row.area_manager_user_id == am_user_id:
|
||||||
|
return row
|
||||||
|
row.effective_to = start
|
||||||
|
await self.db.flush()
|
||||||
|
|
||||||
|
mapping = AMHeadquarters(
|
||||||
|
area_manager_user_id=am_user_id,
|
||||||
|
headquarters_id=headquarters_id,
|
||||||
|
effective_from=start,
|
||||||
|
)
|
||||||
|
self.db.add(mapping)
|
||||||
|
await self.audit.log(
|
||||||
|
actor_user_id=actor.id,
|
||||||
|
entity_type=EntityType.HEADQUARTERS,
|
||||||
|
entity_id=headquarters_id,
|
||||||
|
action=AuditAction.ASSIGN,
|
||||||
|
after={"area_manager_user_id": str(am_user_id), "effective_from": start.isoformat()},
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
|
await self.db.commit()
|
||||||
|
return mapping
|
||||||
@@ -0,0 +1,453 @@
|
|||||||
|
"""View models for the company-form PDFs (tour plan, fare chart, sales & stock, ...).
|
||||||
|
|
||||||
|
Pure Python — no WeasyPrint, no database — so every form's layout data can be unit
|
||||||
|
tested anywhere. ``build_form_context`` turns the stored rows of one CSV table into
|
||||||
|
the context its template under ``templates/forms/`` renders.
|
||||||
|
|
||||||
|
Each form here is a copy of the company's printed form: the same title, the same
|
||||||
|
column headings in the same order, the same column proportions and the same number of
|
||||||
|
ruled lines. Stored rows fill those lines from the top; the rest stay blank for
|
||||||
|
handwriting, and rows beyond the printed length simply continue on the next page.
|
||||||
|
The templates own the look; this module owns *what* each form shows.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
DATE_FIELDS = {"report_date", "date_of_visit"}
|
||||||
|
APPROVAL_FORMS = {"standard_tour_plan", "tour_plan", "fare_chart"}
|
||||||
|
SERIAL = "#" # pseudo-field: the running "Sl.No." column
|
||||||
|
_ALIGN = {"left": "l", "center": "c", "right": "r"}
|
||||||
|
|
||||||
|
Row = dict[str, object]
|
||||||
|
Meta = tuple[str, str] | None # (printed label, column) — None leaves the slot empty
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Col:
|
||||||
|
header: str
|
||||||
|
field: str
|
||||||
|
width: float # percent of the table
|
||||||
|
align: str = "left"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class FormSpec:
|
||||||
|
template: str
|
||||||
|
title: str
|
||||||
|
meta: tuple[tuple[Meta, Meta], ...]
|
||||||
|
columns: tuple[Col, ...] = ()
|
||||||
|
min_rows: int = 25
|
||||||
|
serial_field: str | None = None
|
||||||
|
serial_dot: bool = False # "1." (tour plan, fare chart) instead of "1"
|
||||||
|
table_width: float = 100 # percent of the printed width
|
||||||
|
full_letterhead: bool = True # address, web and phone lines under the company name
|
||||||
|
|
||||||
|
|
||||||
|
def _serial(header: str, width: float) -> Col:
|
||||||
|
return Col(header, SERIAL, width, "center")
|
||||||
|
|
||||||
|
|
||||||
|
_NAME_HQ = ((("NAME:", "name"), None), (("HEADQUARTER:", "headquarter"), None))
|
||||||
|
_NAME_HQ_DATE_MONTH = (
|
||||||
|
(("NAME:", "name"), ("Date:", "report_date")),
|
||||||
|
(("HEADQUARTER:", "headquarter"), ("Month:", "month")),
|
||||||
|
)
|
||||||
|
_NAME_HQ_MONTH = (
|
||||||
|
(("NAME :", "name"), None),
|
||||||
|
(("HEADQUARTER:", "headquarter"), ("MONTH:", "month")),
|
||||||
|
)
|
||||||
|
|
||||||
|
FORMS: dict[str, FormSpec] = {
|
||||||
|
"standard_tour_plan": FormSpec(
|
||||||
|
"standard_tour_plan",
|
||||||
|
"STANDARD TOUR PLAN",
|
||||||
|
_NAME_HQ,
|
||||||
|
(_serial("Sl.No.", 11.4), Col("PLACE", "place", 88.6, "center")),
|
||||||
|
serial_field="serial_no",
|
||||||
|
serial_dot=True,
|
||||||
|
table_width=83,
|
||||||
|
),
|
||||||
|
"tour_plan": FormSpec(
|
||||||
|
"tour_plan",
|
||||||
|
"TOUR PLAN",
|
||||||
|
_NAME_HQ,
|
||||||
|
(
|
||||||
|
_serial("Sl.No.", 9.4),
|
||||||
|
Col("Date", "report_date", 11.9, "center"),
|
||||||
|
Col("From", "from_location", 25.0),
|
||||||
|
Col("To", "to_location", 23.2),
|
||||||
|
Col("POB", "pob", 15.3, "center"),
|
||||||
|
Col("Stockiest Visit", "stockiest_visit", 15.2, "center"),
|
||||||
|
),
|
||||||
|
serial_field="serial_no",
|
||||||
|
serial_dot=True,
|
||||||
|
),
|
||||||
|
"fare_chart": FormSpec(
|
||||||
|
"fare_chart",
|
||||||
|
"FARE CHART",
|
||||||
|
_NAME_HQ,
|
||||||
|
(
|
||||||
|
_serial("Sl.No.", 9.4),
|
||||||
|
Col("Date", "report_date", 15.3, "center"),
|
||||||
|
Col("From", "from_location", 30.2),
|
||||||
|
Col("To", "to_location", 27.1),
|
||||||
|
Col("Kilometers (KM)", "kilometers_km", 17.6, "center"),
|
||||||
|
),
|
||||||
|
serial_field="serial_no",
|
||||||
|
serial_dot=True,
|
||||||
|
),
|
||||||
|
"area_covered": FormSpec(
|
||||||
|
"area_covered",
|
||||||
|
"AREA COVERED",
|
||||||
|
_NAME_HQ_MONTH,
|
||||||
|
(
|
||||||
|
Col("SALE STATUS", "sale_status", 34.0),
|
||||||
|
Col("AREA TO COVER", "area_to_cover", 24.3),
|
||||||
|
Col("SALE OBJECTIVE", "sale_objective", 20.8),
|
||||||
|
Col("STATUS", "status", 20.9, "center"),
|
||||||
|
),
|
||||||
|
min_rows=28,
|
||||||
|
full_letterhead=False,
|
||||||
|
),
|
||||||
|
"core_dr_call_conversion": FormSpec(
|
||||||
|
"core_dr_call_conversion",
|
||||||
|
"CORE Dr. CALL & CONVERSION",
|
||||||
|
_NAME_HQ_MONTH,
|
||||||
|
(
|
||||||
|
Col("DOCTOR NAME", "doctor_name", 38.3),
|
||||||
|
Col("DATE OF VISIT", "date_of_visit", 14.7, "center"),
|
||||||
|
Col("PRODUCT TARGETED", "product_targeted", 30.4),
|
||||||
|
Col("STATUS", "status", 16.6, "center"),
|
||||||
|
),
|
||||||
|
min_rows=28,
|
||||||
|
full_letterhead=False,
|
||||||
|
),
|
||||||
|
"field_activity_report": FormSpec(
|
||||||
|
"field_activity_report",
|
||||||
|
"FIELD ACTIVITY REPORT",
|
||||||
|
_NAME_HQ_MONTH,
|
||||||
|
(
|
||||||
|
Col("DATE", "report_date", 14.5, "center"),
|
||||||
|
Col("STATION WORKED", "station_worked", 36.6),
|
||||||
|
Col("NO. OF DOCTORS CALLED", "no_of_doctors_called", 19.8, "center"),
|
||||||
|
Col("NO. OF CHEMISTS/PDS CALLED", "no_of_chemists_pds_called", 29.1, "center"),
|
||||||
|
),
|
||||||
|
min_rows=25,
|
||||||
|
table_width=83,
|
||||||
|
full_letterhead=False,
|
||||||
|
),
|
||||||
|
"sales_and_stock_statement": FormSpec(
|
||||||
|
"sales_and_stock_statement",
|
||||||
|
"SALES AND STOCK STATEMENT",
|
||||||
|
_NAME_HQ_DATE_MONTH,
|
||||||
|
(
|
||||||
|
_serial("Sl.No.", 7.0),
|
||||||
|
Col("Name of the Product", "product_name", 22.6),
|
||||||
|
Col("Opening", "opening", 15.0, "center"),
|
||||||
|
Col("Receipt", "receipt", 14.7, "center"),
|
||||||
|
Col("Sale", "sale", 15.0, "center"),
|
||||||
|
Col("Closing", "closing", 12.2, "center"),
|
||||||
|
Col("Value in PTS", "value_in_pts", 13.5, "center"),
|
||||||
|
),
|
||||||
|
min_rows=26,
|
||||||
|
serial_field="serial_no",
|
||||||
|
),
|
||||||
|
"sales_projection": FormSpec(
|
||||||
|
"sales_projection",
|
||||||
|
"SALES PROJECTION",
|
||||||
|
_NAME_HQ_MONTH,
|
||||||
|
(
|
||||||
|
_serial("SL. No.", 7.1),
|
||||||
|
Col("NAME OF THE PRODUCT", "product_name", 22.7),
|
||||||
|
Col("PTS", "pts", 10.7, "center"),
|
||||||
|
Col("SEC. QTY", "secondary_qty", 9.1, "center"),
|
||||||
|
Col("VALUE", "value", 9.6, "center"),
|
||||||
|
Col("CLOSING", "closing", 11.6, "center"),
|
||||||
|
Col("SEC. VALUE", "secondary_value", 10.1, "center"),
|
||||||
|
Col("AUG. SALES", "aug_sales", 9.6, "center"),
|
||||||
|
Col("VALUE", "value_2", 9.5, "center"),
|
||||||
|
),
|
||||||
|
min_rows=26,
|
||||||
|
serial_field="serial_no",
|
||||||
|
full_letterhead=False,
|
||||||
|
),
|
||||||
|
"daily_call_report_csv": FormSpec(
|
||||||
|
"daily_call_report_csv",
|
||||||
|
"DAILY CALL REPORT",
|
||||||
|
_NAME_HQ_DATE_MONTH,
|
||||||
|
),
|
||||||
|
"weekly_report": FormSpec(
|
||||||
|
"weekly_report",
|
||||||
|
"Weekly Report",
|
||||||
|
(
|
||||||
|
(("EMPLOYEE NAME:", "employee_name"), ("DATE :", "report_date")),
|
||||||
|
(("HEADQUARTER :", "headquarter"), ("MONTH:", "month")),
|
||||||
|
),
|
||||||
|
full_letterhead=False,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
# Daily Call Report: a doctor-call table and a chemist-visit table share one stored row.
|
||||||
|
_DOCTOR_COLS = (
|
||||||
|
_serial("SR. NO.", 8.6),
|
||||||
|
Col("DR. NAME", "doctor_name", 27.5),
|
||||||
|
Col("QUALIFICATION", "qualification", 14.9),
|
||||||
|
Col("PRODUCT PROMOTE", "product_promote", 14.6),
|
||||||
|
Col("PRODUCT SAMPLE", "product_sample", 18.2),
|
||||||
|
Col("REMARKS", "remarks", 16.2),
|
||||||
|
)
|
||||||
|
_DOCTOR_FIELDS = tuple(c.field for c in _DOCTOR_COLS if c.field != SERIAL)
|
||||||
|
_CHEMIST_COLS = (
|
||||||
|
_serial("SR. NO.", 10.2),
|
||||||
|
Col("NAME OF THE CHEMIST", "chemist_name", 32.8),
|
||||||
|
Col("POB", "pob", 57.0),
|
||||||
|
)
|
||||||
|
_CHEMIST_FIELDS = tuple(c.field for c in _CHEMIST_COLS if c.field != SERIAL)
|
||||||
|
|
||||||
|
_WEEKLY_SUMMARY = (
|
||||||
|
("No. of Days Worked", "no_of_days_worked"),
|
||||||
|
("No. of Doctor Called", "no_of_doctor_called"),
|
||||||
|
("No. of Chemist Called", "no_of_chemist_called"),
|
||||||
|
("POB Booked", "pob_booked"),
|
||||||
|
("Secondary Sales", "secondary_sales"),
|
||||||
|
("POB Objective", "pob_objective"),
|
||||||
|
("Secondary Objective", "secondary_objective"),
|
||||||
|
)
|
||||||
|
_WEEKLY_SCHEMES = (
|
||||||
|
("Product – Offer Scheme Booked", "product_offer_scheme_booked"),
|
||||||
|
("Product – Offer Scheme Objective", "product_offer_scheme_objective"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------- helpers
|
||||||
|
def _text(value: object) -> str:
|
||||||
|
return "" if value is None else str(value).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _display(field: str, value: object) -> str:
|
||||||
|
"""Stored text as printed; ISO dates become dd/mm/yyyy, anything else is untouched."""
|
||||||
|
text = _text(value)
|
||||||
|
if field in DATE_FIELDS and text:
|
||||||
|
try:
|
||||||
|
return date.fromisoformat(text[:10]).strftime("%d/%m/%Y")
|
||||||
|
except ValueError:
|
||||||
|
return text
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def _distinct(rows: list[Row], field: str) -> str:
|
||||||
|
"""Every different stored value of a column, in order — never just the first row's."""
|
||||||
|
seen: list[str] = []
|
||||||
|
for row in rows:
|
||||||
|
value = _display(field, row.get(field))
|
||||||
|
if value and value not in seen:
|
||||||
|
seen.append(value)
|
||||||
|
return ", ".join(seen)
|
||||||
|
|
||||||
|
|
||||||
|
def _has(row: Row, fields: tuple[str, ...]) -> bool:
|
||||||
|
return any(_text(row.get(field)) for field in fields)
|
||||||
|
|
||||||
|
|
||||||
|
def _grid(
|
||||||
|
cols: tuple[Col, ...],
|
||||||
|
rows: list[Row],
|
||||||
|
*,
|
||||||
|
min_rows: int,
|
||||||
|
serial_field: str | None = None,
|
||||||
|
serial_dot: bool = False,
|
||||||
|
table_width: float = 100,
|
||||||
|
) -> dict[str, object]:
|
||||||
|
"""One printed table: header, stored rows, then blank ruled lines up to ``min_rows``."""
|
||||||
|
suffix = "." if serial_dot else ""
|
||||||
|
body = []
|
||||||
|
next_serial = 1
|
||||||
|
for index in range(max(min_rows, len(rows))):
|
||||||
|
row = rows[index] if index < len(rows) else None
|
||||||
|
cells: list[str] = []
|
||||||
|
for col in cols:
|
||||||
|
if col.field == SERIAL:
|
||||||
|
# A stored number wins (single-row PDFs keep their real serial); blank
|
||||||
|
# lines carry on counting from the last printed number.
|
||||||
|
number = _text(row.get(serial_field)) if row and serial_field else ""
|
||||||
|
number = number or str(next_serial)
|
||||||
|
next_serial = int(number) + 1 if number.isdigit() else next_serial + 1
|
||||||
|
cells.append(number + suffix)
|
||||||
|
else:
|
||||||
|
cells.append(_display(col.field, row.get(col.field)) if row else "")
|
||||||
|
body.append({"cells": cells, "blank": row is None})
|
||||||
|
return {
|
||||||
|
"headers": [c.header for c in cols],
|
||||||
|
"aligns": [_ALIGN[c.align] for c in cols],
|
||||||
|
"widths": [f"{c.width}%" for c in cols],
|
||||||
|
"rows": body,
|
||||||
|
"width": f"{table_width}%",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _meta_rows(
|
||||||
|
meta: tuple[tuple[Meta, Meta], ...], rows: list[Row]
|
||||||
|
) -> list[list[tuple[str, str] | None]]:
|
||||||
|
return [
|
||||||
|
[(slot[0], _distinct(rows, slot[1])) if slot else None for slot in pair] for pair in meta
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def approval_signature_line(
|
||||||
|
table_name: str, approval_status: str | None = None, am_name: str | None = None
|
||||||
|
) -> str:
|
||||||
|
if table_name not in APPROVAL_FORMS:
|
||||||
|
return ""
|
||||||
|
approved = (approval_status or "pending").lower() == "approved"
|
||||||
|
name = (am_name or "").strip()
|
||||||
|
return f"APPROVAL SIGNATURE: {name}" if approved and name else "APPROVAL SIGNATURE: PENDING"
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------- builder
|
||||||
|
def build_form_context(
|
||||||
|
table_name: str,
|
||||||
|
label: str,
|
||||||
|
columns: tuple[str, ...],
|
||||||
|
rows: list[Row],
|
||||||
|
approval_status: str | None = None,
|
||||||
|
am_name: str | None = None,
|
||||||
|
approved_at: str | None = None,
|
||||||
|
) -> dict[str, object]:
|
||||||
|
"""Everything a form template needs, for all stored rows of ``table_name``."""
|
||||||
|
spec = FORMS.get(table_name)
|
||||||
|
grids: dict[str, dict[str, object]] = {}
|
||||||
|
extra: dict[str, object] = {}
|
||||||
|
|
||||||
|
if spec is None: # unknown table: print every stored column generically
|
||||||
|
identity = {"name", "employee_name", "headquarter", "month"}
|
||||||
|
spec = FormSpec(
|
||||||
|
"generic",
|
||||||
|
label.upper(),
|
||||||
|
tuple(
|
||||||
|
(
|
||||||
|
(f"{c.replace('_', ' ').upper()}:", c) if c in identity else None,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
for c in columns
|
||||||
|
if c in identity
|
||||||
|
),
|
||||||
|
)
|
||||||
|
cols = tuple(
|
||||||
|
Col(c.replace("_", " ").upper(), c, 100 / max(1, len(columns)))
|
||||||
|
for c in columns
|
||||||
|
if c not in {"id", "source_row_number"}
|
||||||
|
)
|
||||||
|
grids["main"] = _grid(cols, rows, min_rows=0)
|
||||||
|
elif spec.template == "daily_call_report_csv":
|
||||||
|
doctors = [r for r in rows if _has(r, _DOCTOR_FIELDS)]
|
||||||
|
chemists = [r for r in rows if _has(r, _CHEMIST_FIELDS)]
|
||||||
|
grids["doctors"] = _grid(_DOCTOR_COLS, doctors, min_rows=10, serial_field="doctor_sr_no")
|
||||||
|
grids["chemists"] = _grid(
|
||||||
|
_CHEMIST_COLS, chemists, min_rows=5, serial_field="chemist_sr_no", table_width=84
|
||||||
|
)
|
||||||
|
extra["stockist_visit"] = _distinct(rows, "stockist_visit")
|
||||||
|
extra["order_value"] = _distinct(rows, "order_value")
|
||||||
|
elif spec.template == "weekly_report":
|
||||||
|
extra["reports"] = [
|
||||||
|
{
|
||||||
|
"meta_rows": _meta_rows(spec.meta, [r]),
|
||||||
|
"summary": [(lbl, _text(r.get(f))) for lbl, f in _WEEKLY_SUMMARY],
|
||||||
|
"schemes": [(lbl, _text(r.get(f))) for lbl, f in _WEEKLY_SCHEMES],
|
||||||
|
}
|
||||||
|
for r in rows or [{}]
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
grids["main"] = _grid(
|
||||||
|
spec.columns,
|
||||||
|
rows,
|
||||||
|
min_rows=spec.min_rows,
|
||||||
|
serial_field=spec.serial_field,
|
||||||
|
serial_dot=spec.serial_dot,
|
||||||
|
table_width=spec.table_width,
|
||||||
|
)
|
||||||
|
if table_name == "field_activity_report":
|
||||||
|
extra["doctor_call_avg"] = _distinct(rows, "doctor_call_avg")
|
||||||
|
extra["chemist_call_avg"] = _distinct(rows, "chemist_call_avg")
|
||||||
|
|
||||||
|
approval = None
|
||||||
|
if table_name in APPROVAL_FORMS:
|
||||||
|
line = approval_signature_line(table_name, approval_status, am_name)
|
||||||
|
value = line.split(": ", 1)[1]
|
||||||
|
approval = {
|
||||||
|
"line": line, "label": "APPROVAL SIGNATURE:", "value": value,
|
||||||
|
"when": approved_at if value != "PENDING" and approved_at else "",
|
||||||
|
# Once approved, the MR's own signature line carries their name too.
|
||||||
|
"mr_name": _distinct(rows, "name") if value != "PENDING" else "",
|
||||||
|
}
|
||||||
|
|
||||||
|
if spec.template == "weekly_report":
|
||||||
|
meta: list[list[tuple[str, str] | None]] = []
|
||||||
|
else:
|
||||||
|
meta = _meta_rows(spec.meta, rows)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"template": spec.template,
|
||||||
|
"label": label,
|
||||||
|
"title": spec.title,
|
||||||
|
"full_letterhead": spec.full_letterhead,
|
||||||
|
"title_suffix": next((s[1] for pair in meta for s in pair if s and s[1]), ""),
|
||||||
|
"meta_rows": meta,
|
||||||
|
"grids": grids,
|
||||||
|
"approval": approval,
|
||||||
|
**extra,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------- the filed Daily Call Report
|
||||||
|
_OUTCOME_NOTE = {"NOT_AVAILABLE": "Not available", "RESCHEDULED": "Rescheduled"}
|
||||||
|
|
||||||
|
|
||||||
|
def _doctor_remarks(call) -> str:
|
||||||
|
"""The remarks column; a visit that did not happen is flagged, since the form has no outcome column."""
|
||||||
|
note = _OUTCOME_NOTE.get(getattr(call.call_outcome, "value", str(call.call_outcome)), "")
|
||||||
|
return ". ".join(part for part in (note, (call.remarks or "").strip()) if part)
|
||||||
|
|
||||||
|
|
||||||
|
def build_dcr_context(dcr, doctor_calls, chemist_calls, approval: dict[str, str] | None = None) -> dict[str, object]:
|
||||||
|
"""The approved Daily Call Report, laid out exactly like the printed company form.
|
||||||
|
|
||||||
|
Same template family, headings, column widths and number of ruled lines as the
|
||||||
|
``daily_call_report_csv`` company form: 10 doctor lines and 5 chemist lines, filled
|
||||||
|
from the top in visit order; more visits simply continue on the next page. The only
|
||||||
|
additions are the signatures: the MR's name, and (once approved) the Area Manager's
|
||||||
|
approval signature with its date and time.
|
||||||
|
"""
|
||||||
|
doctors = [
|
||||||
|
{
|
||||||
|
"doctor_name": c.doctor.name,
|
||||||
|
"qualification": c.doctor.qualification or "",
|
||||||
|
"product_promote": c.product_promote or "",
|
||||||
|
"product_sample": c.product_sample or "",
|
||||||
|
"remarks": _doctor_remarks(c),
|
||||||
|
}
|
||||||
|
for c in doctor_calls
|
||||||
|
]
|
||||||
|
chemists = [{"chemist_name": c.chemist.name, "pob": c.pob or ""} for c in chemist_calls]
|
||||||
|
meta = [
|
||||||
|
[("NAME:", dcr.mr.full_name), ("Date:", dcr.report_date.strftime("%d/%m/%Y"))],
|
||||||
|
[("HEADQUARTER:", dcr.headquarters.name), ("Month:", dcr.report_date.strftime("%B %Y"))],
|
||||||
|
]
|
||||||
|
return {
|
||||||
|
"template": "dcr",
|
||||||
|
"label": "Daily Call Report",
|
||||||
|
"title": "DAILY CALL REPORT",
|
||||||
|
"title_suffix": f"{dcr.mr.full_name} — {dcr.report_date.strftime('%d/%m/%Y')}",
|
||||||
|
"full_letterhead": True,
|
||||||
|
"meta_rows": meta,
|
||||||
|
"grids": {
|
||||||
|
"doctors": _grid(_DOCTOR_COLS, doctors, min_rows=10),
|
||||||
|
"chemists": _grid(_CHEMIST_COLS, chemists, min_rows=5, table_width=84),
|
||||||
|
},
|
||||||
|
"stockist_visit": dcr.stockist_visit or "",
|
||||||
|
"order_value": dcr.order_value or "",
|
||||||
|
"mr_signed": f"{dcr.mr.full_name} ({dcr.mr.employee_code})",
|
||||||
|
"approval": approval, # {"name": ..., "at": "dd/mm/yyyy HH:MM"} or None
|
||||||
|
}
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
"""Approved-report and company-form PDF generation.
|
||||||
|
|
||||||
|
WeasyPrint (BSD-3-Clause) renders Jinja2 HTML templates, so every layout is plain
|
||||||
|
HTML/CSS that anyone on the team can edit. The approved Daily Call Report and every
|
||||||
|
company form (tour plan, fare chart, sales & stock, ...) extend
|
||||||
|
``templates/forms/_form_base.html``, because each is a copy of the company's printed form;
|
||||||
|
each has its own template (``dcr.html`` or one under ``templates/forms/``). What a form
|
||||||
|
shows is decided in ``app.pdf.forms``.
|
||||||
|
|
||||||
|
WeasyPrint needs system libraries (Pango, HarfBuzz) and DejaVu fonts. They are pinned in
|
||||||
|
the Dockerfile. If they are genuinely absent (a bare dev machine, CI without the apt
|
||||||
|
step) the service falls back to a minimal built-in writer so the workflow still
|
||||||
|
completes and tests still run — and logs a loud warning, because that fallback
|
||||||
|
produces a plain-text PDF, not the designed layout. Production must have WeasyPrint;
|
||||||
|
``pdf_engine_ready()`` lets the health check and startup log say so.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import uuid
|
||||||
|
from html.parser import HTMLParser
|
||||||
|
from pathlib import Path
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
from jinja2 import Environment, FileSystemLoader, select_autoescape
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.audit.service import AuditService
|
||||||
|
from app.common.enums import AuditAction, EntityType
|
||||||
|
from app.config.settings import settings
|
||||||
|
from app.pdf.forms import approval_signature_line, build_dcr_context, build_form_context
|
||||||
|
from app.reports.models import DailyCallReport
|
||||||
|
from app.users.models import User
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_TEMPLATE_DIR = Path(__file__).parent / "templates"
|
||||||
|
_env = Environment(
|
||||||
|
loader=FileSystemLoader(_TEMPLATE_DIR),
|
||||||
|
autoescape=select_autoescape(["html"]),
|
||||||
|
)
|
||||||
|
_env.globals.update(
|
||||||
|
company_name=settings.PDF_COMPANY_NAME,
|
||||||
|
company_address=settings.PDF_COMPANY_ADDRESS,
|
||||||
|
company_website=settings.PDF_COMPANY_WEBSITE,
|
||||||
|
company_email=settings.PDF_COMPANY_EMAIL,
|
||||||
|
company_phone=settings.PDF_COMPANY_PHONE,
|
||||||
|
)
|
||||||
|
|
||||||
|
try: # pragma: no cover - depends on system libraries
|
||||||
|
from weasyprint import HTML as _WeasyHTML
|
||||||
|
|
||||||
|
WEASYPRINT_AVAILABLE = True
|
||||||
|
except Exception: # noqa: BLE001 - ImportError or OSError from missing libs
|
||||||
|
_WeasyHTML = None
|
||||||
|
WEASYPRINT_AVAILABLE = False
|
||||||
|
|
||||||
|
|
||||||
|
def pdf_engine_ready() -> bool:
|
||||||
|
"""True when the designed (WeasyPrint) layout can be rendered."""
|
||||||
|
return WEASYPRINT_AVAILABLE
|
||||||
|
|
||||||
|
|
||||||
|
def _minimal_pdf(text: str) -> bytes:
|
||||||
|
"""Fallback renderer: a valid single-page PDF containing plain text.
|
||||||
|
|
||||||
|
Used ONLY when WeasyPrint's system libraries are unavailable. It exists so the
|
||||||
|
approval workflow and its tests never depend on native libraries being present.
|
||||||
|
"""
|
||||||
|
lines = [ln[:95] for ln in text.splitlines()][:52]
|
||||||
|
content = ["BT", "/F1 9 Tf", "40 780 Td", "11 TL"]
|
||||||
|
for line in lines:
|
||||||
|
escaped = line.replace("\\", r"\\").replace("(", r"\(").replace(")", r"\)")
|
||||||
|
content.append(f"({escaped}) Tj T*")
|
||||||
|
content.append("ET")
|
||||||
|
stream = "\n".join(content).encode("latin-1", "replace")
|
||||||
|
|
||||||
|
objects = [
|
||||||
|
b"<< /Type /Catalog /Pages 2 0 R >>",
|
||||||
|
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
||||||
|
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] "
|
||||||
|
b"/Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
|
||||||
|
b"<< /Length " + str(len(stream)).encode() + b" >>\nstream\n" + stream + b"\nendstream",
|
||||||
|
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
|
||||||
|
]
|
||||||
|
|
||||||
|
out = bytearray(b"%PDF-1.4\n")
|
||||||
|
offsets = [0]
|
||||||
|
for i, body in enumerate(objects, start=1):
|
||||||
|
offsets.append(len(out))
|
||||||
|
out += f"{i} 0 obj\n".encode() + body + b"\nendobj\n"
|
||||||
|
|
||||||
|
xref_pos = len(out)
|
||||||
|
out += f"xref\n0 {len(objects) + 1}\n".encode()
|
||||||
|
out += b"0000000000 65535 f \n"
|
||||||
|
for off in offsets[1:]:
|
||||||
|
out += f"{off:010d} 00000 n \n".encode()
|
||||||
|
out += (
|
||||||
|
f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\n"
|
||||||
|
f"startxref\n{xref_pos}\n%%EOF\n"
|
||||||
|
).encode()
|
||||||
|
return bytes(out)
|
||||||
|
|
||||||
|
|
||||||
|
class _TextExtractor(HTMLParser):
|
||||||
|
"""Flattens a rendered form to lines of text for the plain-text fallback."""
|
||||||
|
|
||||||
|
_SKIP = {"style", "title", "script"}
|
||||||
|
_BREAK = {"tr", "div", "h1", "h2", "p", "br", "table"}
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self.parts: list[str] = []
|
||||||
|
self._skipping = 0
|
||||||
|
|
||||||
|
def handle_starttag(self, tag: str, attrs: list) -> None:
|
||||||
|
if tag in self._SKIP:
|
||||||
|
self._skipping += 1
|
||||||
|
|
||||||
|
def handle_endtag(self, tag: str) -> None:
|
||||||
|
if tag in self._SKIP:
|
||||||
|
self._skipping -= 1
|
||||||
|
elif tag in {"td", "th"}:
|
||||||
|
self.parts.append(" | ")
|
||||||
|
elif tag in self._BREAK:
|
||||||
|
self.parts.append("\n")
|
||||||
|
|
||||||
|
def handle_data(self, data: str) -> None:
|
||||||
|
if not self._skipping and data.strip():
|
||||||
|
self.parts.append(" ".join(data.split()) + " ")
|
||||||
|
|
||||||
|
|
||||||
|
def _html_to_text(html: str) -> str:
|
||||||
|
parser = _TextExtractor()
|
||||||
|
parser.feed(html)
|
||||||
|
lines = ("".join(parser.parts)).splitlines()
|
||||||
|
cleaned = (" ".join(line.split()).strip(" |") for line in lines)
|
||||||
|
return "\n".join(line for line in cleaned if line)
|
||||||
|
|
||||||
|
|
||||||
|
def _approval_signature_line(
|
||||||
|
table_name: str,
|
||||||
|
approval_status: str | None = None,
|
||||||
|
am_name: str | None = None,
|
||||||
|
am_role: str = "Area Manager",
|
||||||
|
) -> str:
|
||||||
|
return approval_signature_line(table_name, approval_status, am_name)
|
||||||
|
|
||||||
|
|
||||||
|
def csv_table_pdf_bytes(
|
||||||
|
table_name: str,
|
||||||
|
table_label: str,
|
||||||
|
columns: tuple[str, ...],
|
||||||
|
rows: list[dict[str, object]],
|
||||||
|
approval_status: str | None = None,
|
||||||
|
am_name: str | None = None,
|
||||||
|
am_role: str = "Area Manager",
|
||||||
|
approved_at: str | None = None,
|
||||||
|
) -> bytes:
|
||||||
|
"""Render every stored row of an imported table on its own company-form layout."""
|
||||||
|
context = build_form_context(
|
||||||
|
table_name, table_label, columns, rows, approval_status, am_name, approved_at
|
||||||
|
)
|
||||||
|
html = _env.get_template(f"forms/{context['template']}.html").render(**context)
|
||||||
|
if WEASYPRINT_AVAILABLE:
|
||||||
|
return _WeasyHTML(string=html).write_pdf()
|
||||||
|
|
||||||
|
logger.warning(
|
||||||
|
"WeasyPrint unavailable — using the plain-text fallback renderer for %s. "
|
||||||
|
"Install Pango/HarfBuzz (see Dockerfile) before production use.",
|
||||||
|
table_name,
|
||||||
|
)
|
||||||
|
return _minimal_pdf(_html_to_text(html))
|
||||||
|
|
||||||
|
|
||||||
|
def csv_pdf_bytes(table_label: str, row: dict[str, object]) -> bytes:
|
||||||
|
"""Render one imported table row for the row-level PDF action."""
|
||||||
|
columns = tuple(key for key in row if key not in {"id", "source_row_number"})
|
||||||
|
return csv_table_pdf_bytes("row", table_label, columns, [row])
|
||||||
|
|
||||||
|
|
||||||
|
class PDFService:
|
||||||
|
def __init__(self, db: AsyncSession) -> None:
|
||||||
|
self.db = db
|
||||||
|
self.audit = AuditService(db)
|
||||||
|
|
||||||
|
async def _approval(self, dcr: DailyCallReport) -> dict[str, str] | None:
|
||||||
|
"""Who approved the report and when, from the audit trail — the signature cannot be typed in."""
|
||||||
|
if dcr.approved_at is None:
|
||||||
|
return None
|
||||||
|
approvals = [h for h in await self.audit.approval_history_for(dcr.id) if h.action == AuditAction.APPROVE]
|
||||||
|
if not approvals:
|
||||||
|
return None
|
||||||
|
approver = await self.db.get(User, approvals[-1].actor_user_id)
|
||||||
|
if approver is None:
|
||||||
|
return None
|
||||||
|
when = dcr.approved_at.astimezone(ZoneInfo(settings.APP_TIMEZONE)).strftime("%d/%m/%Y %H:%M")
|
||||||
|
return {"name": approver.full_name, "at": when}
|
||||||
|
|
||||||
|
async def _context(self, dcr: DailyCallReport) -> dict:
|
||||||
|
return build_dcr_context(
|
||||||
|
dcr,
|
||||||
|
sorted(dcr.doctor_calls, key=lambda c: c.visit_time),
|
||||||
|
sorted(dcr.chemist_calls, key=lambda c: c.visit_time),
|
||||||
|
await self._approval(dcr),
|
||||||
|
)
|
||||||
|
|
||||||
|
async def render_bytes(self, dcr: DailyCallReport) -> bytes:
|
||||||
|
"""The report as a PDF in the current layout — a pure function of the stored report."""
|
||||||
|
context = await self._context(dcr)
|
||||||
|
html = _env.get_template("dcr.html").render(**context)
|
||||||
|
|
||||||
|
if WEASYPRINT_AVAILABLE:
|
||||||
|
return _WeasyHTML(string=html).write_pdf()
|
||||||
|
|
||||||
|
logger.warning(
|
||||||
|
"WeasyPrint unavailable — using the plain-text fallback renderer. "
|
||||||
|
"Install Pango/cairo (see Dockerfile) before production use."
|
||||||
|
)
|
||||||
|
return _minimal_pdf(_env.get_template("dcr.txt").render(**context))
|
||||||
|
|
||||||
|
async def render_and_store(self, dcr: DailyCallReport, approver: User) -> str:
|
||||||
|
pdf_bytes = await self.render_bytes(dcr)
|
||||||
|
|
||||||
|
directory = Path(settings.PDF_STORAGE_PATH) / str(dcr.report_date.year)
|
||||||
|
directory.mkdir(parents=True, exist_ok=True)
|
||||||
|
path = directory / f"DCR-{dcr.report_date.isoformat()}-{dcr.id}.pdf"
|
||||||
|
path.write_bytes(pdf_bytes)
|
||||||
|
|
||||||
|
await self.audit.log(
|
||||||
|
actor_user_id=approver.id,
|
||||||
|
entity_type=EntityType.DCR,
|
||||||
|
entity_id=dcr.id,
|
||||||
|
action=AuditAction.UPDATE,
|
||||||
|
after={"pdf_generated": str(path)},
|
||||||
|
)
|
||||||
|
return str(path)
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
{# The approved Daily Call Report — a copy of the company's printed form, filled in. #}
|
||||||
|
{% extends "forms/_form_base.html" %}
|
||||||
|
{% from "forms/_macros.html" import grid %}
|
||||||
|
|
||||||
|
{% block form_styles %}
|
||||||
|
h1.title { margin: 6mm 0 3mm; font-size: 13pt; text-decoration: none; letter-spacing: .3px; }
|
||||||
|
table.grid th { height: 7.5mm; font-size: 9pt; }
|
||||||
|
table.grid td { font-size: 10pt; }
|
||||||
|
h2.section { margin: 6mm 0 1.5mm; text-align: center; font-size: 11pt; }
|
||||||
|
.visit { margin: 6mm 0 0 14mm; font-size: 10.5pt; line-height: 1.7; }
|
||||||
|
.visit b { display: inline-block; min-width: 30mm; }
|
||||||
|
table.dcr-sign { width: 100%; margin-top: 12mm; border-collapse: collapse; page-break-inside: avoid; }
|
||||||
|
table.dcr-sign td { vertical-align: top; padding: 0; }
|
||||||
|
table.dcr-sign td.mr { width: 52%; padding-left: 14mm; }
|
||||||
|
.sign-label { font-size: 10.5pt; font-weight: bold; }
|
||||||
|
.signed { display: inline-block; min-width: 62mm; margin-top: 4mm; padding-bottom: 1mm; border-bottom: .7pt solid #000; font-family: "Liberation Serif", "Times New Roman", serif; font-style: italic; font-size: 12pt; }
|
||||||
|
.signed-when { margin-top: 1.2mm; font-size: 8.5pt; }
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block form %}
|
||||||
|
{{ grid(grids.doctors, left=True) }}
|
||||||
|
<h2 class="section">CHEMIST VISIT</h2>
|
||||||
|
{{ grid(grids.chemists, left=True) }}
|
||||||
|
<div class="visit">
|
||||||
|
<div><b>STOCKIST VISIT :</b> {{ stockist_visit }}</div>
|
||||||
|
<div><b>ORDER :</b> {{ order_value }}</div>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block signature %}
|
||||||
|
<table class="dcr-sign">
|
||||||
|
<tr>
|
||||||
|
<td class="mr">
|
||||||
|
<div class="sign-label">MR Signature</div>
|
||||||
|
<div class="signed">{{ mr_signed }}</div>
|
||||||
|
</td>
|
||||||
|
<td class="am">
|
||||||
|
{% if approval %}
|
||||||
|
<div class="sign-label">APPROVAL SIGNATURE:</div>
|
||||||
|
<div class="signed">{{ approval.name }}</div>
|
||||||
|
<div class="signed-when">Area Manager · {{ approval.at }}</div>
|
||||||
|
{% endif %}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{{ company_name }}
|
||||||
|
{{ company_address }}
|
||||||
|
Website: {{ company_website }} E-Mail: {{ company_email }} PHONE: {{ company_phone }}
|
||||||
|
DAILY CALL REPORT
|
||||||
|
{% for pair in meta_rows %}{% for slot in pair %}{% if slot %}{{ slot[0] }} {{ slot[1] }} {% endif %}{% endfor %}
|
||||||
|
{% endfor %}
|
||||||
|
SR.NO | DR. NAME | QUALIFICATION | PRODUCT PROMOTE | PRODUCT SAMPLE | REMARKS
|
||||||
|
{% for r in grids.doctors.rows %}{{ r.cells | join(' | ') }}
|
||||||
|
{% endfor %}
|
||||||
|
CHEMIST VISIT
|
||||||
|
SR.NO | NAME OF THE CHEMIST | POB
|
||||||
|
{% for r in grids.chemists.rows %}{{ r.cells | join(' | ') }}
|
||||||
|
{% endfor %}
|
||||||
|
STOCKIST VISIT : {{ stockist_visit }}
|
||||||
|
ORDER : {{ order_value }}
|
||||||
|
|
||||||
|
MR Signature: {{ mr_signed }}
|
||||||
|
{% if approval %}APPROVAL SIGNATURE: {{ approval.name }} ({{ approval.at }})
|
||||||
|
{% endif %}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
{# Base for every company form. Standalone on purpose: the forms copy the printed
|
||||||
|
originals and must not inherit the DCR report's look (base.html). #}
|
||||||
|
{% from "forms/_macros.html" import letterhead, meta_block, grid, sign_right, sign_approval %}
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>{{ label }}{% if title_suffix %} — {{ title_suffix }}{% endif %}</title>
|
||||||
|
<style>
|
||||||
|
@page {
|
||||||
|
size: A4;
|
||||||
|
margin: 12mm 16mm;
|
||||||
|
{% block page_box %}{% endblock %}
|
||||||
|
}
|
||||||
|
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
font-family: Carlito, Calibri, "Liberation Sans", "DejaVu Sans", sans-serif;
|
||||||
|
font-size: 11.5pt;
|
||||||
|
line-height: 1.2;
|
||||||
|
color: #000;
|
||||||
|
}
|
||||||
|
|
||||||
|
.company { text-align: center; }
|
||||||
|
.company .name {
|
||||||
|
font-family: "Liberation Sans", Arial, Helvetica, "DejaVu Sans", sans-serif;
|
||||||
|
font-size: 21pt;
|
||||||
|
font-weight: bold;
|
||||||
|
line-height: 1.15;
|
||||||
|
color: #000;
|
||||||
|
}
|
||||||
|
.company .line { font-size: 11pt; line-height: 1.35; }
|
||||||
|
|
||||||
|
h1.title {
|
||||||
|
margin: 7mm 0 4mm;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 18pt;
|
||||||
|
line-height: 1.1;
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
table.meta { width: 100%; border-collapse: collapse; margin: 0 0 2.5mm; }
|
||||||
|
table.meta td { padding: .6mm 0; font-size: 12pt; vertical-align: top; }
|
||||||
|
table.meta td.ml { width: 62%; padding-left: 1.5mm; }
|
||||||
|
|
||||||
|
table.grid { border-collapse: collapse; table-layout: fixed; margin: 0 auto; }
|
||||||
|
table.grid.left { margin: 0; }
|
||||||
|
table.grid th, table.grid td { border: .7pt solid #000; padding: 0 1.6mm; }
|
||||||
|
table.grid th {
|
||||||
|
background: #fff;
|
||||||
|
height: 9mm;
|
||||||
|
font-size: 11.5pt;
|
||||||
|
line-height: 1.15;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
table.grid td {
|
||||||
|
height: 6.4mm;
|
||||||
|
font-size: 11.5pt;
|
||||||
|
line-height: 1.15;
|
||||||
|
vertical-align: middle;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
table.grid tr { page-break-inside: avoid; }
|
||||||
|
th.l, td.l { text-align: left; }
|
||||||
|
th.c, td.c { text-align: center; }
|
||||||
|
th.r, td.r { text-align: right; }
|
||||||
|
|
||||||
|
/* A fill-in line: the printed underscore rule, holding the value when there is one. */
|
||||||
|
.ln {
|
||||||
|
display: inline-block;
|
||||||
|
min-width: 42mm;
|
||||||
|
height: 4.4mm;
|
||||||
|
border-bottom: .7pt solid #000;
|
||||||
|
text-align: center;
|
||||||
|
font-weight: normal;
|
||||||
|
vertical-align: bottom;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sign-right {
|
||||||
|
margin: 16mm 0 0 68%;
|
||||||
|
font-size: 10.5pt;
|
||||||
|
font-weight: bold;
|
||||||
|
page-break-inside: avoid;
|
||||||
|
}
|
||||||
|
table.sign-approval { width: 100%; margin-top: 14mm; border-collapse: collapse; page-break-inside: avoid; }
|
||||||
|
table.sign-approval td { padding: 0; font-size: 8.5pt; font-weight: bold; }
|
||||||
|
table.sign-approval td:first-child { width: 56%; }
|
||||||
|
table.sign-approval .sign-when { margin: 1.5mm 0 0 0; font-size: 8pt; font-weight: normal; text-align: right; }
|
||||||
|
table.sign-approval .ln { font-size: 9pt; }
|
||||||
|
|
||||||
|
{% block form_styles %}{% endblock %}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
{% block body %}
|
||||||
|
{{ letterhead(full_letterhead) }}
|
||||||
|
<h1 class="title">{{ title }}</h1>
|
||||||
|
{{ meta_block(meta_rows) }}
|
||||||
|
{% block form %}{% endblock %}
|
||||||
|
{% block signature %}{{ sign_right() }}{% endblock %}
|
||||||
|
{% endblock %}
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
{# Building blocks shared by the company-form PDFs. Each mirrors a part of the printed form. #}
|
||||||
|
|
||||||
|
{% macro letterhead(full) %}
|
||||||
|
<div class="company">
|
||||||
|
<div class="name">{{ company_name }}</div>
|
||||||
|
{% if full %}
|
||||||
|
<div class="line">{{ company_address }}</div>
|
||||||
|
<div class="line">Website: {{ company_website }} E-Mail:{{ company_email }}</div>
|
||||||
|
<div class="line">PHONE: {{ company_phone }}</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endmacro %}
|
||||||
|
|
||||||
|
{# NAME / HEADQUARTER on the left, DATE / MONTH on the right — empty slots stay empty. #}
|
||||||
|
{% macro meta_block(rows) %}
|
||||||
|
{% if rows %}
|
||||||
|
<table class="meta">
|
||||||
|
{% for pair in rows %}
|
||||||
|
<tr>
|
||||||
|
{% for slot in pair %}
|
||||||
|
<td class="{{ 'ml' if loop.first else 'mr' }}">{% if slot %}<b>{{ slot[0] }}</b> {{ slot[1] }}{% endif %}</td>
|
||||||
|
{% endfor %}
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</table>
|
||||||
|
{% endif %}
|
||||||
|
{% endmacro %}
|
||||||
|
|
||||||
|
{% macro grid(g, left=False) %}
|
||||||
|
<table class="grid{% if left %} left{% endif %}" style="width:{{ g.width }}">
|
||||||
|
<colgroup>{% for w in g.widths %}<col style="width:{{ w }}">{% endfor %}</colgroup>
|
||||||
|
<thead>
|
||||||
|
<tr>{% for h in g.headers %}<th>{{ h }}</th>{% endfor %}</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for r in g.rows %}
|
||||||
|
<tr>{% for c in r.cells %}<td class="{{ g.aligns[loop.index0] }}">{{ c }}</td>{% endfor %}</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
{% endmacro %}
|
||||||
|
|
||||||
|
{# "SIGNATURE" alone, low on the right — the sales / activity / call-report forms. #}
|
||||||
|
{% macro sign_right(text="SIGNATURE") %}
|
||||||
|
<div class="sign-right">{{ text }}</div>
|
||||||
|
{% endmacro %}
|
||||||
|
|
||||||
|
{# Tour plan, standard tour plan and fare chart: MR signature plus the AM approval. #}
|
||||||
|
{% macro sign_approval(approval) %}
|
||||||
|
<table class="sign-approval">
|
||||||
|
<tr>
|
||||||
|
<td>SIGNATURE: <span class="ln">{{ approval.mr_name }}</span></td>
|
||||||
|
<td>{{ approval.label }} <span class="ln">{{ approval.value }}</span>{% if approval.when %}<div class="sign-when">{{ approval.when }}</div>{% endif %}</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
{% endmacro %}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{% extends "forms/_form_base.html" %}
|
||||||
|
{% from "forms/_macros.html" import grid %}
|
||||||
|
|
||||||
|
{% block form_styles %}
|
||||||
|
h1.title { margin: 0 0 5mm; font-size: 10pt; }
|
||||||
|
table.grid th { font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; font-size: 10pt; }
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block form %}
|
||||||
|
{{ grid(grids.main) }}
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{% extends "forms/_form_base.html" %}
|
||||||
|
{% from "forms/_macros.html" import grid %}
|
||||||
|
|
||||||
|
{% block form_styles %}
|
||||||
|
h1.title { margin: 0 0 5mm; font-size: 10pt; }
|
||||||
|
table.grid th { font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; font-size: 10pt; }
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block form %}
|
||||||
|
{{ grid(grids.main) }}
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{% extends "forms/_form_base.html" %}
|
||||||
|
{% from "forms/_macros.html" import grid %}
|
||||||
|
|
||||||
|
{% block form_styles %}
|
||||||
|
h1.title { margin: 6mm 0 3mm; font-size: 13pt; text-decoration: none; letter-spacing: .3px; }
|
||||||
|
table.grid th { height: 7.5mm; font-size: 9pt; }
|
||||||
|
table.grid td { font-size: 10pt; }
|
||||||
|
h2.section { margin: 6mm 0 1.5mm; text-align: center; font-size: 11pt; }
|
||||||
|
.visit { margin: 6mm 0 0 14mm; font-size: 10.5pt; line-height: 1.7; }
|
||||||
|
.visit b { display: inline-block; min-width: 30mm; }
|
||||||
|
.sign-left { margin: 12mm 0 0 14mm; font-size: 10.5pt; font-weight: bold; }
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block form %}
|
||||||
|
{{ grid(grids.doctors, left=True) }}
|
||||||
|
<h2 class="section">CHEMIST VISIT</h2>
|
||||||
|
{{ grid(grids.chemists, left=True) }}
|
||||||
|
<div class="visit">
|
||||||
|
<div><b>STOCKIST VISIT :</b> {{ stockist_visit }}</div>
|
||||||
|
<div><b>ORDER :</b> {{ order_value }}</div>
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block signature %}<div class="sign-left">MR Signature</div>{% endblock %}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{% extends "forms/_form_base.html" %}
|
||||||
|
{% from "forms/_macros.html" import grid, sign_approval %}
|
||||||
|
|
||||||
|
{% block form %}
|
||||||
|
{{ grid(grids.main) }}
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block signature %}{{ sign_approval(approval) }}{% endblock %}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
{% extends "forms/_form_base.html" %}
|
||||||
|
{% from "forms/_macros.html" import grid, sign_right %}
|
||||||
|
|
||||||
|
{% block form_styles %}
|
||||||
|
h1.title { margin: 0 0 5mm; font-size: 13pt; }
|
||||||
|
table.grid th { font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; font-size: 10pt; }
|
||||||
|
table.avg { width: 100%; margin-top: 7mm; border-collapse: collapse; }
|
||||||
|
table.avg td { padding: 0; font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; font-size: 9.5pt; font-weight: bold; white-space: nowrap; }
|
||||||
|
table.avg .ln { min-width: 44mm; }
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block form %}
|
||||||
|
{{ grid(grids.main) }}
|
||||||
|
<table class="avg">
|
||||||
|
<tr>
|
||||||
|
<td>DOCTOR CALL AVG <span class="ln">{{ doctor_call_avg }}</span></td>
|
||||||
|
<td>CHEMIST CALL AVG. <span class="ln">{{ chemist_call_avg }}</span></td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
{% extends "forms/_form_base.html" %}
|
||||||
|
{% from "forms/_macros.html" import grid %}
|
||||||
|
|
||||||
|
{% block form %}
|
||||||
|
{{ grid(grids.main) }}
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{% extends "forms/_form_base.html" %}
|
||||||
|
{% from "forms/_macros.html" import grid %}
|
||||||
|
|
||||||
|
{% block form_styles %}
|
||||||
|
h1.title { font-size: 14pt; margin: 6mm 0 3mm; }
|
||||||
|
table.grid th { font-size: 11pt; }
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block form %}
|
||||||
|
{{ grid(grids.main) }}
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
{% extends "forms/_form_base.html" %}
|
||||||
|
{% from "forms/_macros.html" import grid %}
|
||||||
|
|
||||||
|
{# Arial throughout, title tucked directly under the company name — as printed. #}
|
||||||
|
{% block form_styles %}
|
||||||
|
.company .name { font-size: 20pt; }
|
||||||
|
h1.title {
|
||||||
|
margin: 0 0 4mm;
|
||||||
|
font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif;
|
||||||
|
font-size: 14pt;
|
||||||
|
}
|
||||||
|
table.grid th, table.grid td { font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; }
|
||||||
|
table.grid th { height: 10mm; font-size: 9.5pt; }
|
||||||
|
table.grid td { font-size: 9.5pt; }
|
||||||
|
table.grid td:nth-child(2) { font-weight: bold; }
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block form %}
|
||||||
|
{{ grid(grids.main) }}
|
||||||
|
{% endblock %}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{% extends "forms/_form_base.html" %}
|
||||||
|
{% from "forms/_macros.html" import grid, sign_approval %}
|
||||||
|
|
||||||
|
{% block form %}
|
||||||
|
{{ grid(grids.main, left=True) }}
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block signature %}{{ sign_approval(approval) }}{% endblock %}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user