Production
This commit is contained in:
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
# Container entrypoint: bring the schema up to date, then hand over to the server.
|
||||
# Migrations are idempotent, so restarting the container is always safe. Data import
|
||||
# scripts (which replace table contents) are never run from here.
|
||||
set -eu
|
||||
|
||||
if [ "${RUN_MIGRATIONS:-1}" = "1" ]; then
|
||||
attempt=1
|
||||
until alembic upgrade head; do
|
||||
if [ "$attempt" -ge 15 ]; then
|
||||
echo "entrypoint: database migration failed after $attempt attempts" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "entrypoint: database not ready (attempt $attempt), retrying in 3s" >&2
|
||||
attempt=$((attempt + 1))
|
||||
sleep 3
|
||||
done
|
||||
fi
|
||||
|
||||
exec "$@"
|
||||
@@ -0,0 +1,46 @@
|
||||
-- SEC-3: make the audit log genuinely append-only.
|
||||
--
|
||||
-- The application must be able to INSERT into audit_log and SELECT from it, and
|
||||
-- nothing else. Enforcing this at the database role level means that even an
|
||||
-- application bug — or an attacker with the application's credentials — cannot
|
||||
-- rewrite history.
|
||||
--
|
||||
-- Run this ONCE after the first migration, as a superuser:
|
||||
-- psql -U postgres -d pharma -f scripts/harden_audit.sql
|
||||
--
|
||||
-- Assumes the application connects as the role `pharma_app`. Create that role
|
||||
-- separately from the migration role: migrations need DDL rights, the running
|
||||
-- application does not.
|
||||
|
||||
-- 1. The application role (create it if it does not exist).
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'pharma_app') THEN
|
||||
CREATE ROLE pharma_app LOGIN PASSWORD 'change-me-before-production';
|
||||
END IF;
|
||||
END
|
||||
$$;
|
||||
|
||||
-- 2. Normal rights on every other table.
|
||||
GRANT USAGE ON SCHEMA public TO pharma_app;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO pharma_app;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO pharma_app;
|
||||
|
||||
-- 3. audit_log is the exception: insert and read only.
|
||||
REVOKE UPDATE, DELETE, TRUNCATE ON audit_log FROM pharma_app;
|
||||
|
||||
-- 4. Same policy for tables created by future migrations.
|
||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO pharma_app;
|
||||
|
||||
-- 5. Belt and braces: a trigger, so the rule survives a mis-granted privilege.
|
||||
CREATE OR REPLACE FUNCTION audit_log_is_append_only() RETURNS trigger AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'audit_log is append-only: % is not permitted', TG_OP;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
DROP TRIGGER IF EXISTS trg_audit_log_append_only ON audit_log;
|
||||
CREATE TRIGGER trg_audit_log_append_only
|
||||
BEFORE UPDATE OR DELETE ON audit_log
|
||||
FOR EACH ROW EXECUTE FUNCTION audit_log_is_append_only();
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Import eligible root-level CSV files into their form tables.
|
||||
|
||||
Usage: python -m scripts.import_csv_data [--only-empty]
|
||||
|
||||
Without a flag every form table is REPLACED by its CSV. ``--only-empty`` is the safe
|
||||
mode for a database that already holds work: a table that has any rows is left
|
||||
untouched, and only empty tables are loaded (e.g. the product lists).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import csv
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.database.session import AsyncSessionLocal
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
EXCLUDED_FILES = {"stock.csv"}
|
||||
CSV_TABLES = {
|
||||
"Weekly_Report.csv": ("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.csv": ("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.csv": ("fare_chart", ["name", "headquarter", "serial_no", "report_date", "from_location", "to_location", "kilometers_km"]),
|
||||
"Daily_Call_Report.csv": ("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.csv": ("core_dr_call_conversion", ["name", "headquarter", "month", "doctor_name", "date_of_visit", "product_targeted", "status"]),
|
||||
"AREA_COVERED.csv": ("area_covered", ["name", "headquarter", "month", "sale_status", "area_to_cover", "sale_objective", "status"]),
|
||||
"Sales_and_Stock_Statement.csv": ("sales_and_stock_statement", ["name", "headquarter", "report_date", "month", "serial_no", "product_name", "opening", "receipt", "sale", "closing", "value_in_pts"]),
|
||||
"TOUR_PLAN.csv": ("tour_plan", ["name", "headquarter", "serial_no", "report_date", "from_location", "to_location", "pob", "stockiest_visit"]),
|
||||
"STANDARD_TOUR_PLAN.csv": ("standard_tour_plan", ["name", "headquarter", "serial_no", "place"]),
|
||||
"sales_projection.csv": ("sales_projection", ["name", "headquarter", "report_date", "month", "serial_no", "product_name", "pts", "secondary_qty", "value", "closing", "secondary_value", "aug_sales", "value_2"]),
|
||||
}
|
||||
SERIAL_COLUMNS = {"serial_no", "doctor_sr_no", "chemist_sr_no"}
|
||||
|
||||
|
||||
def read_rows(path: Path, columns: list[str]) -> list[tuple[int, dict[str, str]]]:
|
||||
with path.open(newline="", encoding="utf-8-sig") as file:
|
||||
reader = csv.reader(file)
|
||||
next(reader, None)
|
||||
rows: list[tuple[int, dict[str, str]]] = []
|
||||
for row in reader:
|
||||
data = {
|
||||
column: (row[index] if index < len(row) else "").strip()
|
||||
for index, column in enumerate(columns)
|
||||
}
|
||||
if any(value for column, value in data.items() if column not in SERIAL_COLUMNS):
|
||||
rows.append((len(rows) + 1, data))
|
||||
return rows
|
||||
|
||||
|
||||
async def apply_sales_projection_account(db) -> None:
|
||||
await db.execute(
|
||||
text(
|
||||
'''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' '''
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
async def import_csv_data(only_empty: bool = False) -> None:
|
||||
csv_files = sorted(path for path in ROOT.glob("*.csv") if path.name not in EXCLUDED_FILES)
|
||||
async with AsyncSessionLocal() as db:
|
||||
imported_rows = 0
|
||||
for path in csv_files:
|
||||
table_name, columns = CSV_TABLES[path.name]
|
||||
if only_empty:
|
||||
count = await db.execute(text(f'SELECT COUNT(*) FROM "{table_name}"'))
|
||||
existing = count.scalar_one()
|
||||
if existing:
|
||||
print(f"{table_name}: skipped, already has {existing} rows")
|
||||
continue
|
||||
else:
|
||||
await db.execute(text(f'DELETE FROM "{table_name}"'))
|
||||
source_columns = columns[4:] if table_name == "sales_projection" else columns
|
||||
rows = read_rows(path, source_columns)
|
||||
if table_name == "sales_projection":
|
||||
rows = [
|
||||
(row_number, {"name": "", "headquarter": "", "report_date": "", "month": "", **data})
|
||||
for row_number, data in rows
|
||||
]
|
||||
if rows:
|
||||
column_names = ", ".join(f'"{column}"' for column in columns)
|
||||
parameters = ", ".join(f":{column}" for column in columns)
|
||||
statement = text(
|
||||
f'INSERT INTO "{table_name}" '
|
||||
f'(id, source_row_number, {column_names}) '
|
||||
f'VALUES (:id, :source_row_number, {parameters})'
|
||||
)
|
||||
await db.execute(
|
||||
statement,
|
||||
[
|
||||
{"id": uuid.uuid4(), "source_row_number": row_number, **data}
|
||||
for row_number, data in rows
|
||||
],
|
||||
)
|
||||
imported_rows += len(rows)
|
||||
print(f"{table_name}: {len(rows)} rows")
|
||||
if table_name == "sales_projection":
|
||||
await apply_sales_projection_account(db)
|
||||
await db.commit()
|
||||
print(f"Imported {imported_rows} rows from {len(csv_files)} CSV files.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument(
|
||||
"--only-empty",
|
||||
action="store_true",
|
||||
help="load only tables that have no rows; never delete existing data",
|
||||
)
|
||||
asyncio.run(import_csv_data(parser.parse_args().only_empty))
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Creates the scratch database the test suite uses.
|
||||
-- Runs automatically on first `docker compose up` via docker-entrypoint-initdb.d.
|
||||
CREATE DATABASE pharma_test OWNER pharma;
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
"""Seed the minimum MVP system described in report §10.2.
|
||||
|
||||
Creates: 1 company, 1 headquarters, 1 GM, 1 AM, 1 MR, 1 System Admin,
|
||||
15 doctors (3 flagged as core) and 5 chemists, all assigned to the MR.
|
||||
|
||||
python -m scripts.seed
|
||||
|
||||
Idempotent: running it twice does not duplicate anything.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
import uuid
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.auth.security import hash_password
|
||||
from app.chemists.models import Chemist, ChemistAssignment
|
||||
from app.common.enums import Role
|
||||
from app.database.session import AsyncSessionLocal
|
||||
from app.doctors.models import Doctor, DoctorAssignment
|
||||
from app.organization.models import AMHeadquarters, Company, Headquarters
|
||||
from app.users.models import User
|
||||
|
||||
DEMO_PASSWORD = "ChangeMe123!"
|
||||
|
||||
SPECIALITIES = [
|
||||
"General Medicine", "Paediatrics", "Orthopaedics", "Cardiology", "Dermatology",
|
||||
]
|
||||
|
||||
SURNAMES = [
|
||||
"Sen", "Patra", "Rout", "Mishra", "Jena", "Sahoo", "Panda", "Das",
|
||||
"Nayak", "Pradhan", "Behera", "Swain", "Barik", "Mohapatra", "Tripathy",
|
||||
]
|
||||
|
||||
|
||||
async def seed() -> None:
|
||||
async with AsyncSessionLocal() as db:
|
||||
existing = (
|
||||
await db.execute(select(Company).where(Company.name == "Acme Pharma Pvt Ltd"))
|
||||
).scalar_one_or_none()
|
||||
if existing:
|
||||
print("Seed data already present — nothing to do.")
|
||||
return
|
||||
|
||||
company = Company(id=uuid.uuid4(), name="Acme Pharma Pvt Ltd", address="Bhubaneswar")
|
||||
db.add(company)
|
||||
await db.flush()
|
||||
|
||||
hq = Headquarters(
|
||||
id=uuid.uuid4(), company_id=company.id, code="BBSR",
|
||||
name="Bhubaneswar", district="Khordha", state="Odisha",
|
||||
)
|
||||
db.add(hq)
|
||||
await db.flush()
|
||||
|
||||
def make(role: Role, name: str, code: str, hq_id=None) -> User:
|
||||
return User(
|
||||
id=uuid.uuid4(), company_id=company.id,
|
||||
email=f"{code.lower()}@acmepharma.in",
|
||||
password_hash=hash_password(DEMO_PASSWORD),
|
||||
full_name=name, employee_code=code, role=role, headquarters_id=hq_id,
|
||||
)
|
||||
|
||||
admin = make(Role.ADMIN, "System Administrator", "ADM001")
|
||||
gm = make(Role.GM, "Anita Mohanty", "GM001")
|
||||
am = make(Role.AM, "Suresh Behera", "AM001")
|
||||
mr = make(Role.MR, "Ravi Das", "MR001", hq.id)
|
||||
db.add_all([admin, gm, am, mr])
|
||||
await db.flush()
|
||||
|
||||
db.add(
|
||||
AMHeadquarters(
|
||||
area_manager_user_id=am.id, headquarters_id=hq.id, effective_from=date.today()
|
||||
)
|
||||
)
|
||||
|
||||
for i in range(15):
|
||||
doctor = Doctor(
|
||||
id=uuid.uuid4(), headquarters_id=hq.id,
|
||||
name=f"Dr {SURNAMES[i]}",
|
||||
speciality=SPECIALITIES[i % len(SPECIALITIES)],
|
||||
qualification="MBBS, MD" if i % 3 == 0 else "MBBS",
|
||||
clinic_address=f"Clinic {i + 1}, Unit {i % 9 + 1}, Bhubaneswar",
|
||||
is_core_doctor=i < 3,
|
||||
)
|
||||
db.add(doctor)
|
||||
await db.flush()
|
||||
db.add(
|
||||
DoctorAssignment(
|
||||
doctor_id=doctor.id, mr_user_id=mr.id, effective_from=date.today()
|
||||
)
|
||||
)
|
||||
|
||||
for i in range(5):
|
||||
chemist = Chemist(
|
||||
id=uuid.uuid4(), headquarters_id=hq.id,
|
||||
name=f"{['Konark','Utkal','Kalinga','Sriya','Jagannath'][i]} Medical Stores",
|
||||
shop_address=f"Shop {i + 1}, Market Building, Bhubaneswar",
|
||||
contact_number=f"9{i}0000000{i}",
|
||||
)
|
||||
db.add(chemist)
|
||||
await db.flush()
|
||||
db.add(
|
||||
ChemistAssignment(
|
||||
chemist_id=chemist.id, mr_user_id=mr.id, effective_from=date.today()
|
||||
)
|
||||
)
|
||||
|
||||
await db.commit()
|
||||
|
||||
print("Seeded the minimum MVP system.\n")
|
||||
print(f" Password for every account: {DEMO_PASSWORD}\n")
|
||||
print(" System Admin adm001@acmepharma.in")
|
||||
print(" General Mgr gm001@acmepharma.in")
|
||||
print(" Area Manager am001@acmepharma.in")
|
||||
print(" MR mr001@acmepharma.in")
|
||||
print("\n 1 headquarters (BBSR), 15 doctors (3 core), 5 chemists — all assigned to MR001.")
|
||||
print("\n CHANGE THESE PASSWORDS before any real use.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(seed())
|
||||
except KeyboardInterrupt:
|
||||
sys.exit(1)
|
||||
Executable
+72
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env bash
|
||||
# Prepare .env for a Docker deployment on this machine. Safe to re-run.
|
||||
#
|
||||
# ./scripts/setup.sh # production values
|
||||
# DOMAIN=app.example.com ./scripts/setup.sh
|
||||
#
|
||||
# What it does:
|
||||
# * creates .env from .env.example if it does not exist
|
||||
# * generates SECRET_KEY when it is missing or a placeholder
|
||||
# * sets ENVIRONMENT=production and DEBUG=false
|
||||
# * generates POSTGRES_PASSWORD only for a brand-new database (an existing database
|
||||
# volume keeps the password it was created with, so it is never changed here)
|
||||
# * picks free host ports: if 80/443 are taken by another service (a host nginx, another
|
||||
# Caddy, ...), it serves plain HTTP on the first free ports from 2000/2443 instead
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
ENV_FILE=.env
|
||||
PROJECT=${COMPOSE_PROJECT_NAME:-$(basename "$PWD" | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9_-')}
|
||||
|
||||
[ -f "$ENV_FILE" ] || { cp .env.example "$ENV_FILE"; echo "created $ENV_FILE from .env.example"; }
|
||||
|
||||
get() { grep -E "^$1=" "$ENV_FILE" | tail -1 | cut -d= -f2- || true; }
|
||||
set_kv() {
|
||||
if grep -qE "^$1=" "$ENV_FILE"; then sed -i -E "s|^$1=.*|$1=$2|" "$ENV_FILE"
|
||||
else printf '%s=%s\n' "$1" "$2" >> "$ENV_FILE"; fi
|
||||
}
|
||||
random() { python3 -c "import secrets;print(secrets.token_urlsafe($1))" 2>/dev/null \
|
||||
|| openssl rand -base64 "$1" | tr -d '\n=+/'; }
|
||||
|
||||
# Ports this project's own containers already publish are not "busy" for us.
|
||||
own_ports=$(docker ps --filter "label=com.docker.compose.project=$PROJECT" \
|
||||
--format '{{.Ports}}' 2>/dev/null | grep -oE ':[0-9]+->' | tr -d ':>-' || true)
|
||||
busy() {
|
||||
echo "$own_ports" | grep -qx "$1" && return 1
|
||||
(exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null
|
||||
}
|
||||
free_from() { local p=$1; while busy "$p"; do p=$((p + 1)); done; echo "$p"; }
|
||||
|
||||
# --- secrets ---------------------------------------------------------------
|
||||
key=$(get SECRET_KEY)
|
||||
case "$key" in ""|replace-with*|change-me*) key="" ;; esac
|
||||
if [ "${#key}" -lt 32 ]; then set_kv SECRET_KEY "$(random 64)"; echo "generated SECRET_KEY"; fi
|
||||
|
||||
set_kv ENVIRONMENT production
|
||||
set_kv DEBUG false
|
||||
|
||||
if docker volume inspect "${PROJECT}_pgdata" >/dev/null 2>&1; then
|
||||
echo "database volume exists: keeping POSTGRES_PASSWORD"
|
||||
case "$(get POSTGRES_PASSWORD)" in pharma|replace-with*|"")
|
||||
echo "WARNING: the database still uses a weak/default password; rotate it (see README)." ;;
|
||||
esac
|
||||
else
|
||||
case "$(get POSTGRES_PASSWORD)" in pharma|replace-with*|"")
|
||||
set_kv POSTGRES_PASSWORD "$(random 24)"; echo "generated POSTGRES_PASSWORD" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# --- ports -----------------------------------------------------------------
|
||||
[ -n "${DOMAIN:-}" ] && set_kv DOMAIN "$DOMAIN"
|
||||
domain=$(get DOMAIN); domain=${domain:-localhost}
|
||||
if [ "$domain" != ":80" ] && ! busy 80 && ! busy 443; then
|
||||
set_kv HTTP_PORT 80; set_kv HTTPS_PORT 443
|
||||
echo "ports 80/443 are free: Caddy serves $domain directly"
|
||||
else
|
||||
http=$(free_from "$(get HTTP_PORT | grep -vx 80 || echo 2000)")
|
||||
https=$(free_from "$(get HTTPS_PORT | grep -vx 443 || echo 2443)")
|
||||
set_kv DOMAIN ":80"; set_kv HTTP_PORT "$http"; set_kv HTTPS_PORT "$https"
|
||||
echo "ports 80/443 are in use: Caddy serves plain HTTP on host port $http"
|
||||
echo " -> point your existing reverse proxy at http://127.0.0.1:$http"
|
||||
fi
|
||||
echo "done. Next: docker compose up -d --build"
|
||||
Reference in New Issue
Block a user