--
This commit is contained in:
@@ -11,3 +11,5 @@ storage/
|
|||||||
.coverage
|
.coverage
|
||||||
htmlcov/
|
htmlcov/
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
# Database dumps (docker-compose `backup` service): never committed.
|
||||||
|
backups/
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
"""split the Daily Call Report into a morning plan and an end-of-day report
|
||||||
|
|
||||||
|
An MR now files a PLAN (doctors/chemists to visit, and when) and, once the Area Manager
|
||||||
|
approves it, an ACTUAL end-of-day report of the visits made, with a note for each planned
|
||||||
|
visit that was missed. Existing reports are end-of-day reports with no plan.
|
||||||
|
|
||||||
|
Revision ID: m3c9e5f1b8d0
|
||||||
|
Revises: l2b8d4e0a7c9
|
||||||
|
Create Date: 2026-10-23
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "m3c9e5f1b8d0"
|
||||||
|
down_revision: str | None = "l2b8d4e0a7c9"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column(
|
||||||
|
"daily_call_report",
|
||||||
|
sa.Column(
|
||||||
|
"report_type",
|
||||||
|
sa.Enum("PLAN", "ACTUAL", name="report_type_enum", native_enum=False, length=10),
|
||||||
|
nullable=False,
|
||||||
|
server_default="ACTUAL",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
op.alter_column("daily_call_report", "report_type", server_default=None)
|
||||||
|
op.add_column(
|
||||||
|
"daily_call_report",
|
||||||
|
sa.Column(
|
||||||
|
"plan_id",
|
||||||
|
sa.UUID(),
|
||||||
|
sa.ForeignKey("daily_call_report.id", ondelete="RESTRICT"),
|
||||||
|
nullable=True,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
op.drop_constraint("uq_dcr_mr_date", "daily_call_report", type_="unique")
|
||||||
|
op.create_unique_constraint(
|
||||||
|
"uq_dcr_mr_date_type", "daily_call_report", ["mr_user_id", "report_date", "report_type"]
|
||||||
|
)
|
||||||
|
op.create_unique_constraint("uq_dcr_plan_id", "daily_call_report", ["plan_id"])
|
||||||
|
op.create_check_constraint(
|
||||||
|
"ck_dcr_plan_link", "daily_call_report", "report_type = 'ACTUAL' OR plan_id IS NULL"
|
||||||
|
)
|
||||||
|
|
||||||
|
# A planned visit has no outcome yet.
|
||||||
|
op.alter_column("doctor_call", "call_outcome", nullable=True)
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"missed_visit",
|
||||||
|
sa.Column("id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("dcr_id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("doctor_id", sa.UUID(), nullable=True),
|
||||||
|
sa.Column("chemist_id", sa.UUID(), nullable=True),
|
||||||
|
sa.Column("reason", sa.Text(), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"(doctor_id IS NULL) <> (chemist_id IS NULL)", name="ck_missed_one_target"
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(["dcr_id"], ["daily_call_report.id"], ondelete="CASCADE"),
|
||||||
|
sa.ForeignKeyConstraint(["doctor_id"], ["doctor.id"], ondelete="RESTRICT"),
|
||||||
|
sa.ForeignKeyConstraint(["chemist_id"], ["chemist.id"], ondelete="RESTRICT"),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
sa.UniqueConstraint("dcr_id", "doctor_id", name="uq_missed_dcr_doctor"),
|
||||||
|
sa.UniqueConstraint("dcr_id", "chemist_id", name="uq_missed_dcr_chemist"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("missed_visit")
|
||||||
|
# Planned visits cannot exist without an outcome in the old schema.
|
||||||
|
for table in ("doctor_call", "chemist_call"):
|
||||||
|
op.execute(
|
||||||
|
f"DELETE FROM {table} WHERE dcr_id IN "
|
||||||
|
"(SELECT id FROM daily_call_report WHERE report_type = 'PLAN')"
|
||||||
|
)
|
||||||
|
op.execute("UPDATE daily_call_report SET plan_id = NULL")
|
||||||
|
op.execute("DELETE FROM daily_call_report WHERE report_type = 'PLAN'")
|
||||||
|
op.alter_column("doctor_call", "call_outcome", nullable=False)
|
||||||
|
op.drop_constraint("ck_dcr_plan_link", "daily_call_report", type_="check")
|
||||||
|
op.drop_constraint("uq_dcr_plan_id", "daily_call_report", type_="unique")
|
||||||
|
op.drop_constraint("uq_dcr_mr_date_type", "daily_call_report", type_="unique")
|
||||||
|
op.create_unique_constraint(
|
||||||
|
"uq_dcr_mr_date", "daily_call_report", ["mr_user_id", "report_date"]
|
||||||
|
)
|
||||||
|
op.drop_column("daily_call_report", "plan_id")
|
||||||
|
op.drop_column("daily_call_report", "report_type")
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
"""add an optional date of birth to the doctor master
|
||||||
|
|
||||||
|
Revision ID: n4d0f6b2c9e1
|
||||||
|
Revises: m3c9e5f1b8d0
|
||||||
|
Create Date: 2026-10-24
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "n4d0f6b2c9e1"
|
||||||
|
down_revision: str | None = "m3c9e5f1b8d0"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("doctor", sa.Column("date_of_birth", sa.Date(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_column("doctor", "date_of_birth")
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"""Area Manager's own report (SELF), and several products per doctor visit
|
||||||
|
|
||||||
|
``report_type`` is a plain string column, so SELF needs no schema change. The promoted
|
||||||
|
and sample product columns become text arrays; an existing value becomes a one-item list.
|
||||||
|
|
||||||
|
Revision ID: o5e1a7c3d0f2
|
||||||
|
Revises: n4d0f6b2c9e1
|
||||||
|
Create Date: 2026-10-24
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "o5e1a7c3d0f2"
|
||||||
|
down_revision: str | None = "n4d0f6b2c9e1"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
_COLUMNS = ("product_promote", "product_sample")
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
for column in _COLUMNS:
|
||||||
|
op.execute(
|
||||||
|
f"ALTER TABLE doctor_call ALTER COLUMN {column} TYPE varchar(200)[] USING "
|
||||||
|
f"CASE WHEN btrim(coalesce({column}, '')) = '' THEN '{{}}'::varchar(200)[] "
|
||||||
|
f"ELSE ARRAY[btrim({column})]::varchar(200)[] END"
|
||||||
|
)
|
||||||
|
op.execute(f"ALTER TABLE doctor_call ALTER COLUMN {column} SET DEFAULT '{{}}'")
|
||||||
|
op.execute(f"ALTER TABLE doctor_call ALTER COLUMN {column} SET NOT NULL")
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.execute("DELETE FROM daily_call_report WHERE report_type = 'SELF'")
|
||||||
|
for column in _COLUMNS:
|
||||||
|
op.execute(f"ALTER TABLE doctor_call ALTER COLUMN {column} DROP NOT NULL")
|
||||||
|
op.execute(f"ALTER TABLE doctor_call ALTER COLUMN {column} DROP DEFAULT")
|
||||||
|
op.execute(
|
||||||
|
f"ALTER TABLE doctor_call ALTER COLUMN {column} TYPE varchar(200) USING "
|
||||||
|
f"nullif(left(array_to_string({column}, ', '), 200), '')"
|
||||||
|
)
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""the Expense Statement company form
|
||||||
|
|
||||||
|
One row per day of travel: place of visit, fare, daily allowance, postage, other expenses
|
||||||
|
and business achieved. Like the fare chart, each MR has their own copy, and the Area
|
||||||
|
Manager checks (approves) it.
|
||||||
|
|
||||||
|
Revision ID: p6f2b8d4e1a3
|
||||||
|
Revises: o5e1a7c3d0f2
|
||||||
|
Create Date: 2026-10-25
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "p6f2b8d4e1a3"
|
||||||
|
down_revision: str | None = "o5e1a7c3d0f2"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
COLUMNS = (
|
||||||
|
"name", "designation", "headquarter", "month", "serial_no", "report_date", "from_location", "to_location",
|
||||||
|
"fare", "da_hq", "da_ex", "da_out", "postage", "other_expense", "total", "business_achieved",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"expense_statement",
|
||||||
|
sa.Column("id", sa.UUID(), nullable=False),
|
||||||
|
sa.Column("source_row_number", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("owner_user_id", sa.UUID(), sa.ForeignKey("user.id", ondelete="SET NULL"), nullable=True),
|
||||||
|
*(sa.Column(column, sa.Text(), nullable=True) for column in COLUMNS),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
sa.UniqueConstraint("source_row_number", name="uq_expense_statement_source_row"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_expense_statement_owner", "expense_statement", ["owner_user_id"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index("ix_expense_statement_owner", table_name="expense_statement")
|
||||||
|
op.drop_table("expense_statement")
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"""Sales Projection: Closing (quantity, value) and Projection (quantity, value)
|
||||||
|
|
||||||
|
The form is now Sl. No. | Product | PTS | Closing (Qty, Value) | Projection (Qty, Value).
|
||||||
|
The old Closing figure becomes the closing quantity. The other old columns (Sec. Qty, Value,
|
||||||
|
Sec. Value, <Month> Sales, Value) are no longer shown, but are kept so no entered figure is lost.
|
||||||
|
|
||||||
|
Revision ID: q7a3c9e5f2b4
|
||||||
|
Revises: p6f2b8d4e1a3
|
||||||
|
Create Date: 2026-10-26
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "q7a3c9e5f2b4"
|
||||||
|
down_revision: str | None = "p6f2b8d4e1a3"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
COLUMNS = ("closing_qty", "closing_value", "projection_qty", "projection_value")
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
for column in COLUMNS:
|
||||||
|
op.add_column("sales_projection", sa.Column(column, sa.Text(), nullable=True))
|
||||||
|
op.execute('UPDATE "sales_projection" SET closing_qty = closing')
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
for column in reversed(COLUMNS):
|
||||||
|
op.drop_column("sales_projection", column)
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
"""a doctor or chemist added by an MR waits for the Area Manager; a doctor visit records a gift
|
||||||
|
|
||||||
|
Every existing doctor and chemist is already in use, so all of them start APPROVED.
|
||||||
|
|
||||||
|
Revision ID: r8b4d0f6a3c5
|
||||||
|
Revises: q7a3c9e5f2b4
|
||||||
|
Create Date: 2026-10-26
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "r8b4d0f6a3c5"
|
||||||
|
down_revision: str | None = "q7a3c9e5f2b4"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
MASTERS = ("doctor", "chemist")
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
for table in MASTERS:
|
||||||
|
op.add_column(
|
||||||
|
table,
|
||||||
|
sa.Column("approval_status", sa.String(10), nullable=False, server_default="APPROVED"),
|
||||||
|
)
|
||||||
|
op.add_column(
|
||||||
|
table,
|
||||||
|
sa.Column(
|
||||||
|
"requested_by_user_id",
|
||||||
|
sa.UUID(),
|
||||||
|
sa.ForeignKey("user.id", ondelete="SET NULL"),
|
||||||
|
nullable=True,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
op.add_column(table, sa.Column("rejection_reason", sa.String(500), nullable=True))
|
||||||
|
op.create_index(f"ix_{table}_approval_status", table, ["approval_status"])
|
||||||
|
op.add_column("doctor_call", sa.Column("gift", sa.String(200), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_column("doctor_call", "gift")
|
||||||
|
for table in reversed(MASTERS):
|
||||||
|
op.drop_index(f"ix_{table}_approval_status", table_name=table)
|
||||||
|
op.drop_column(table, "rejection_reason")
|
||||||
|
op.drop_column(table, "requested_by_user_id")
|
||||||
|
op.drop_column(table, "approval_status")
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
"""a headquarters may have several Area Managers
|
||||||
|
|
||||||
|
The rule was one active Area Manager per headquarters. Now any number may manage one;
|
||||||
|
the same Area Manager still holds a headquarters only once at a time.
|
||||||
|
|
||||||
|
Revision ID: s9c5e1a7b4d6
|
||||||
|
Revises: r8b4d0f6a3c5
|
||||||
|
Create Date: 2026-10-26
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "s9c5e1a7b4d6"
|
||||||
|
down_revision: str | None = "r8b4d0f6a3c5"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.drop_index("uq_active_am_per_hq", table_name="am_headquarters")
|
||||||
|
op.create_index(
|
||||||
|
"uq_active_am_hq_pair",
|
||||||
|
"am_headquarters",
|
||||||
|
["headquarters_id", "area_manager_user_id"],
|
||||||
|
unique=True,
|
||||||
|
postgresql_where=sa.text("effective_to IS NULL"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index("uq_active_am_hq_pair", table_name="am_headquarters")
|
||||||
|
# Back to one per headquarters: keep the longest-standing Area Manager of each.
|
||||||
|
op.execute(
|
||||||
|
"""UPDATE am_headquarters a SET effective_to = CURRENT_DATE
|
||||||
|
WHERE a.effective_to IS NULL AND EXISTS (
|
||||||
|
SELECT 1 FROM am_headquarters b
|
||||||
|
WHERE b.headquarters_id = a.headquarters_id AND b.effective_to IS NULL
|
||||||
|
AND (b.effective_from, b.id::text) < (a.effective_from, a.id::text))"""
|
||||||
|
)
|
||||||
|
op.create_index(
|
||||||
|
"uq_active_am_per_hq",
|
||||||
|
"am_headquarters",
|
||||||
|
["headquarters_id"],
|
||||||
|
unique=True,
|
||||||
|
postgresql_where=sa.text("effective_to IS NULL"),
|
||||||
|
)
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
"""protected super admin account
|
||||||
|
|
||||||
|
Adds `user.is_superadmin`. A trigger refuses to delete such a row, to deactivate it, or
|
||||||
|
to change its role, email, employee code or the flag itself, so the protection holds even
|
||||||
|
for a direct SQL session. (The password hash stays changeable so the owner can rotate it
|
||||||
|
with `scripts/create_superadmin.py`.)
|
||||||
|
|
||||||
|
Revision ID: t0d6f2b8c5e7
|
||||||
|
Revises: s9c5e1a7b4d6
|
||||||
|
Create Date: 2026-10-27
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "t0d6f2b8c5e7"
|
||||||
|
down_revision: str | None = "s9c5e1a7b4d6"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column(
|
||||||
|
"user",
|
||||||
|
sa.Column("is_superadmin", sa.Boolean(), server_default=sa.text("false"), nullable=False),
|
||||||
|
)
|
||||||
|
op.execute(
|
||||||
|
"""
|
||||||
|
CREATE OR REPLACE FUNCTION protect_superadmin() RETURNS trigger AS $$
|
||||||
|
BEGIN
|
||||||
|
IF TG_OP = 'DELETE' THEN
|
||||||
|
IF OLD.is_superadmin THEN
|
||||||
|
RAISE EXCEPTION 'The super admin account cannot be deleted';
|
||||||
|
END IF;
|
||||||
|
RETURN OLD;
|
||||||
|
END IF;
|
||||||
|
IF OLD.is_superadmin AND (
|
||||||
|
NEW.is_superadmin IS DISTINCT FROM OLD.is_superadmin
|
||||||
|
OR NEW.is_active IS DISTINCT FROM OLD.is_active
|
||||||
|
OR NEW.role IS DISTINCT FROM OLD.role
|
||||||
|
OR NEW.email IS DISTINCT FROM OLD.email
|
||||||
|
OR NEW.employee_code IS DISTINCT FROM OLD.employee_code
|
||||||
|
OR NEW.full_name IS DISTINCT FROM OLD.full_name
|
||||||
|
) THEN
|
||||||
|
RAISE EXCEPTION 'The super admin account cannot be modified';
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
op.execute(
|
||||||
|
'CREATE TRIGGER trg_protect_superadmin BEFORE UPDATE OR DELETE ON "user" '
|
||||||
|
"FOR EACH ROW EXECUTE FUNCTION protect_superadmin()"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.execute('DROP TRIGGER IF EXISTS trg_protect_superadmin ON "user"')
|
||||||
|
op.execute("DROP FUNCTION IF EXISTS protect_superadmin()")
|
||||||
|
op.drop_column("user", "is_superadmin")
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
"""sales projection rows belong to the MR who entered them
|
||||||
|
|
||||||
|
Until now the form was one shared sheet, so two MRs overwrote each other and the NAME /
|
||||||
|
HEADQUARTER columns had no reliable value. Rows with no owner stay as the shared product
|
||||||
|
list every MR starts from; an MR's first entry on a product becomes their own row.
|
||||||
|
|
||||||
|
Revision ID: u1e7a3c9d6f8
|
||||||
|
Revises: t0d6f2b8c5e7
|
||||||
|
Create Date: 2026-10-27
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "u1e7a3c9d6f8"
|
||||||
|
down_revision: str | None = "t0d6f2b8c5e7"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("sales_projection", sa.Column("owner_user_id", sa.UUID(), nullable=True))
|
||||||
|
op.create_foreign_key(
|
||||||
|
"fk_sales_projection_owner", "sales_projection", "user", ["owner_user_id"], ["id"],
|
||||||
|
ondelete="RESTRICT",
|
||||||
|
)
|
||||||
|
op.create_index("ix_sales_projection_owner", "sales_projection", ["owner_user_id"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index("ix_sales_projection_owner", table_name="sales_projection")
|
||||||
|
op.drop_constraint("fk_sales_projection_owner", "sales_projection", type_="foreignkey")
|
||||||
|
op.drop_column("sales_projection", "owner_user_id")
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""an MR submits a month of their Sales Projection
|
||||||
|
|
||||||
|
Revision ID: v2f8b4d0e7a9
|
||||||
|
Revises: u1e7a3c9d6f8
|
||||||
|
Create Date: 2026-10-27
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "v2f8b4d0e7a9"
|
||||||
|
down_revision: str | None = "u1e7a3c9d6f8"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"sales_projection_submission",
|
||||||
|
sa.Column("owner_user_id", sa.UUID(), sa.ForeignKey("user.id", ondelete="CASCADE"), nullable=False),
|
||||||
|
sa.Column("month", sa.String(20), nullable=False),
|
||||||
|
sa.Column("submitted_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint("owner_user_id", "month"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("sales_projection_submission")
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""drop the Sales Projection month submission
|
||||||
|
|
||||||
|
Revision ID: w3a9c5e1f8b0
|
||||||
|
Revises: v2f8b4d0e7a9
|
||||||
|
Create Date: 2026-10-27
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "w3a9c5e1f8b0"
|
||||||
|
down_revision: str | None = "v2f8b4d0e7a9"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.drop_table("sales_projection_submission")
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"sales_projection_submission",
|
||||||
|
sa.Column("owner_user_id", sa.UUID(), sa.ForeignKey("user.id", ondelete="CASCADE"), nullable=False),
|
||||||
|
sa.Column("month", sa.String(20), nullable=False),
|
||||||
|
sa.Column("submitted_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint("owner_user_id", "month"),
|
||||||
|
)
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
"""sales and stock statement rows belong to the MR who entered them
|
||||||
|
|
||||||
|
Same change as Sales Projection: rows with no owner stay as the shared product list.
|
||||||
|
|
||||||
|
Revision ID: x4b0d6f2a9c1
|
||||||
|
Revises: w3a9c5e1f8b0
|
||||||
|
Create Date: 2026-10-27
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "x4b0d6f2a9c1"
|
||||||
|
down_revision: str | None = "w3a9c5e1f8b0"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("sales_and_stock_statement", sa.Column("owner_user_id", sa.UUID(), nullable=True))
|
||||||
|
op.create_foreign_key(
|
||||||
|
"fk_sales_stock_owner", "sales_and_stock_statement", "user", ["owner_user_id"], ["id"],
|
||||||
|
ondelete="RESTRICT",
|
||||||
|
)
|
||||||
|
op.create_index("ix_sales_stock_owner", "sales_and_stock_statement", ["owner_user_id"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index("ix_sales_stock_owner", table_name="sales_and_stock_statement")
|
||||||
|
op.drop_constraint("fk_sales_stock_owner", "sales_and_stock_statement", type_="foreignkey")
|
||||||
|
op.drop_column("sales_and_stock_statement", "owner_user_id")
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""Senior Field Executive: a field role like MR that may cover several headquarters
|
||||||
|
|
||||||
|
Revision ID: y5c1e7a3b0d2
|
||||||
|
Revises: x4b0d6f2a9c1
|
||||||
|
Create Date: 2026-10-27
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "y5c1e7a3b0d2"
|
||||||
|
down_revision: str | None = "x4b0d6f2a9c1"
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.drop_constraint("ck_user_mr_requires_hq", "user", type_="check")
|
||||||
|
op.create_check_constraint(
|
||||||
|
"ck_user_mr_requires_hq",
|
||||||
|
"user",
|
||||||
|
"(role IN ('MR', 'SFE') AND headquarters_id IS NOT NULL) "
|
||||||
|
"OR (role NOT IN ('MR', 'SFE') AND headquarters_id IS NULL)",
|
||||||
|
)
|
||||||
|
op.create_table(
|
||||||
|
"user_extra_headquarters",
|
||||||
|
sa.Column("user_id", sa.UUID(), sa.ForeignKey("user.id", ondelete="CASCADE"), primary_key=True),
|
||||||
|
sa.Column(
|
||||||
|
"headquarters_id", sa.UUID(), sa.ForeignKey("headquarters.id", ondelete="RESTRICT"), primary_key=True
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("user_extra_headquarters")
|
||||||
|
op.drop_constraint("ck_user_mr_requires_hq", "user", type_="check")
|
||||||
|
op.create_check_constraint(
|
||||||
|
"ck_user_mr_requires_hq",
|
||||||
|
"user",
|
||||||
|
"(role = 'MR' AND headquarters_id IS NOT NULL) OR (role <> 'MR' AND headquarters_id IS NULL)",
|
||||||
|
)
|
||||||
@@ -10,7 +10,7 @@ The Area Manager is the final approver; there is no General Manager stage.
|
|||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
|
||||||
from app.common.enums import EDITABLE_STATUSES, DCRStatus, Role, WorkflowAction
|
from app.common.enums import EDITABLE_STATUSES, FIELD_ROLES, DCRStatus, Role, WorkflowAction
|
||||||
from app.common.exceptions import ForbiddenError, InvalidStateTransitionError
|
from app.common.exceptions import ForbiddenError, InvalidStateTransitionError
|
||||||
|
|
||||||
|
|
||||||
@@ -62,7 +62,8 @@ def assert_transition(status: DCRStatus, action: WorkflowAction, role: Role) ->
|
|||||||
),
|
),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
if transition.allowed_role != role:
|
# An SFE files and submits reports exactly as an MR does.
|
||||||
|
if transition.allowed_role != (Role.MR if role in FIELD_ROLES else role):
|
||||||
raise ForbiddenError(
|
raise ForbiddenError(
|
||||||
f"Role {role.value} may not {action.value.lower()} this report",
|
f"Role {role.value} may not {action.value.lower()} this report",
|
||||||
{"required_role": transition.allowed_role.value, "your_role": role.value},
|
{"required_role": transition.allowed_role.value, "your_role": role.value},
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ from sqlalchemy import select
|
|||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.auth.security import decode_access_token
|
from app.auth.security import decode_access_token
|
||||||
from app.common.enums import Role
|
from app.common.enums import Role, FIELD_ROLES
|
||||||
from app.common.exceptions import ForbiddenError, UnauthorizedError
|
from app.common.exceptions import ForbiddenError, UnauthorizedError
|
||||||
from app.database.session import get_db
|
from app.database.session import get_db
|
||||||
from app.organization.models import AMHeadquarters
|
from app.organization.models import AMHeadquarters
|
||||||
@@ -51,7 +51,9 @@ def require_role(*allowed: Role):
|
|||||||
"""Layer 1. Usage: `user: User = Depends(require_role(Role.MR))`."""
|
"""Layer 1. Usage: `user: User = Depends(require_role(Role.MR))`."""
|
||||||
|
|
||||||
async def _check(user: User = Depends(get_current_user)) -> User:
|
async def _check(user: User = Depends(get_current_user)) -> User:
|
||||||
if user.role not in allowed:
|
# Wherever an MR is allowed, an SFE is too.
|
||||||
|
permitted = set(allowed) | ({Role.SFE} if Role.MR in allowed else set())
|
||||||
|
if user.role not in permitted:
|
||||||
raise ForbiddenError(
|
raise ForbiddenError(
|
||||||
"Role not permitted for this action",
|
"Role not permitted for this action",
|
||||||
{"your_role": user.role.value, "required": [r.value for r in allowed]},
|
{"your_role": user.role.value, "required": [r.value for r in allowed]},
|
||||||
@@ -76,8 +78,8 @@ async def visible_hq_ids(db: AsyncSession, user: User) -> set[uuid.UUID] | None:
|
|||||||
return None
|
return None
|
||||||
if user.role == Role.AM:
|
if user.role == Role.AM:
|
||||||
return await active_hq_ids_for_am(db, user.id)
|
return await active_hq_ids_for_am(db, user.id)
|
||||||
if user.role == Role.MR:
|
if user.role in FIELD_ROLES:
|
||||||
return {user.headquarters_id} if user.headquarters_id else set()
|
return user.covered_headquarter_ids
|
||||||
return set()
|
return set()
|
||||||
|
|
||||||
|
|
||||||
@@ -96,7 +98,7 @@ async def assert_can_view_dcr(db: AsyncSession, user: User, dcr) -> None:
|
|||||||
"""
|
"""
|
||||||
if user.role in (Role.GM, Role.ADMIN):
|
if user.role in (Role.GM, Role.ADMIN):
|
||||||
return
|
return
|
||||||
if user.role == Role.MR and dcr.mr_user_id == user.id:
|
if user.role in FIELD_ROLES and dcr.mr_user_id == user.id:
|
||||||
return
|
return
|
||||||
if user.role == Role.AM:
|
if user.role == Role.AM:
|
||||||
if dcr.headquarters_id in await active_hq_ids_for_am(db, user.id):
|
if dcr.headquarters_id in await active_hq_ids_for_am(db, user.id):
|
||||||
|
|||||||
@@ -31,3 +31,5 @@ class CurrentUser(BaseModel):
|
|||||||
role: Role
|
role: Role
|
||||||
headquarters_id: uuid.UUID | None
|
headquarters_id: uuid.UUID | None
|
||||||
is_active: bool
|
is_active: bool
|
||||||
|
is_superadmin: bool = False
|
||||||
|
extra_headquarter_ids: list[uuid.UUID] = []
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ from sqlalchemy import Boolean, Date, ForeignKey, Index, String, UniqueConstrain
|
|||||||
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
||||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
|
from app.common.enums import MasterApproval
|
||||||
from app.database.base import Base, TimestampMixin, UUIDMixin
|
from app.database.base import Base, TimestampMixin, UUIDMixin
|
||||||
|
|
||||||
|
|
||||||
@@ -25,6 +26,22 @@ class Chemist(Base, UUIDMixin, TimestampMixin):
|
|||||||
shop_address: Mapped[str] = mapped_column(String(500), nullable=False)
|
shop_address: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
contact_number: Mapped[str | None] = mapped_column(String(20))
|
contact_number: Mapped[str | None] = mapped_column(String(20))
|
||||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||||
|
#: PENDING until the Area Manager approves one an MR added; only APPROVED ones are listed or visited.
|
||||||
|
approval_status: Mapped[str] = mapped_column(
|
||||||
|
String(10), default=MasterApproval.APPROVED.value, server_default=MasterApproval.APPROVED.value, nullable=False
|
||||||
|
)
|
||||||
|
#: The MR who asked for it (None for one the administrator created).
|
||||||
|
requested_by_user_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="SET NULL")
|
||||||
|
)
|
||||||
|
rejection_reason: Mapped[str | None] = mapped_column(String(500))
|
||||||
|
requested_by: Mapped["User | None"] = relationship( # noqa: F821
|
||||||
|
lazy="selectin", foreign_keys=[requested_by_user_id]
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def requested_by_name(self) -> str | None:
|
||||||
|
return self.requested_by.full_name if self.requested_by else None
|
||||||
|
|
||||||
assignments: Mapped[list["ChemistAssignment"]] = relationship(back_populates="chemist")
|
assignments: Mapped[list["ChemistAssignment"]] = relationship(back_populates="chemist")
|
||||||
|
|
||||||
|
|||||||
+34
-2
@@ -9,7 +9,7 @@ from app.chemists.schemas import ChemistCreate, ChemistRead, ChemistUpdate
|
|||||||
from app.chemists.service import ChemistService
|
from app.chemists.service import ChemistService
|
||||||
from app.common.enums import Role
|
from app.common.enums import Role
|
||||||
from app.database.session import get_db
|
from app.database.session import get_db
|
||||||
from app.doctors.schemas import AssignToMR
|
from app.doctors.schemas import AssignToMR, RejectMaster
|
||||||
from app.users.models import User
|
from app.users.models import User
|
||||||
|
|
||||||
router = APIRouter(prefix="/chemists", tags=["chemists"])
|
router = APIRouter(prefix="/chemists", tags=["chemists"])
|
||||||
@@ -26,9 +26,10 @@ async def list_chemists(
|
|||||||
async def create_chemist(
|
async def create_chemist(
|
||||||
payload: ChemistCreate,
|
payload: ChemistCreate,
|
||||||
request: Request,
|
request: Request,
|
||||||
current_user: User = Depends(require_role(Role.ADMIN)),
|
current_user: User = Depends(require_role(Role.ADMIN, Role.MR)),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> Chemist:
|
) -> Chemist:
|
||||||
|
"""An Administrator, or an MR within their own headquarters (AM and GM cannot)."""
|
||||||
return await ChemistService(db).create(payload, current_user, client_ip(request))
|
return await ChemistService(db).create(payload, current_user, client_ip(request))
|
||||||
|
|
||||||
|
|
||||||
@@ -60,3 +61,34 @@ async def assign_chemist(
|
|||||||
"mr_user_id": assignment.mr_user_id,
|
"mr_user_id": assignment.mr_user_id,
|
||||||
"effective_from": assignment.effective_from,
|
"effective_from": assignment.effective_from,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/requests", response_model=list[ChemistRead])
|
||||||
|
async def list_chemist_requests(
|
||||||
|
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
||||||
|
) -> list[Chemist]:
|
||||||
|
"""Chemists an MR added that wait for the Area Manager: an MR sees their own (with any
|
||||||
|
rejected and why), an Area Manager what waits for them, the administrator and GM all."""
|
||||||
|
return await ChemistService(db).requests_for(current_user)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{chemist_id}/approve", response_model=ChemistRead)
|
||||||
|
async def approve_chemist(
|
||||||
|
chemist_id: uuid.UUID,
|
||||||
|
request: Request,
|
||||||
|
current_user: User = Depends(require_role(Role.AM, Role.ADMIN)),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> Chemist:
|
||||||
|
"""The Area Manager of its headquarters adds it to the list, assigned to the MR who asked."""
|
||||||
|
return await ChemistService(db).review(chemist_id, True, None, current_user, client_ip(request))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{chemist_id}/reject", response_model=ChemistRead)
|
||||||
|
async def reject_chemist(
|
||||||
|
chemist_id: uuid.UUID,
|
||||||
|
payload: RejectMaster,
|
||||||
|
request: Request,
|
||||||
|
current_user: User = Depends(require_role(Role.AM, Role.ADMIN)),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> Chemist:
|
||||||
|
return await ChemistService(db).review(chemist_id, False, payload.reason, current_user, client_ip(request))
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import uuid
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
@@ -26,3 +27,9 @@ class ChemistRead(BaseModel):
|
|||||||
shop_address: str
|
shop_address: str
|
||||||
contact_number: str | None
|
contact_number: str | None
|
||||||
is_active: bool
|
is_active: bool
|
||||||
|
#: PENDING / APPROVED / REJECTED — see app/common/master_approval.py.
|
||||||
|
approval_status: str
|
||||||
|
rejection_reason: str | None
|
||||||
|
requested_by_name: str | None
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
|||||||
+60
-6
@@ -9,7 +9,8 @@ from app.audit.service import AuditService
|
|||||||
from app.auth.dependencies import assert_can_view_hq, visible_hq_ids
|
from app.auth.dependencies import assert_can_view_hq, visible_hq_ids
|
||||||
from app.chemists.models import Chemist, ChemistAssignment
|
from app.chemists.models import Chemist, ChemistAssignment
|
||||||
from app.chemists.schemas import ChemistCreate, ChemistUpdate
|
from app.chemists.schemas import ChemistCreate, ChemistUpdate
|
||||||
from app.common.enums import AuditAction, EntityType, Role
|
from app.common import master_approval
|
||||||
|
from app.common.enums import AuditAction, EntityType, MasterApproval, Role, FIELD_ROLES
|
||||||
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
|
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
|
||||||
from app.common.utils import snapshot
|
from app.common.utils import snapshot
|
||||||
from app.users.models import User
|
from app.users.models import User
|
||||||
@@ -25,7 +26,32 @@ class ChemistService:
|
|||||||
async def create(self, data: ChemistCreate, actor: User, ip: str | None = None) -> Chemist:
|
async def create(self, data: ChemistCreate, actor: User, ip: str | None = None) -> Chemist:
|
||||||
await assert_can_view_hq(self.db, actor, data.headquarters_id)
|
await assert_can_view_hq(self.db, actor, data.headquarters_id)
|
||||||
|
|
||||||
chemist = Chemist(**data.model_dump())
|
values = data.model_dump()
|
||||||
|
# Added by an MR: it waits for the Area Manager. One they were refused is sent again.
|
||||||
|
twin = None
|
||||||
|
if actor.role in FIELD_ROLES:
|
||||||
|
twin = await master_approval.rejected_twin(
|
||||||
|
self.db, Chemist, {k: values[k] for k in ('headquarters_id', 'name', 'shop_address')}
|
||||||
|
)
|
||||||
|
if twin is not None:
|
||||||
|
await master_approval.resubmit(self.db, twin, values, actor, ChemistAssignment, "chemist_id")
|
||||||
|
await self.audit.log(
|
||||||
|
actor_user_id=actor.id,
|
||||||
|
entity_type=EntityType.CHEMIST,
|
||||||
|
entity_id=twin.id,
|
||||||
|
action=AuditAction.SUBMIT,
|
||||||
|
after=snapshot(twin, _AUDIT_FIELDS),
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
|
await self.db.commit()
|
||||||
|
await self.db.refresh(twin)
|
||||||
|
return twin
|
||||||
|
|
||||||
|
chemist = Chemist(
|
||||||
|
**values,
|
||||||
|
approval_status=master_approval.initial_status(actor),
|
||||||
|
requested_by_user_id=actor.id if actor.role in FIELD_ROLES else None,
|
||||||
|
)
|
||||||
self.db.add(chemist)
|
self.db.add(chemist)
|
||||||
try:
|
try:
|
||||||
await self.db.flush()
|
await self.db.flush()
|
||||||
@@ -44,7 +70,22 @@ class ChemistService:
|
|||||||
after=snapshot(chemist, _AUDIT_FIELDS),
|
after=snapshot(chemist, _AUDIT_FIELDS),
|
||||||
ip_address=ip,
|
ip_address=ip,
|
||||||
)
|
)
|
||||||
|
# An MR only sees assigned chemists, so the one they add is assigned to them.
|
||||||
|
if actor.role in FIELD_ROLES:
|
||||||
|
start = date.today()
|
||||||
|
self.db.add(
|
||||||
|
ChemistAssignment(chemist_id=chemist.id, mr_user_id=actor.id, effective_from=start)
|
||||||
|
)
|
||||||
|
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(actor.id), "effective_from": start.isoformat()},
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
await self.db.commit()
|
await self.db.commit()
|
||||||
|
await self.db.refresh(chemist)
|
||||||
return chemist
|
return chemist
|
||||||
|
|
||||||
async def update(
|
async def update(
|
||||||
@@ -72,7 +113,7 @@ class ChemistService:
|
|||||||
return chemist
|
return chemist
|
||||||
|
|
||||||
async def list_for(self, actor: User) -> list[Chemist]:
|
async def list_for(self, actor: User) -> list[Chemist]:
|
||||||
if actor.role == Role.MR:
|
if actor.role in FIELD_ROLES:
|
||||||
stmt = (
|
stmt = (
|
||||||
select(Chemist)
|
select(Chemist)
|
||||||
.join(ChemistAssignment, ChemistAssignment.chemist_id == Chemist.id)
|
.join(ChemistAssignment, ChemistAssignment.chemist_id == Chemist.id)
|
||||||
@@ -80,13 +121,14 @@ class ChemistService:
|
|||||||
ChemistAssignment.mr_user_id == actor.id,
|
ChemistAssignment.mr_user_id == actor.id,
|
||||||
ChemistAssignment.effective_to.is_(None),
|
ChemistAssignment.effective_to.is_(None),
|
||||||
Chemist.is_active.is_(True),
|
Chemist.is_active.is_(True),
|
||||||
|
Chemist.approval_status == MasterApproval.APPROVED,
|
||||||
)
|
)
|
||||||
.order_by(Chemist.name)
|
.order_by(Chemist.name)
|
||||||
)
|
)
|
||||||
return list((await self.db.execute(stmt)).scalars().all())
|
return list((await self.db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
allowed = await visible_hq_ids(self.db, actor)
|
allowed = await visible_hq_ids(self.db, actor)
|
||||||
stmt = select(Chemist).order_by(Chemist.name)
|
stmt = select(Chemist).where(Chemist.approval_status == MasterApproval.APPROVED).order_by(Chemist.name)
|
||||||
if allowed is not None:
|
if allowed is not None:
|
||||||
stmt = stmt.where(Chemist.headquarters_id.in_(allowed or [None]))
|
stmt = stmt.where(Chemist.headquarters_id.in_(allowed or [None]))
|
||||||
return list((await self.db.execute(stmt)).scalars().all())
|
return list((await self.db.execute(stmt)).scalars().all())
|
||||||
@@ -103,13 +145,15 @@ class ChemistService:
|
|||||||
if chemist is None:
|
if chemist is None:
|
||||||
raise NotFoundError("Chemist not found")
|
raise NotFoundError("Chemist not found")
|
||||||
await assert_can_view_hq(self.db, actor, chemist.headquarters_id)
|
await assert_can_view_hq(self.db, actor, chemist.headquarters_id)
|
||||||
|
if chemist.approval_status != MasterApproval.APPROVED:
|
||||||
|
raise ValidationError("This chemist is still waiting for the Area Manager's approval")
|
||||||
|
|
||||||
mr = await self.db.get(User, mr_user_id)
|
mr = await self.db.get(User, mr_user_id)
|
||||||
if mr is None:
|
if mr is None:
|
||||||
raise NotFoundError("MR not found")
|
raise NotFoundError("MR not found")
|
||||||
if mr.role != Role.MR:
|
if mr.role not in FIELD_ROLES:
|
||||||
raise ValidationError("Chemists can only be assigned to an MR")
|
raise ValidationError("Chemists can only be assigned to an MR")
|
||||||
if mr.headquarters_id != chemist.headquarters_id:
|
if chemist.headquarters_id not in mr.covered_headquarter_ids:
|
||||||
raise ValidationError("MR and chemist belong to different headquarters")
|
raise ValidationError("MR and chemist belong to different headquarters")
|
||||||
|
|
||||||
start = effective_from or date.today()
|
start = effective_from or date.today()
|
||||||
@@ -141,3 +185,13 @@ class ChemistService:
|
|||||||
)
|
)
|
||||||
await self.db.commit()
|
await self.db.commit()
|
||||||
return assignment
|
return assignment
|
||||||
|
|
||||||
|
async def requests_for(self, actor: User) -> list[Chemist]:
|
||||||
|
return await master_approval.requests_for(self.db, Chemist, actor)
|
||||||
|
|
||||||
|
async def review(
|
||||||
|
self, chemist_id: uuid.UUID, approve: bool, reason: str | None, actor: User, ip: str | None = None
|
||||||
|
) -> Chemist:
|
||||||
|
return await master_approval.review(
|
||||||
|
self.db, Chemist, EntityType.CHEMIST, chemist_id, approve, reason, actor, ip
|
||||||
|
)
|
||||||
|
|||||||
@@ -19,6 +19,13 @@ class Role(StrEnum):
|
|||||||
GM = "GM"
|
GM = "GM"
|
||||||
AM = "AM"
|
AM = "AM"
|
||||||
MR = "MR"
|
MR = "MR"
|
||||||
|
#: Senior Field Executive: does an MR's work (daily reports, forms, doctors, chemists) and
|
||||||
|
#: reports to the same Area Manager, but may cover several headquarters.
|
||||||
|
SFE = "SFE"
|
||||||
|
|
||||||
|
|
||||||
|
#: The roles that do field work and file reports; everywhere "an MR" is checked, an SFE counts too.
|
||||||
|
FIELD_ROLES: frozenset[Role] = frozenset({Role.MR, Role.SFE})
|
||||||
|
|
||||||
|
|
||||||
class DCRStatus(StrEnum):
|
class DCRStatus(StrEnum):
|
||||||
@@ -34,6 +41,21 @@ class DCRStatus(StrEnum):
|
|||||||
APPROVED = "APPROVED"
|
APPROVED = "APPROVED"
|
||||||
|
|
||||||
|
|
||||||
|
class ReportType(StrEnum):
|
||||||
|
"""An MR files two reports a day, each approved by the Area Manager on its own.
|
||||||
|
|
||||||
|
PLAN — in the morning: which doctors and chemists the MR intends to visit, and when.
|
||||||
|
ACTUAL — at the end of the day: the visits that happened, plus a short note for every
|
||||||
|
planned visit that did not. It can be started only once the plan is approved.
|
||||||
|
SELF — an Area Manager's own end-of-day report of the visits they made. It needs no
|
||||||
|
plan and no approval: submitting it makes it final.
|
||||||
|
"""
|
||||||
|
|
||||||
|
PLAN = "PLAN"
|
||||||
|
ACTUAL = "ACTUAL"
|
||||||
|
SELF = "SELF"
|
||||||
|
|
||||||
|
|
||||||
#: Statuses in which the owning MR may still change report data (V9).
|
#: Statuses in which the owning MR may still change report data (V9).
|
||||||
EDITABLE_STATUSES: frozenset[DCRStatus] = frozenset(
|
EDITABLE_STATUSES: frozenset[DCRStatus] = frozenset(
|
||||||
{DCRStatus.DRAFT, DCRStatus.RETURNED}
|
{DCRStatus.DRAFT, DCRStatus.RETURNED}
|
||||||
@@ -61,6 +83,14 @@ class ConversionStatus(StrEnum):
|
|||||||
LOST = "LOST"
|
LOST = "LOST"
|
||||||
|
|
||||||
|
|
||||||
|
class MasterApproval(StrEnum):
|
||||||
|
"""A doctor or chemist an MR adds waits for their Area Manager before anyone can use it."""
|
||||||
|
|
||||||
|
PENDING = "PENDING"
|
||||||
|
APPROVED = "APPROVED"
|
||||||
|
REJECTED = "REJECTED"
|
||||||
|
|
||||||
|
|
||||||
class AuditAction(StrEnum):
|
class AuditAction(StrEnum):
|
||||||
CREATE = "CREATE"
|
CREATE = "CREATE"
|
||||||
UPDATE = "UPDATE"
|
UPDATE = "UPDATE"
|
||||||
@@ -81,3 +111,5 @@ class EntityType(StrEnum):
|
|||||||
CHEMIST = "chemist"
|
CHEMIST = "chemist"
|
||||||
DCR = "dcr"
|
DCR = "dcr"
|
||||||
PRODUCT = "product"
|
PRODUCT = "product"
|
||||||
|
#: A row of a company form (the table is named in the entry's data).
|
||||||
|
FORM_ROW = "form_row"
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
"""Approval of the doctors and chemists an MR adds.
|
||||||
|
|
||||||
|
MR adds one --> PENDING --approve(AM)--> APPROVED (listed, and visitable by that MR)
|
||||||
|
--reject(AM)---> REJECTED (the MR sees why; adding it again re-sends it)
|
||||||
|
|
||||||
|
Only APPROVED masters are listed or may be visited. The administrator's own additions are
|
||||||
|
APPROVED at once. The reviewer is the Area Manager of the master's headquarters (or the
|
||||||
|
administrator); the General Manager may look but not act.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from datetime import date
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
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, MasterApproval, Role, FIELD_ROLES
|
||||||
|
from app.common.exceptions import ConflictError, ForbiddenError, NotFoundError
|
||||||
|
from app.users.models import User
|
||||||
|
|
||||||
|
|
||||||
|
def initial_status(actor: User) -> str:
|
||||||
|
return MasterApproval.PENDING if actor.role in FIELD_ROLES else MasterApproval.APPROVED
|
||||||
|
|
||||||
|
|
||||||
|
async def rejected_twin(db: AsyncSession, model: Any, match: dict[str, Any]) -> Any | None:
|
||||||
|
"""A rejected record with the same identity: adding it again re-sends that one for approval."""
|
||||||
|
stmt = select(model).where(*(getattr(model, k) == v for k, v in match.items()))
|
||||||
|
found = (await db.execute(stmt)).scalars().first()
|
||||||
|
return found if found is not None and found.approval_status == MasterApproval.REJECTED else None
|
||||||
|
|
||||||
|
|
||||||
|
async def resubmit(
|
||||||
|
db: AsyncSession, record: Any, values: dict[str, Any], actor: User, assignment_model: Any, fk: str
|
||||||
|
) -> None:
|
||||||
|
"""Re-send a rejected record with the MR's new details, assigned to that MR."""
|
||||||
|
for field, value in values.items():
|
||||||
|
setattr(record, field, value)
|
||||||
|
record.approval_status = MasterApproval.PENDING
|
||||||
|
record.requested_by_user_id = actor.id
|
||||||
|
record.rejection_reason = None
|
||||||
|
today = date.today()
|
||||||
|
current = (
|
||||||
|
await db.execute(
|
||||||
|
select(assignment_model).where(
|
||||||
|
getattr(assignment_model, fk) == record.id, assignment_model.effective_to.is_(None)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
if not any(a.mr_user_id == actor.id for a in current):
|
||||||
|
for row in current:
|
||||||
|
row.effective_to = today
|
||||||
|
await db.flush()
|
||||||
|
db.add(assignment_model(**{fk: record.id, "mr_user_id": actor.id, "effective_from": today}))
|
||||||
|
|
||||||
|
|
||||||
|
async def requests_for(db: AsyncSession, model: Any, actor: User) -> list[Any]:
|
||||||
|
"""An MR: what they asked for that is still waiting or was rejected.
|
||||||
|
An Area Manager: what waits for them. Administrator and GM: everything waiting."""
|
||||||
|
stmt = select(model).order_by(model.created_at.desc())
|
||||||
|
if actor.role in FIELD_ROLES:
|
||||||
|
return list(
|
||||||
|
(
|
||||||
|
await db.execute(
|
||||||
|
stmt.where(
|
||||||
|
model.requested_by_user_id == actor.id,
|
||||||
|
model.approval_status.in_([MasterApproval.PENDING, MasterApproval.REJECTED]),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
).scalars()
|
||||||
|
)
|
||||||
|
stmt = stmt.where(model.approval_status == MasterApproval.PENDING)
|
||||||
|
allowed = await visible_hq_ids(db, actor)
|
||||||
|
if allowed is not None:
|
||||||
|
stmt = stmt.where(model.headquarters_id.in_(allowed or [None]))
|
||||||
|
return list((await db.execute(stmt)).scalars())
|
||||||
|
|
||||||
|
|
||||||
|
async def review(
|
||||||
|
db: AsyncSession,
|
||||||
|
model: Any,
|
||||||
|
entity_type: EntityType,
|
||||||
|
record_id: uuid.UUID,
|
||||||
|
approve: bool,
|
||||||
|
reason: str | None,
|
||||||
|
actor: User,
|
||||||
|
ip: str | None,
|
||||||
|
) -> Any:
|
||||||
|
record = await db.get(model, record_id)
|
||||||
|
if record is None:
|
||||||
|
raise NotFoundError(f"{entity_type.value.capitalize()} not found")
|
||||||
|
if actor.role not in (Role.AM, Role.ADMIN):
|
||||||
|
raise ForbiddenError("Only the Area Manager approves a new doctor or chemist")
|
||||||
|
await assert_can_view_hq(db, actor, record.headquarters_id)
|
||||||
|
target = MasterApproval.APPROVED if approve else MasterApproval.REJECTED
|
||||||
|
if record.approval_status == target:
|
||||||
|
return record # a double click
|
||||||
|
if record.approval_status != MasterApproval.PENDING:
|
||||||
|
raise ConflictError("This request has already been decided", {"status": record.approval_status})
|
||||||
|
record.approval_status = target
|
||||||
|
record.rejection_reason = None if approve else reason
|
||||||
|
await AuditService(db).log(
|
||||||
|
actor_user_id=actor.id,
|
||||||
|
entity_type=entity_type,
|
||||||
|
entity_id=record.id,
|
||||||
|
action=AuditAction.APPROVE if approve else AuditAction.RETURN,
|
||||||
|
before={"approval_status": MasterApproval.PENDING.value},
|
||||||
|
after={"approval_status": target.value, **({"reason": reason} if reason else {})},
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
await db.refresh(record)
|
||||||
|
return record
|
||||||
@@ -40,6 +40,8 @@ class Settings(BaseSettings):
|
|||||||
# --- Business rules (see report §21 — confirm with client) ----------
|
# --- Business rules (see report §21 — confirm with client) ----------
|
||||||
# A10 / Q8: how many days back an MR may file a report.
|
# A10 / Q8: how many days back an MR may file a report.
|
||||||
BACKDATING_WINDOW_DAYS: int = Field(default=7, ge=0, le=90)
|
BACKDATING_WINDOW_DAYS: int = Field(default=7, ge=0, le=90)
|
||||||
|
# A Daily Call Report (Plan) may be made this many days ahead; Done and Self never.
|
||||||
|
PLAN_AHEAD_DAYS: int = Field(default=2, ge=0, le=30)
|
||||||
# A16 / Q9: report for date D must be submitted by end of D + this many days.
|
# 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)
|
SUBMISSION_DEADLINE_DAYS: int = Field(default=1, ge=0, le=30)
|
||||||
# V8: minimum length of a manager's return reason.
|
# V8: minimum length of a manager's return reason.
|
||||||
|
|||||||
@@ -14,23 +14,23 @@ from sqlalchemy import select, text
|
|||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.auth.dependencies import active_hq_ids_for_am
|
from app.auth.dependencies import active_hq_ids_for_am
|
||||||
from app.common.enums import Role
|
from app.common.enums import Role, FIELD_ROLES
|
||||||
from app.common.exceptions import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
from app.common.exceptions import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||||
from app.csv_data.models import FormApproval
|
from app.csv_data.models import FormApproval
|
||||||
from app.organization.models import AMHeadquarters, Headquarters
|
from app.organization.models import AMHeadquarters, Headquarters
|
||||||
from app.users.models import User
|
from app.users.models import User
|
||||||
|
|
||||||
APPROVAL_TABLES = {"standard_tour_plan", "tour_plan", "fare_chart"}
|
APPROVAL_TABLES = {"standard_tour_plan", "tour_plan", "fare_chart", "expense_statement"}
|
||||||
|
|
||||||
|
|
||||||
async def owners_in_scope(db: AsyncSession, user: User) -> list[User]:
|
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."""
|
"""The MRs whose forms this user may see: themselves, their headquarters' MRs, or (admin, GM) all."""
|
||||||
stmt = select(User).where(User.role == Role.MR, User.is_active.is_(True)).order_by(User.full_name)
|
stmt = select(User).where(User.role.in_(FIELD_ROLES), User.is_active.is_(True)).order_by(User.full_name)
|
||||||
if user.role == Role.MR:
|
if user.role in FIELD_ROLES:
|
||||||
stmt = stmt.where(User.id == user.id)
|
stmt = stmt.where(User.id == user.id)
|
||||||
elif user.role == Role.AM:
|
elif user.role == Role.AM:
|
||||||
stmt = stmt.where(User.headquarters_id.in_(await active_hq_ids_for_am(db, user.id)))
|
stmt = stmt.where(User.headquarters_id.in_(await active_hq_ids_for_am(db, user.id)))
|
||||||
elif user.role != Role.ADMIN:
|
elif user.role not in (Role.ADMIN, Role.GM):
|
||||||
return []
|
return []
|
||||||
return list((await db.execute(stmt)).scalars())
|
return list((await db.execute(stmt)).scalars())
|
||||||
|
|
||||||
@@ -49,7 +49,7 @@ async def assert_owner_in_scope(db: AsyncSession, user: User, owner_id: uuid.UUI
|
|||||||
for owner in await owners_in_scope(db, user):
|
for owner in await owners_in_scope(db, user):
|
||||||
if owner.id == owner_id:
|
if owner.id == owner_id:
|
||||||
return owner
|
return owner
|
||||||
if user.role == Role.ADMIN or (await db.get(User, owner_id)) is None:
|
if user.role in (Role.ADMIN, Role.GM) or (await db.get(User, owner_id)) is None:
|
||||||
raise NotFoundError("Medical representative not found", {"id": str(owner_id)})
|
raise NotFoundError("Medical representative not found", {"id": str(owner_id)})
|
||||||
raise ForbiddenError("This form belongs to a medical representative outside your headquarters")
|
raise ForbiddenError("This form belongs to a medical representative outside your headquarters")
|
||||||
|
|
||||||
@@ -80,7 +80,7 @@ async def list_approvals(db: AsyncSession, user: User) -> list[tuple[FormApprova
|
|||||||
for r in (await db.execute(select(FormApproval).where(FormApproval.owner_user_id.in_(owners)))).scalars()
|
for r in (await db.execute(select(FormApproval).where(FormApproval.owner_user_id.in_(owners)))).scalars()
|
||||||
}
|
}
|
||||||
out: list[tuple[FormApproval, User, str | None]] = []
|
out: list[tuple[FormApproval, User, str | None]] = []
|
||||||
if user.role == Role.MR:
|
if user.role in FIELD_ROLES:
|
||||||
for name in sorted(APPROVAL_TABLES):
|
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)))
|
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
|
return out
|
||||||
|
|||||||
+19
-2
@@ -1,7 +1,7 @@
|
|||||||
"""Allow-listed imported CSV tables and their database columns."""
|
"""Allow-listed imported CSV tables and their database columns."""
|
||||||
|
|
||||||
TABLES: dict[str, tuple[str, ...]] = {
|
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"),
|
"sales_projection": ("name", "headquarter", "report_date", "month", "serial_no", "product_name", "pts", "closing_qty", "closing_value", "projection_qty", "projection_value"),
|
||||||
"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"),
|
"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"),
|
"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"),
|
"fare_chart": ("name", "headquarter", "serial_no", "report_date", "from_location", "to_location", "kilometers_km"),
|
||||||
@@ -11,17 +11,34 @@ TABLES: dict[str, tuple[str, ...]] = {
|
|||||||
"sales_and_stock_statement": ("name", "headquarter", "report_date", "month", "serial_no", "product_name", "opening", "receipt", "sale", "closing", "value_in_pts"),
|
"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"),
|
"tour_plan": ("name", "headquarter", "serial_no", "report_date", "from_location", "to_location", "pob", "stockiest_visit"),
|
||||||
"standard_tour_plan": ("name", "headquarter", "serial_no", "place"),
|
"standard_tour_plan": ("name", "headquarter", "serial_no", "place"),
|
||||||
|
"expense_statement": ("name", "designation", "headquarter", "month", "serial_no", "report_date", "from_location", "to_location", "fare", "da_hq", "da_ex", "da_out", "postage", "other_expense", "total", "business_achieved"),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#: The order the forms are listed in, on screen and in the API.
|
||||||
|
FORM_ORDER = (
|
||||||
|
"standard_tour_plan",
|
||||||
|
"tour_plan",
|
||||||
|
"fare_chart",
|
||||||
|
"sales_and_stock_statement",
|
||||||
|
"sales_projection",
|
||||||
|
"field_activity_report",
|
||||||
|
"expense_statement",
|
||||||
|
"area_covered",
|
||||||
|
"weekly_report",
|
||||||
|
"core_dr_call_conversion",
|
||||||
|
"daily_call_report_csv",
|
||||||
|
)
|
||||||
|
|
||||||
CSV_LABELS = {
|
CSV_LABELS = {
|
||||||
"weekly_report": "Weekly Report",
|
"weekly_report": "Weekly Report",
|
||||||
"field_activity_report": "Field Activity Report",
|
"field_activity_report": "Field Activity Report",
|
||||||
"fare_chart": "Fare Chart",
|
"fare_chart": "Fare Chart",
|
||||||
"daily_call_report_csv": "Daily Call Report CSV",
|
"daily_call_report_csv": "Daily Call Report CSV",
|
||||||
"core_dr_call_conversion": "Core Doctor Call Conversion",
|
"core_dr_call_conversion": "Core Doctor Call Conversion",
|
||||||
"area_covered": "Area Covered",
|
"area_covered": "Area Coverage",
|
||||||
"sales_and_stock_statement": "Sales and Stock Statement",
|
"sales_and_stock_statement": "Sales and Stock Statement",
|
||||||
"tour_plan": "Tour Plan",
|
"tour_plan": "Tour Plan",
|
||||||
"standard_tour_plan": "Standard Tour Plan",
|
"standard_tour_plan": "Standard Tour Plan",
|
||||||
"sales_projection": "Sales Projection",
|
"sales_projection": "Sales Projection",
|
||||||
|
"expense_statement": "Expense Statement",
|
||||||
}
|
}
|
||||||
+263
-23
@@ -3,17 +3,18 @@ import uuid
|
|||||||
from collections.abc import Iterable
|
from collections.abc import Iterable
|
||||||
from zoneinfo import ZoneInfo
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
from fastapi import APIRouter, Body, Depends, Query, status
|
from fastapi import APIRouter, Body, Depends, Query, Request, status
|
||||||
from fastapi.responses import Response
|
from fastapi.responses import Response
|
||||||
from sqlalchemy import select, text
|
from sqlalchemy import select, text
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.auth.dependencies import require_role
|
from app.audit.service import AuditService
|
||||||
from app.common.enums import Role
|
from app.auth.dependencies import client_ip, require_role
|
||||||
|
from app.common.enums import AuditAction, EntityType, Role, FIELD_ROLES
|
||||||
from app.common.exceptions import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
from app.common.exceptions import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||||
from app.config.settings import settings
|
from app.config.settings import settings
|
||||||
from app.csv_data import approval as approvals
|
from app.csv_data import approval as approvals
|
||||||
from app.csv_data.config import CSV_LABELS, TABLES
|
from app.csv_data.config import CSV_LABELS, FORM_ORDER, TABLES
|
||||||
from app.database.session import get_db
|
from app.database.session import get_db
|
||||||
from app.users.models import User
|
from app.users.models import User
|
||||||
from app.organization.models import Headquarters
|
from app.organization.models import Headquarters
|
||||||
@@ -62,7 +63,11 @@ async def _reject_repeat(
|
|||||||
#: Tables whose printed Sl. No. starts over at 1 for each month rather than running on
|
#: Tables whose printed Sl. No. starts over at 1 for each month rather than running on
|
||||||
#: forever — a shared master list (e.g. Sales Projection's product list) refilled every
|
#: forever — a shared master list (e.g. Sales Projection's product list) refilled every
|
||||||
#: month, not one MR's own running form.
|
#: month, not one MR's own running form.
|
||||||
MONTH_NUMBERED_TABLES = {"sales_projection"}
|
MONTH_NUMBERED_TABLES = {"sales_projection", "sales_and_stock_statement"}
|
||||||
|
#: Forms whose rows are the company's product list, shared by every MR. An MR may delete an extra
|
||||||
|
#: copy of a product (a row added by mistake), but never a product's only row — that would take
|
||||||
|
#: the product off everyone's list; they clear its figures instead (a PATCH). The admin may delete any.
|
||||||
|
PRODUCT_LIST_TABLES = {"sales_projection", "sales_and_stock_statement"}
|
||||||
|
|
||||||
|
|
||||||
async def _renumber_rows(table_name: str, db: AsyncSession) -> None:
|
async def _renumber_rows(table_name: str, db: AsyncSession) -> None:
|
||||||
@@ -98,7 +103,7 @@ async def _apply_mr_identity(
|
|||||||
values: dict[str, str | None], subject: User | None, db: AsyncSession
|
values: dict[str, str | None], subject: User | None, db: AsyncSession
|
||||||
) -> dict[str, str | None]:
|
) -> dict[str, str | None]:
|
||||||
"""Fill NAME / HEADQUARTER from the MR the row is for (the signed-in MR, or the one an admin picked)."""
|
"""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:
|
if subject is None or subject.role not in FIELD_ROLES:
|
||||||
return values
|
return values
|
||||||
headquarters_name = None
|
headquarters_name = None
|
||||||
if subject.headquarters_id:
|
if subject.headquarters_id:
|
||||||
@@ -120,7 +125,7 @@ async def _present_rows_for_user(
|
|||||||
Admins must see the source values and every row. MRs use the imported rows as
|
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.
|
their working data, but identity columns must always reflect the logged-in MR.
|
||||||
"""
|
"""
|
||||||
if current_user.role != Role.MR:
|
if current_user.role not in FIELD_ROLES:
|
||||||
return rows
|
return rows
|
||||||
|
|
||||||
headquarters_name = None
|
headquarters_name = None
|
||||||
@@ -168,6 +173,25 @@ async def _apply_sales_projection_product(
|
|||||||
return values
|
return values
|
||||||
|
|
||||||
|
|
||||||
|
#: Expense Statement: the TOTAL column is always fare + daily allowance + postage + other expenses.
|
||||||
|
EXPENSE_AMOUNTS = ("fare", "da_hq", "da_ex", "da_out", "postage", "other_expense")
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_expense_total(values: dict[str, str | None]) -> dict[str, str | None]:
|
||||||
|
total = 0.0
|
||||||
|
for column in EXPENSE_AMOUNTS:
|
||||||
|
raw = (values.get(column) or "").replace(",", "").strip()
|
||||||
|
if not raw:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
total += float(raw)
|
||||||
|
except ValueError:
|
||||||
|
raise ValidationError("Expense amounts must be numbers", {"column": column}) from None
|
||||||
|
has_amount = any((values.get(column) or "").strip() for column in EXPENSE_AMOUNTS)
|
||||||
|
values["total"] = f"{total:.2f}" if has_amount else None
|
||||||
|
return values
|
||||||
|
|
||||||
|
|
||||||
def _select(table_name: str, columns: Iterable[str]) -> str:
|
def _select(table_name: str, columns: Iterable[str]) -> str:
|
||||||
selected = ", ".join(f'"{column}"' for column in columns)
|
selected = ", ".join(f'"{column}"' for column in columns)
|
||||||
return f'SELECT id, source_row_number, {selected} FROM "{table_name}"'
|
return f'SELECT id, source_row_number, {selected} FROM "{table_name}"'
|
||||||
@@ -180,7 +204,7 @@ async def _owner_condition(
|
|||||||
an Area Manager only the MRs of their headquarters, an admin anyone (or one chosen MR)."""
|
an Area Manager only the MRs of their headquarters, an admin anyone (or one chosen MR)."""
|
||||||
if table_name not in OWNED_TABLES:
|
if table_name not in OWNED_TABLES:
|
||||||
return [], {}
|
return [], {}
|
||||||
if current_user.role == Role.MR:
|
if current_user.role in FIELD_ROLES:
|
||||||
if owner_id not in (None, current_user.id):
|
if owner_id not in (None, current_user.id):
|
||||||
raise ForbiddenError("You can only see your own forms")
|
raise ForbiddenError("You can only see your own forms")
|
||||||
return ["owner_user_id = :owner"], {"owner": current_user.id}
|
return ["owner_user_id = :owner"], {"owner": current_user.id}
|
||||||
@@ -194,13 +218,18 @@ async def _owner_condition(
|
|||||||
|
|
||||||
async def _row_owner(table_name: str, row_id: uuid.UUID, current_user: User, db: AsyncSession) -> uuid.UUID | None:
|
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."""
|
"""Who owns this row, after checking `current_user` is allowed to touch it."""
|
||||||
if table_name not in OWNED_TABLES:
|
if table_name not in OWNED_TABLES and table_name not in PER_MR_PRODUCT_TABLES:
|
||||||
return None
|
return None
|
||||||
found = (await db.execute(text(f'SELECT owner_user_id FROM "{table_name}" WHERE id = :id'), {"id": row_id})).first()
|
found = (await db.execute(text(f'SELECT owner_user_id FROM "{table_name}" WHERE id = :id'), {"id": row_id})).first()
|
||||||
if found is None:
|
if found is None:
|
||||||
raise NotFoundError("CSV row not found", {"id": str(row_id)})
|
raise NotFoundError("CSV row not found", {"id": str(row_id)})
|
||||||
owner_id = found[0]
|
owner_id = found[0]
|
||||||
if current_user.role == Role.MR and owner_id != current_user.id:
|
if table_name in PER_MR_PRODUCT_TABLES:
|
||||||
|
# A shared product line has no owner; only an MR's own row is theirs alone.
|
||||||
|
if current_user.role in FIELD_ROLES and owner_id not in (None, current_user.id):
|
||||||
|
raise ForbiddenError("This row belongs to another medical representative")
|
||||||
|
return owner_id
|
||||||
|
if current_user.role in FIELD_ROLES and owner_id != current_user.id:
|
||||||
raise ForbiddenError("This row belongs to another medical representative")
|
raise ForbiddenError("This row belongs to another medical representative")
|
||||||
if current_user.role == Role.AM:
|
if current_user.role == Role.AM:
|
||||||
if owner_id is None:
|
if owner_id is None:
|
||||||
@@ -221,6 +250,8 @@ async def _load_rows(
|
|||||||
table_name: str, db: AsyncSession, current_user: User, owner_id: uuid.UUID | None = None, month: str | None = None
|
table_name: str, db: AsyncSession, current_user: User, owner_id: uuid.UUID | None = None, month: str | None = None
|
||||||
) -> list[dict[str, object]]:
|
) -> list[dict[str, object]]:
|
||||||
columns = _table(table_name)
|
columns = _table(table_name)
|
||||||
|
if table_name in PER_MR_PRODUCT_TABLES:
|
||||||
|
return await _load_per_mr_rows(table_name, db, current_user, owner_id, month)
|
||||||
conditions, params = await _owner_condition(table_name, current_user, db, owner_id)
|
conditions, params = await _owner_condition(table_name, current_user, db, owner_id)
|
||||||
more, extra = _month_filter(table_name, month)
|
more, extra = _month_filter(table_name, month)
|
||||||
where = f" WHERE {' AND '.join(conditions + more)}" if conditions or more else ""
|
where = f" WHERE {' AND '.join(conditions + more)}" if conditions or more else ""
|
||||||
@@ -228,8 +259,116 @@ async def _load_rows(
|
|||||||
return await _present_rows_for_user([dict(row) for row in result.mappings().all()], current_user, db)
|
return await _present_rows_for_user([dict(row) for row in result.mappings().all()], current_user, db)
|
||||||
|
|
||||||
|
|
||||||
|
#: Product-list forms where every MR has their own figures. Rows with no owner are the shared
|
||||||
|
#: product list: an MR sees each product they have not started yet as a blank line, and their
|
||||||
|
#: first entry on it becomes their own row. A manager sees the MRs' rows, with the MR's name
|
||||||
|
#: and headquarters taken from the owner.
|
||||||
|
PER_MR_PRODUCT_TABLES = {"sales_projection", "sales_and_stock_statement"}
|
||||||
|
#: What an MR types in (and the month it belongs to): a product line with none of these is blank.
|
||||||
|
_FIGURES = {
|
||||||
|
"sales_projection": ("report_date", "month", "closing_qty", "closing_value", "projection_qty", "projection_value"),
|
||||||
|
"sales_and_stock_statement": ("report_date", "month", "opening", "receipt", "sale", "closing", "value_in_pts"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _product_key(row: dict[str, object]) -> str:
|
||||||
|
return str(row.get("product_name") or "").strip().upper()
|
||||||
|
|
||||||
|
|
||||||
|
def _has_figures(table_name: str, row: dict[str, object]) -> bool:
|
||||||
|
return any(str(row.get(c) or "").strip() for c in _FIGURES[table_name])
|
||||||
|
|
||||||
|
|
||||||
|
async def _view_owner(
|
||||||
|
table_name: str, db: AsyncSession, current_user: User, owner_id: uuid.UUID | None
|
||||||
|
) -> uuid.UUID | None:
|
||||||
|
"""The one MR whose copy is shown: the signed-in MR, or the one a manager picked."""
|
||||||
|
if current_user.role in FIELD_ROLES:
|
||||||
|
return current_user.id
|
||||||
|
if owner_id is None:
|
||||||
|
return None
|
||||||
|
await approvals.assert_owner_in_scope(db, current_user, owner_id)
|
||||||
|
return owner_id
|
||||||
|
|
||||||
|
|
||||||
|
async def _load_per_mr_rows(
|
||||||
|
table_name: str, db: AsyncSession, current_user: User, owner_id: uuid.UUID | None, month: str | None
|
||||||
|
) -> list[dict[str, object]]:
|
||||||
|
columns = _table(table_name)
|
||||||
|
selected = ", ".join(f'"{c}"' for c in columns)
|
||||||
|
result = await db.execute(
|
||||||
|
text(f'SELECT id, source_row_number, owner_user_id, {selected} FROM "{table_name}" ORDER BY source_row_number')
|
||||||
|
)
|
||||||
|
everything = [dict(r) for r in result.mappings().all()]
|
||||||
|
mine = await _view_owner(table_name, db, current_user, owner_id)
|
||||||
|
owner_ids = {r["owner_user_id"] for r in everything if r["owner_user_id"]} | ({mine} if mine else set())
|
||||||
|
people: dict[uuid.UUID, tuple[str, str | None]] = {}
|
||||||
|
if owner_ids:
|
||||||
|
found = await db.execute(
|
||||||
|
select(User.id, User.full_name, Headquarters.name)
|
||||||
|
.outerjoin(Headquarters, Headquarters.id == User.headquarters_id)
|
||||||
|
.where(User.id.in_(owner_ids))
|
||||||
|
)
|
||||||
|
people = {uid: (name, hq) for uid, name, hq in found.all()}
|
||||||
|
|
||||||
|
shown: list[dict[str, object]] = []
|
||||||
|
if mine is not None:
|
||||||
|
own = [r for r in everything if r["owner_user_id"] == mine]
|
||||||
|
started = {_product_key(r) for r in own}
|
||||||
|
for r in everything:
|
||||||
|
if r["owner_user_id"] is None and _product_key(r) not in started:
|
||||||
|
shown.append({**r, **{c: None for c in _FIGURES[table_name]}}) # a blank line of the product list
|
||||||
|
shown += own
|
||||||
|
else:
|
||||||
|
# A manager gets every MR's rows plus the shared product list (the page lays the list out).
|
||||||
|
shown = everything
|
||||||
|
# A row an MR starts on a product keeps that product's place in the list, whenever it was
|
||||||
|
# created; a manager reading several MRs sees them one MR after another.
|
||||||
|
place: dict[str, int] = {}
|
||||||
|
for r in everything:
|
||||||
|
if r["owner_user_id"] is None:
|
||||||
|
place[_product_key(r)] = min(place.get(_product_key(r), r["source_row_number"]), r["source_row_number"])
|
||||||
|
def order(r: dict[str, object]) -> tuple:
|
||||||
|
who = people.get(r["owner_user_id"], ("", None))[0] if mine is None else ""
|
||||||
|
return (who, place.get(_product_key(r), r["source_row_number"]), r["source_row_number"])
|
||||||
|
shown.sort(key=order)
|
||||||
|
|
||||||
|
wanted = (month or "").strip().lower()
|
||||||
|
out: list[dict[str, object]] = []
|
||||||
|
for r in shown:
|
||||||
|
if wanted and str(r.get("month") or "").strip().lower() != wanted:
|
||||||
|
continue
|
||||||
|
item = {k: v for k, v in r.items() if k != "owner_user_id"}
|
||||||
|
who = r["owner_user_id"] or mine # a blank product line is shown as that MR's own
|
||||||
|
if who in people:
|
||||||
|
item["name"], item["headquarter"] = people[who][0], people[who][1] or ""
|
||||||
|
out.append(item)
|
||||||
|
return await _present_rows_for_user(out, current_user, db)
|
||||||
|
|
||||||
|
|
||||||
|
def _month_of_every_product(rows: list[dict[str, object]], month: str, columns: Iterable[str]) -> list[dict[str, object]]:
|
||||||
|
"""A product-list form for one month: every product once — its row for that month, else its
|
||||||
|
still-unused blank row, else an empty line carrying only the product — so the printed form
|
||||||
|
always lists the whole range, filled in where this month has figures."""
|
||||||
|
wanted = month.strip().lower()
|
||||||
|
key = lambda r: str(r.get("product_name") or "").strip().upper() # noqa: E731
|
||||||
|
copies: dict[str, list[dict[str, object]]] = {}
|
||||||
|
for row in rows:
|
||||||
|
if key(row):
|
||||||
|
copies.setdefault(key(row), []).append(row)
|
||||||
|
out: list[dict[str, object]] = []
|
||||||
|
for product, group in copies.items():
|
||||||
|
mine = next((r for r in group if str(r.get("month") or "").strip().lower() == wanted), None) or next(
|
||||||
|
(r for r in group if not str(r.get("month") or "").strip()), None
|
||||||
|
)
|
||||||
|
if mine is None:
|
||||||
|
mine = {c: group[0].get(c) for c in ("product_name", "pts", "value_in_pts", "name", "headquarter") if c in set(columns)}
|
||||||
|
out.append({**mine, "month": month.strip()})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def _available_csv_tables(current_user: User) -> list[str]:
|
def _available_csv_tables(current_user: User) -> list[str]:
|
||||||
visible = [name for name in TABLES if name not in HIDDEN_TABLES]
|
visible = [name for name in FORM_ORDER if name not in HIDDEN_TABLES]
|
||||||
if current_user.role == Role.AM:
|
if current_user.role == Role.AM:
|
||||||
return [name for name in visible if name in APPROVAL_TABLES]
|
return [name for name in visible if name in APPROVAL_TABLES]
|
||||||
return visible
|
return visible
|
||||||
@@ -243,7 +382,7 @@ def _ensure_table_access(table_name: str, current_user: User) -> None:
|
|||||||
|
|
||||||
|
|
||||||
@router.get("/tables")
|
@router.get("/tables")
|
||||||
async def list_csv_tables(current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM))) -> list[dict[str, object]]:
|
async def list_csv_tables(current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM))) -> list[dict[str, object]]:
|
||||||
return [{"name": name, "label": CSV_LABELS[name], "columns": list(TABLES[name])} for name in _available_csv_tables(current_user)]
|
return [{"name": name, "label": CSV_LABELS[name], "columns": list(TABLES[name])} for name in _available_csv_tables(current_user)]
|
||||||
|
|
||||||
|
|
||||||
@@ -288,7 +427,7 @@ def _approval_table(table_name: str) -> str:
|
|||||||
@router.get("/approvals")
|
@router.get("/approvals")
|
||||||
async def list_form_approvals(
|
async def list_form_approvals(
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM)),
|
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM)),
|
||||||
) -> list[dict[str, object]]:
|
) -> list[dict[str, object]]:
|
||||||
"""Approval state of the forms that carry an Area Manager signature, limited to the MRs this user may see."""
|
"""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)]
|
return [_approval_out(r, owner, hq) for r, owner, hq in await approvals.list_approvals(db, current_user)]
|
||||||
@@ -297,7 +436,7 @@ async def list_form_approvals(
|
|||||||
@router.get("/owners")
|
@router.get("/owners")
|
||||||
async def list_form_owners(
|
async def list_form_owners(
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM)),
|
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM)),
|
||||||
) -> list[dict[str, object]]:
|
) -> list[dict[str, object]]:
|
||||||
"""The medical representatives whose forms this user may open."""
|
"""The medical representatives whose forms this user may open."""
|
||||||
hq = {h.id: h.name for h in (await db.execute(select(Headquarters))).scalars()}
|
hq = {h.id: h.name for h in (await db.execute(select(Headquarters))).scalars()}
|
||||||
@@ -336,7 +475,7 @@ async def list_csv_rows(
|
|||||||
table_name: str,
|
table_name: str,
|
||||||
owner_id: uuid.UUID | None = None,
|
owner_id: uuid.UUID | None = None,
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM)),
|
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM)),
|
||||||
) -> list[dict[str, object]]:
|
) -> list[dict[str, object]]:
|
||||||
_ensure_table_access(table_name, current_user)
|
_ensure_table_access(table_name, current_user)
|
||||||
return await _load_rows(table_name, db, current_user, owner_id)
|
return await _load_rows(table_name, db, current_user, owner_id)
|
||||||
@@ -354,15 +493,19 @@ async def create_csv_row(
|
|||||||
values = _clean_payload(table_name, payload)
|
values = _clean_payload(table_name, payload)
|
||||||
owner: User | None = None
|
owner: User | None = None
|
||||||
if table_name in OWNED_TABLES:
|
if table_name in OWNED_TABLES:
|
||||||
if current_user.role == Role.MR:
|
if current_user.role in FIELD_ROLES:
|
||||||
owner = current_user
|
owner = current_user
|
||||||
elif owner_id is None:
|
elif owner_id is None:
|
||||||
raise ValidationError("Choose which medical representative this row is for")
|
raise ValidationError("Choose which medical representative this row is for")
|
||||||
else:
|
else:
|
||||||
owner = await approvals.assert_owner_in_scope(db, current_user, owner_id)
|
owner = await approvals.assert_owner_in_scope(db, current_user, owner_id)
|
||||||
|
if owner is None and table_name in PER_MR_PRODUCT_TABLES and current_user.role in FIELD_ROLES:
|
||||||
|
owner = current_user
|
||||||
values = await _apply_mr_identity(values, owner or current_user, db)
|
values = await _apply_mr_identity(values, owner or current_user, db)
|
||||||
if table_name == "sales_projection":
|
if table_name == "sales_projection":
|
||||||
values = await _apply_sales_projection_product(values, db, current_user)
|
values = await _apply_sales_projection_product(values, db, current_user)
|
||||||
|
if table_name == "expense_statement":
|
||||||
|
values = _apply_expense_total(values)
|
||||||
if not _has_user_data(table_name, values):
|
if not _has_user_data(table_name, values):
|
||||||
raise ValidationError("Add at least one value before creating a row")
|
raise ValidationError("Add at least one value before creating a row")
|
||||||
await _reject_repeat(table_name, values, db, owner.id if owner else None)
|
await _reject_repeat(table_name, values, db, owner.id if owner else None)
|
||||||
@@ -384,17 +527,65 @@ async def create_csv_row(
|
|||||||
return await _get_row(table_name, row_id, db)
|
return await _get_row(table_name, row_id, db)
|
||||||
|
|
||||||
|
|
||||||
|
async def _stored_owner(table_name: str, row_id: uuid.UUID, db: AsyncSession) -> uuid.UUID | 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)})
|
||||||
|
return found[0]
|
||||||
|
|
||||||
|
|
||||||
|
async def _start_own_row(
|
||||||
|
table_name: str, shared: dict[str, object], values: dict[str, str | None],
|
||||||
|
payload: dict[str, object], db: AsyncSession, current_user: User,
|
||||||
|
) -> dict[str, object]:
|
||||||
|
"""An MR's first entry on a product of the shared list: it becomes their own row, so the
|
||||||
|
shared line stays blank for everyone else."""
|
||||||
|
columns = _table(table_name)
|
||||||
|
new = {c: None for c in columns}
|
||||||
|
for c in ("product_name", "pts"):
|
||||||
|
if c in new:
|
||||||
|
new[c] = shared.get(c)
|
||||||
|
new.update({c: v for c, v in values.items() if c in payload and c not in SERIAL_COLUMNS})
|
||||||
|
new = await _apply_mr_identity(new, current_user, db)
|
||||||
|
if not _has_user_data(table_name, new):
|
||||||
|
raise ValidationError("A row must contain at least one value")
|
||||||
|
next_row = (await db.execute(text(f'SELECT COALESCE(MAX(source_row_number), 0) + 1 FROM "{table_name}"'))).scalar_one()
|
||||||
|
for c in columns:
|
||||||
|
if c in SERIAL_COLUMNS:
|
||||||
|
new[c] = str(next_row)
|
||||||
|
names = ", ".join(["id", "source_row_number", "owner_user_id", *[f'"{c}"' for c in columns]])
|
||||||
|
params = ", ".join([":id", ":source_row_number", ":owner_user_id", *[f":{c}" for c in columns]])
|
||||||
|
row_id = uuid.uuid4()
|
||||||
|
await db.execute(
|
||||||
|
text(f'INSERT INTO "{table_name}" ({names}) VALUES ({params})'),
|
||||||
|
{**new, "id": row_id, "source_row_number": next_row, "owner_user_id": current_user.id},
|
||||||
|
)
|
||||||
|
await _renumber_rows(table_name, db)
|
||||||
|
await db.commit()
|
||||||
|
return await _get_row(table_name, row_id, db)
|
||||||
|
|
||||||
|
|
||||||
@router.patch("/{table_name}/rows/{row_id}")
|
@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]:
|
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)
|
values = _clean_payload(table_name, payload)
|
||||||
|
if table_name in PER_MR_PRODUCT_TABLES and current_user.role in FIELD_ROLES:
|
||||||
|
shared = await _get_row(table_name, row_id, db)
|
||||||
|
if await _stored_owner(table_name, row_id, db) is None:
|
||||||
|
return await _start_own_row(table_name, shared, values, payload, db, current_user)
|
||||||
row_owner = await _row_owner(table_name, row_id, current_user, db)
|
row_owner = await _row_owner(table_name, row_id, current_user, db)
|
||||||
values = await _apply_mr_identity(values, current_user, db)
|
values = await _apply_mr_identity(values, current_user, db)
|
||||||
if table_name == "sales_projection":
|
if table_name == "sales_projection":
|
||||||
values = await _apply_sales_projection_product(values, db, current_user)
|
values = await _apply_sales_projection_product(values, db, current_user)
|
||||||
changes = {column: value for column, value in values.items() if column in payload}
|
changes = {column: value for column, value in values.items() if column in payload}
|
||||||
|
stored = await _get_row(table_name, row_id, db)
|
||||||
|
if table_name == "expense_statement" and any(column in payload for column in (*EXPENSE_AMOUNTS, "total")):
|
||||||
|
merged = {c: (changes[c] if c in changes else stored.get(c)) for c in EXPENSE_AMOUNTS}
|
||||||
|
changes["total"] = _apply_expense_total(merged)["total"]
|
||||||
if not changes:
|
if not changes:
|
||||||
raise ValidationError("At least one CSV column is required")
|
raise ValidationError("At least one CSV column is required")
|
||||||
if not _has_user_data(table_name, {**values, **changes}):
|
# Judged on the whole row as it will be stored, not only the columns sent: clearing
|
||||||
|
# one cell of a row that still has other values is a normal edit.
|
||||||
|
if not _has_user_data(table_name, {**{c: stored.get(c) for c in _table(table_name)}, **changes}):
|
||||||
raise ValidationError("A row must contain at least one value")
|
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}
|
changes = {column: value for column, value in changes.items() if column not in SERIAL_COLUMNS}
|
||||||
if not changes:
|
if not changes:
|
||||||
@@ -409,12 +600,56 @@ async def update_csv_row(table_name: str, row_id: uuid.UUID, payload: dict[str,
|
|||||||
|
|
||||||
|
|
||||||
@router.delete("/{table_name}/rows/{row_id}", status_code=status.HTTP_204_NO_CONTENT)
|
@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.ADMIN))) -> None:
|
async def delete_csv_row(
|
||||||
|
table_name: str,
|
||||||
|
row_id: uuid.UUID,
|
||||||
|
request: Request,
|
||||||
|
confirm: str | None = Query(default=None, description="The product's name, to remove a product's last row"),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_role(Role.MR, Role.ADMIN)),
|
||||||
|
) -> None:
|
||||||
|
"""Remove a row entered by mistake. An MR may remove only their own rows (checked by _row_owner).
|
||||||
|
|
||||||
|
On a shared product list, a product's last row takes the product off everyone's list: an MR
|
||||||
|
may not remove it at all, and the administrator must name the product in `confirm`. Every
|
||||||
|
removal is written to the audit log with the whole row, so it can be put back by hand."""
|
||||||
_table(table_name)
|
_table(table_name)
|
||||||
row_owner = await _row_owner(table_name, row_id, current_user, db)
|
row_owner = await _row_owner(table_name, row_id, current_user, db)
|
||||||
|
row = await _get_row(table_name, row_id, db)
|
||||||
|
if table_name in PRODUCT_LIST_TABLES:
|
||||||
|
product = str(row.get("product_name") or "").strip()
|
||||||
|
copies = (
|
||||||
|
await db.execute(
|
||||||
|
text(
|
||||||
|
f'SELECT COUNT(*) FROM "{table_name}" '
|
||||||
|
"WHERE upper(btrim(COALESCE(product_name, ''))) = upper(:product)"
|
||||||
|
+ (" AND owner_user_id IS NOT DISTINCT FROM :owner" if table_name in PER_MR_PRODUCT_TABLES else "")
|
||||||
|
),
|
||||||
|
{"product": product, **({"owner": row_owner} if table_name in PER_MR_PRODUCT_TABLES else {})},
|
||||||
|
)
|
||||||
|
).scalar_one()
|
||||||
|
if copies < 2:
|
||||||
|
if current_user.role in FIELD_ROLES:
|
||||||
|
raise ForbiddenError(
|
||||||
|
"This is the product's only row, so it stays in the list. Clear its figures instead.",
|
||||||
|
{"table": table_name},
|
||||||
|
)
|
||||||
|
if (confirm or "").strip().upper() != product.upper():
|
||||||
|
raise ValidationError(
|
||||||
|
"Type the product's name to confirm removing it from everyone's list",
|
||||||
|
{"product_name": product},
|
||||||
|
)
|
||||||
result = await db.execute(text(f'DELETE FROM "{table_name}" WHERE id = :id'), {"id": row_id})
|
result = await db.execute(text(f'DELETE FROM "{table_name}" WHERE id = :id'), {"id": row_id})
|
||||||
if result.rowcount == 0:
|
if result.rowcount == 0:
|
||||||
raise NotFoundError("CSV row not found", {"id": str(row_id)})
|
raise NotFoundError("CSV row not found", {"id": str(row_id)})
|
||||||
|
await AuditService(db).log(
|
||||||
|
actor_user_id=current_user.id,
|
||||||
|
entity_type=EntityType.FORM_ROW,
|
||||||
|
entity_id=row_id,
|
||||||
|
action=AuditAction.DELETE,
|
||||||
|
before={"table": table_name, **{k: (str(v) if isinstance(v, uuid.UUID) else v) for k, v in row.items()}},
|
||||||
|
ip_address=client_ip(request),
|
||||||
|
)
|
||||||
await _renumber_rows(table_name, db)
|
await _renumber_rows(table_name, db)
|
||||||
await approvals.invalidate(db, table_name, row_owner)
|
await approvals.invalidate(db, table_name, row_owner)
|
||||||
await db.commit()
|
await db.commit()
|
||||||
@@ -454,7 +689,7 @@ async def download_csv_row_pdf(
|
|||||||
table_name: str,
|
table_name: str,
|
||||||
row_id: uuid.UUID,
|
row_id: uuid.UUID,
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM)),
|
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM)),
|
||||||
) -> Response:
|
) -> Response:
|
||||||
_ensure_table_access(table_name, current_user)
|
_ensure_table_access(table_name, current_user)
|
||||||
row_owner = await _row_owner(table_name, row_id, current_user, db)
|
row_owner = await _row_owner(table_name, row_id, current_user, db)
|
||||||
@@ -474,23 +709,28 @@ async def download_csv_table_pdfs(
|
|||||||
owner_id: uuid.UUID | None = None,
|
owner_id: uuid.UUID | None = None,
|
||||||
month: str | None = None,
|
month: str | None = None,
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM)),
|
current_user: User = Depends(require_role(Role.MR, Role.ADMIN, Role.AM, Role.GM)),
|
||||||
) -> Response:
|
) -> Response:
|
||||||
"""The whole form, or only one month of it (for the forms that have a month)."""
|
"""The whole form, or only one month of it (for the forms that have a month)."""
|
||||||
_ensure_table_access(table_name, current_user)
|
_ensure_table_access(table_name, current_user)
|
||||||
columns = _table(table_name)
|
columns = _table(table_name)
|
||||||
rows = await _load_rows(table_name, db, current_user, owner_id, month)
|
whole_range = table_name in PRODUCT_LIST_TABLES and bool(month and month.strip())
|
||||||
|
if table_name in PER_MR_PRODUCT_TABLES and await _view_owner(table_name, db, current_user, owner_id) is None:
|
||||||
|
whole_range = False # several MRs together: print the rows that exist, not one line per product
|
||||||
|
rows = await _load_rows(table_name, db, current_user, owner_id, None if whole_range else month)
|
||||||
|
if whole_range and month:
|
||||||
|
rows = _month_of_every_product(rows, month, columns)
|
||||||
if month and month.strip() and not rows:
|
if month and month.strip() and not rows:
|
||||||
raise NotFoundError(f"There are no rows for {month.strip()} in this form", {"month": month})
|
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.
|
# 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
|
subject = current_user.id if current_user.role in FIELD_ROLES else owner_id
|
||||||
approval_status, am_name, approved_at = await _signature(table_name, subject, db)
|
approval_status, am_name, approved_at = await _signature(table_name, subject, db)
|
||||||
from app.pdf.service import csv_table_pdf_bytes
|
from app.pdf.service import csv_table_pdf_bytes
|
||||||
suffix = re.sub(r"[^a-z]", "", month.lower()) if month else ""
|
suffix = re.sub(r"[^a-z]", "", month.lower()) if month else ""
|
||||||
filename = f"{table_name}-{suffix}.pdf" if suffix else f"{table_name}.pdf"
|
filename = f"{table_name}-{suffix}.pdf" if suffix else f"{table_name}.pdf"
|
||||||
# Printing every month together: a month-numbered table's stored Sl. No. (1, 2… 1, 2…)
|
# Printing every month together: a month-numbered table's stored Sl. No. (1, 2… 1, 2…)
|
||||||
# would repeat, so it is recomputed as one running count over what is actually printed.
|
# would repeat, so it is recomputed as one running count over what is actually printed.
|
||||||
renumber = table_name in MONTH_NUMBERED_TABLES and not (month and month.strip())
|
renumber = table_name in MONTH_NUMBERED_TABLES and (not (month and month.strip()) or whole_range)
|
||||||
pdf = csv_table_pdf_bytes(
|
pdf = csv_table_pdf_bytes(
|
||||||
table_name,
|
table_name,
|
||||||
CSV_LABELS[table_name],
|
CSV_LABELS[table_name],
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ from app.database.base import Base
|
|||||||
from app.doctors.models import Doctor, DoctorAssignment
|
from app.doctors.models import Doctor, DoctorAssignment
|
||||||
from app.organization.models import AMHeadquarters, Company, Headquarters
|
from app.organization.models import AMHeadquarters, Company, Headquarters
|
||||||
from app.products.models import Product
|
from app.products.models import Product
|
||||||
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall
|
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall, MissedVisit
|
||||||
from app.users.models import User
|
from app.users.models import User, UserExtraHeadquarters # noqa: F401
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"Base",
|
"Base",
|
||||||
@@ -31,6 +31,7 @@ __all__ = [
|
|||||||
"ChemistCall",
|
"ChemistCall",
|
||||||
"DailyCallReport",
|
"DailyCallReport",
|
||||||
"DoctorCall",
|
"DoctorCall",
|
||||||
|
"MissedVisit",
|
||||||
"User",
|
"User",
|
||||||
"Product",
|
"Product",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ from sqlalchemy import Boolean, Date, ForeignKey, Index, String, UniqueConstrain
|
|||||||
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
||||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
|
from app.common.enums import MasterApproval
|
||||||
from app.database.base import Base, TimestampMixin, UUIDMixin
|
from app.database.base import Base, TimestampMixin, UUIDMixin
|
||||||
|
|
||||||
|
|
||||||
@@ -35,9 +36,26 @@ class Doctor(Base, UUIDMixin, TimestampMixin):
|
|||||||
qualification: 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)
|
clinic_address: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||||
contact_number: Mapped[str | None] = mapped_column(String(20))
|
contact_number: Mapped[str | None] = mapped_column(String(20))
|
||||||
|
date_of_birth: Mapped[date | None] = mapped_column(Date)
|
||||||
#: Core doctors are the high-value targets tracked for conversion.
|
#: Core doctors are the high-value targets tracked for conversion.
|
||||||
is_core_doctor: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
is_core_doctor: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||||
|
#: PENDING until the Area Manager approves one an MR added; only APPROVED ones are listed or visited.
|
||||||
|
approval_status: Mapped[str] = mapped_column(
|
||||||
|
String(10), default=MasterApproval.APPROVED.value, server_default=MasterApproval.APPROVED.value, nullable=False
|
||||||
|
)
|
||||||
|
#: The MR who asked for it (None for one the administrator created).
|
||||||
|
requested_by_user_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="SET NULL")
|
||||||
|
)
|
||||||
|
rejection_reason: Mapped[str | None] = mapped_column(String(500))
|
||||||
|
requested_by: Mapped["User | None"] = relationship( # noqa: F821
|
||||||
|
lazy="selectin", foreign_keys=[requested_by_user_id]
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def requested_by_name(self) -> str | None:
|
||||||
|
return self.requested_by.full_name if self.requested_by else None
|
||||||
|
|
||||||
assignments: Mapped[list["DoctorAssignment"]] = relationship(back_populates="doctor")
|
assignments: Mapped[list["DoctorAssignment"]] = relationship(back_populates="doctor")
|
||||||
|
|
||||||
|
|||||||
+34
-3
@@ -7,7 +7,7 @@ from app.auth.dependencies import client_ip, get_current_user, require_role
|
|||||||
from app.common.enums import Role
|
from app.common.enums import Role
|
||||||
from app.database.session import get_db
|
from app.database.session import get_db
|
||||||
from app.doctors.models import Doctor
|
from app.doctors.models import Doctor
|
||||||
from app.doctors.schemas import AssignToMR, DoctorCreate, DoctorRead, DoctorUpdate
|
from app.doctors.schemas import AssignToMR, DoctorCreate, DoctorRead, DoctorUpdate, RejectMaster
|
||||||
from app.doctors.service import DoctorService
|
from app.doctors.service import DoctorService
|
||||||
from app.users.models import User
|
from app.users.models import User
|
||||||
|
|
||||||
@@ -26,10 +26,10 @@ async def list_doctors(
|
|||||||
async def create_doctor(
|
async def create_doctor(
|
||||||
payload: DoctorCreate,
|
payload: DoctorCreate,
|
||||||
request: Request,
|
request: Request,
|
||||||
current_user: User = Depends(require_role(Role.ADMIN)),
|
current_user: User = Depends(require_role(Role.ADMIN, Role.MR)),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> Doctor:
|
) -> Doctor:
|
||||||
"""Only an Administrator can create a doctor (MR, AM and GM cannot)."""
|
"""An Administrator, or an MR within their own headquarters (AM and GM cannot)."""
|
||||||
return await DoctorService(db).create(payload, current_user, client_ip(request))
|
return await DoctorService(db).create(payload, current_user, client_ip(request))
|
||||||
|
|
||||||
|
|
||||||
@@ -62,3 +62,34 @@ async def assign_doctor(
|
|||||||
"mr_user_id": assignment.mr_user_id,
|
"mr_user_id": assignment.mr_user_id,
|
||||||
"effective_from": assignment.effective_from,
|
"effective_from": assignment.effective_from,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/requests", response_model=list[DoctorRead])
|
||||||
|
async def list_doctor_requests(
|
||||||
|
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
||||||
|
) -> list[Doctor]:
|
||||||
|
"""Doctors an MR added that wait for the Area Manager: an MR sees their own (with any
|
||||||
|
rejected and why), an Area Manager what waits for them, the administrator and GM all."""
|
||||||
|
return await DoctorService(db).requests_for(current_user)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{doctor_id}/approve", response_model=DoctorRead)
|
||||||
|
async def approve_doctor(
|
||||||
|
doctor_id: uuid.UUID,
|
||||||
|
request: Request,
|
||||||
|
current_user: User = Depends(require_role(Role.AM, Role.ADMIN)),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> Doctor:
|
||||||
|
"""The Area Manager of its headquarters adds it to the list, assigned to the MR who asked."""
|
||||||
|
return await DoctorService(db).review(doctor_id, True, None, current_user, client_ip(request))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{doctor_id}/reject", response_model=DoctorRead)
|
||||||
|
async def reject_doctor(
|
||||||
|
doctor_id: uuid.UUID,
|
||||||
|
payload: RejectMaster,
|
||||||
|
request: Request,
|
||||||
|
current_user: User = Depends(require_role(Role.AM, Role.ADMIN)),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> Doctor:
|
||||||
|
return await DoctorService(db).review(doctor_id, False, payload.reason, current_user, client_ip(request))
|
||||||
|
|||||||
+26
-2
@@ -1,7 +1,13 @@
|
|||||||
import uuid
|
import uuid
|
||||||
from datetime import date
|
from datetime import date, datetime
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field
|
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||||
|
|
||||||
|
|
||||||
|
def _not_in_future(value: date | None) -> date | None:
|
||||||
|
if value is not None and value > date.today():
|
||||||
|
raise ValueError("date_of_birth cannot be in the future")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
class DoctorCreate(BaseModel):
|
class DoctorCreate(BaseModel):
|
||||||
@@ -11,8 +17,11 @@ class DoctorCreate(BaseModel):
|
|||||||
speciality: str | None = Field(default=None, max_length=100)
|
speciality: str | None = Field(default=None, max_length=100)
|
||||||
qualification: 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)
|
contact_number: str | None = Field(default=None, max_length=20)
|
||||||
|
date_of_birth: date | None = None
|
||||||
is_core_doctor: bool = False
|
is_core_doctor: bool = False
|
||||||
|
|
||||||
|
_check_dob = field_validator("date_of_birth")(_not_in_future)
|
||||||
|
|
||||||
|
|
||||||
class DoctorUpdate(BaseModel):
|
class DoctorUpdate(BaseModel):
|
||||||
name: str | None = Field(default=None, min_length=2, max_length=200)
|
name: str | None = Field(default=None, min_length=2, max_length=200)
|
||||||
@@ -20,9 +29,12 @@ class DoctorUpdate(BaseModel):
|
|||||||
speciality: str | None = Field(default=None, max_length=100)
|
speciality: str | None = Field(default=None, max_length=100)
|
||||||
qualification: 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)
|
contact_number: str | None = Field(default=None, max_length=20)
|
||||||
|
date_of_birth: date | None = None
|
||||||
is_core_doctor: bool | None = None
|
is_core_doctor: bool | None = None
|
||||||
is_active: bool | None = None
|
is_active: bool | None = None
|
||||||
|
|
||||||
|
_check_dob = field_validator("date_of_birth")(_not_in_future)
|
||||||
|
|
||||||
|
|
||||||
class DoctorRead(BaseModel):
|
class DoctorRead(BaseModel):
|
||||||
model_config = ConfigDict(from_attributes=True)
|
model_config = ConfigDict(from_attributes=True)
|
||||||
@@ -34,10 +46,22 @@ class DoctorRead(BaseModel):
|
|||||||
speciality: str | None
|
speciality: str | None
|
||||||
qualification: str | None
|
qualification: str | None
|
||||||
contact_number: str | None
|
contact_number: str | None
|
||||||
|
date_of_birth: date | None
|
||||||
is_core_doctor: bool
|
is_core_doctor: bool
|
||||||
is_active: bool
|
is_active: bool
|
||||||
|
#: PENDING / APPROVED / REJECTED — see app/common/master_approval.py.
|
||||||
|
approval_status: str
|
||||||
|
rejection_reason: str | None
|
||||||
|
requested_by_name: str | None
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
|
||||||
class AssignToMR(BaseModel):
|
class AssignToMR(BaseModel):
|
||||||
mr_user_id: uuid.UUID
|
mr_user_id: uuid.UUID
|
||||||
effective_from: date | None = None
|
effective_from: date | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class RejectMaster(BaseModel):
|
||||||
|
"""Why the Area Manager refused a doctor or chemist an MR added — shown to that MR."""
|
||||||
|
|
||||||
|
reason: str = Field(min_length=3, max_length=500)
|
||||||
|
|||||||
+69
-8
@@ -7,14 +7,22 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||||||
|
|
||||||
from app.audit.service import AuditService
|
from app.audit.service import AuditService
|
||||||
from app.auth.dependencies import assert_can_view_hq, visible_hq_ids
|
from app.auth.dependencies import assert_can_view_hq, visible_hq_ids
|
||||||
from app.common.enums import AuditAction, EntityType, Role
|
from app.common import master_approval
|
||||||
|
from app.common.enums import AuditAction, EntityType, MasterApproval, Role, FIELD_ROLES
|
||||||
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
|
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
|
||||||
from app.common.utils import snapshot
|
from app.common.utils import snapshot
|
||||||
from app.doctors.models import Doctor, DoctorAssignment
|
from app.doctors.models import Doctor, DoctorAssignment
|
||||||
from app.doctors.schemas import DoctorCreate, DoctorUpdate
|
from app.doctors.schemas import DoctorCreate, DoctorUpdate
|
||||||
from app.users.models import User
|
from app.users.models import User
|
||||||
|
|
||||||
_AUDIT_FIELDS = ["name", "clinic_address", "speciality", "is_core_doctor", "is_active"]
|
_AUDIT_FIELDS = [
|
||||||
|
"name",
|
||||||
|
"clinic_address",
|
||||||
|
"speciality",
|
||||||
|
"date_of_birth",
|
||||||
|
"is_core_doctor",
|
||||||
|
"is_active",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
class DoctorService:
|
class DoctorService:
|
||||||
@@ -23,10 +31,35 @@ class DoctorService:
|
|||||||
self.audit = AuditService(db)
|
self.audit = AuditService(db)
|
||||||
|
|
||||||
async def create(self, data: DoctorCreate, actor: User, ip: str | None = None) -> Doctor:
|
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.
|
# A2/A3 — masters belong to a headquarters. An MR may add one only to their own.
|
||||||
await assert_can_view_hq(self.db, actor, data.headquarters_id)
|
await assert_can_view_hq(self.db, actor, data.headquarters_id)
|
||||||
|
|
||||||
doctor = Doctor(**data.model_dump())
|
values = data.model_dump()
|
||||||
|
# Added by an MR: it waits for the Area Manager. One they were refused is sent again.
|
||||||
|
twin = None
|
||||||
|
if actor.role in FIELD_ROLES:
|
||||||
|
twin = await master_approval.rejected_twin(
|
||||||
|
self.db, Doctor, {k: values[k] for k in ('headquarters_id', 'name', 'clinic_address')}
|
||||||
|
)
|
||||||
|
if twin is not None:
|
||||||
|
await master_approval.resubmit(self.db, twin, values, actor, DoctorAssignment, "doctor_id")
|
||||||
|
await self.audit.log(
|
||||||
|
actor_user_id=actor.id,
|
||||||
|
entity_type=EntityType.DOCTOR,
|
||||||
|
entity_id=twin.id,
|
||||||
|
action=AuditAction.SUBMIT,
|
||||||
|
after=snapshot(twin, _AUDIT_FIELDS),
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
|
await self.db.commit()
|
||||||
|
await self.db.refresh(twin)
|
||||||
|
return twin
|
||||||
|
|
||||||
|
doctor = Doctor(
|
||||||
|
**values,
|
||||||
|
approval_status=master_approval.initial_status(actor),
|
||||||
|
requested_by_user_id=actor.id if actor.role in FIELD_ROLES else None,
|
||||||
|
)
|
||||||
self.db.add(doctor)
|
self.db.add(doctor)
|
||||||
try:
|
try:
|
||||||
await self.db.flush()
|
await self.db.flush()
|
||||||
@@ -45,7 +78,22 @@ class DoctorService:
|
|||||||
after=snapshot(doctor, _AUDIT_FIELDS),
|
after=snapshot(doctor, _AUDIT_FIELDS),
|
||||||
ip_address=ip,
|
ip_address=ip,
|
||||||
)
|
)
|
||||||
|
# An MR only sees assigned doctors, so the one they add is assigned to them.
|
||||||
|
if actor.role in FIELD_ROLES:
|
||||||
|
start = date.today()
|
||||||
|
self.db.add(
|
||||||
|
DoctorAssignment(doctor_id=doctor.id, mr_user_id=actor.id, effective_from=start)
|
||||||
|
)
|
||||||
|
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(actor.id), "effective_from": start.isoformat()},
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
await self.db.commit()
|
await self.db.commit()
|
||||||
|
await self.db.refresh(doctor)
|
||||||
return doctor
|
return doctor
|
||||||
|
|
||||||
async def update(
|
async def update(
|
||||||
@@ -74,7 +122,7 @@ class DoctorService:
|
|||||||
|
|
||||||
async def list_for(self, actor: User) -> list[Doctor]:
|
async def list_for(self, actor: User) -> list[Doctor]:
|
||||||
"""An MR sees ONLY doctors currently assigned to them (R5)."""
|
"""An MR sees ONLY doctors currently assigned to them (R5)."""
|
||||||
if actor.role == Role.MR:
|
if actor.role in FIELD_ROLES:
|
||||||
stmt = (
|
stmt = (
|
||||||
select(Doctor)
|
select(Doctor)
|
||||||
.join(DoctorAssignment, DoctorAssignment.doctor_id == Doctor.id)
|
.join(DoctorAssignment, DoctorAssignment.doctor_id == Doctor.id)
|
||||||
@@ -82,13 +130,14 @@ class DoctorService:
|
|||||||
DoctorAssignment.mr_user_id == actor.id,
|
DoctorAssignment.mr_user_id == actor.id,
|
||||||
DoctorAssignment.effective_to.is_(None),
|
DoctorAssignment.effective_to.is_(None),
|
||||||
Doctor.is_active.is_(True),
|
Doctor.is_active.is_(True),
|
||||||
|
Doctor.approval_status == MasterApproval.APPROVED,
|
||||||
)
|
)
|
||||||
.order_by(Doctor.name)
|
.order_by(Doctor.name)
|
||||||
)
|
)
|
||||||
return list((await self.db.execute(stmt)).scalars().all())
|
return list((await self.db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
allowed = await visible_hq_ids(self.db, actor)
|
allowed = await visible_hq_ids(self.db, actor)
|
||||||
stmt = select(Doctor).order_by(Doctor.name)
|
stmt = select(Doctor).where(Doctor.approval_status == MasterApproval.APPROVED).order_by(Doctor.name)
|
||||||
if allowed is not None:
|
if allowed is not None:
|
||||||
stmt = stmt.where(Doctor.headquarters_id.in_(allowed or [None]))
|
stmt = stmt.where(Doctor.headquarters_id.in_(allowed or [None]))
|
||||||
return list((await self.db.execute(stmt)).scalars().all())
|
return list((await self.db.execute(stmt)).scalars().all())
|
||||||
@@ -105,14 +154,16 @@ class DoctorService:
|
|||||||
if doctor is None:
|
if doctor is None:
|
||||||
raise NotFoundError("Doctor not found")
|
raise NotFoundError("Doctor not found")
|
||||||
await assert_can_view_hq(self.db, actor, doctor.headquarters_id)
|
await assert_can_view_hq(self.db, actor, doctor.headquarters_id)
|
||||||
|
if doctor.approval_status != MasterApproval.APPROVED:
|
||||||
|
raise ValidationError("This doctor is still waiting for the Area Manager's approval")
|
||||||
|
|
||||||
mr = await self.db.get(User, mr_user_id)
|
mr = await self.db.get(User, mr_user_id)
|
||||||
if mr is None:
|
if mr is None:
|
||||||
raise NotFoundError("MR not found")
|
raise NotFoundError("MR not found")
|
||||||
if mr.role != Role.MR:
|
if mr.role not in FIELD_ROLES:
|
||||||
raise ValidationError("Doctors can only be assigned to an MR")
|
raise ValidationError("Doctors can only be assigned to an MR")
|
||||||
# An MR may only be given doctors from their own headquarters.
|
# An MR may only be given doctors from their own headquarters.
|
||||||
if mr.headquarters_id != doctor.headquarters_id:
|
if doctor.headquarters_id not in mr.covered_headquarter_ids:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
"MR and doctor belong to different headquarters",
|
"MR and doctor belong to different headquarters",
|
||||||
{
|
{
|
||||||
@@ -150,3 +201,13 @@ class DoctorService:
|
|||||||
)
|
)
|
||||||
await self.db.commit()
|
await self.db.commit()
|
||||||
return assignment
|
return assignment
|
||||||
|
|
||||||
|
async def requests_for(self, actor: User) -> list[Doctor]:
|
||||||
|
return await master_approval.requests_for(self.db, Doctor, actor)
|
||||||
|
|
||||||
|
async def review(
|
||||||
|
self, doctor_id: uuid.UUID, approve: bool, reason: str | None, actor: User, ip: str | None = None
|
||||||
|
) -> Doctor:
|
||||||
|
return await master_approval.review(
|
||||||
|
self.db, Doctor, EntityType.DOCTOR, doctor_id, approve, reason, actor, ip
|
||||||
|
)
|
||||||
|
|||||||
@@ -56,15 +56,17 @@ class Headquarters(Base, UUIDMixin, TimestampMixin):
|
|||||||
class AMHeadquarters(Base, UUIDMixin, TimestampMixin):
|
class AMHeadquarters(Base, UUIDMixin, TimestampMixin):
|
||||||
"""Which Area Manager currently manages which headquarters.
|
"""Which Area Manager currently manages which headquarters.
|
||||||
|
|
||||||
`effective_to IS NULL` means "current". A partial unique index guarantees at most
|
`effective_to IS NULL` means "current". A headquarters may have several Area Managers
|
||||||
one active Area Manager per headquarters at any time.
|
and an Area Manager several headquarters; the partial unique index only stops the same
|
||||||
|
pair being active twice.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__tablename__ = "am_headquarters"
|
__tablename__ = "am_headquarters"
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
Index(
|
Index(
|
||||||
"uq_active_am_per_hq",
|
"uq_active_am_hq_pair",
|
||||||
"headquarters_id",
|
"headquarters_id",
|
||||||
|
"area_manager_user_id",
|
||||||
unique=True,
|
unique=True,
|
||||||
postgresql_where=text("effective_to IS NULL"),
|
postgresql_where=text("effective_to IS NULL"),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -81,9 +81,8 @@ class OrganizationService:
|
|||||||
) -> list[AMHeadquarters]:
|
) -> list[AMHeadquarters]:
|
||||||
"""Make `headquarters_ids` exactly the set of headquarters this AM manages.
|
"""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 missing from the list are released, new ones are added. Other Area
|
||||||
headquarters already has another AM, that mapping is closed first (one active AM
|
Managers of the same headquarters keep it: a headquarters may have several.
|
||||||
per headquarters stays true). An AM may manage any number of headquarters.
|
|
||||||
"""
|
"""
|
||||||
manager = await self.db.get(User, am_user_id)
|
manager = await self.db.get(User, am_user_id)
|
||||||
if manager is None or manager.company_id != actor.company_id:
|
if manager is None or manager.company_id != actor.company_id:
|
||||||
@@ -127,16 +126,6 @@ class OrganizationService:
|
|||||||
for hq_id in released:
|
for hq_id in released:
|
||||||
mine[hq_id].effective_to = start
|
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()
|
await self.db.flush()
|
||||||
|
|
||||||
for hq_id in added:
|
for hq_id in added:
|
||||||
@@ -176,10 +165,9 @@ class OrganizationService:
|
|||||||
actor: User,
|
actor: User,
|
||||||
ip: str | None = None,
|
ip: str | None = None,
|
||||||
) -> AMHeadquarters:
|
) -> AMHeadquarters:
|
||||||
"""Assign an AM to an HQ, closing any existing active mapping first.
|
"""Add an Area Manager to a headquarters, beside any it already has.
|
||||||
|
|
||||||
The partial unique index `uq_active_am_per_hq` is the real guarantee that only
|
Assigning the same pair twice changes nothing (`uq_active_am_hq_pair`).
|
||||||
one Area Manager is active per headquarters at a time.
|
|
||||||
"""
|
"""
|
||||||
hq = await self.db.get(Headquarters, headquarters_id)
|
hq = await self.db.get(Headquarters, headquarters_id)
|
||||||
if hq is None:
|
if hq is None:
|
||||||
@@ -207,8 +195,6 @@ class OrganizationService:
|
|||||||
for row in existing:
|
for row in existing:
|
||||||
if row.area_manager_user_id == am_user_id:
|
if row.area_manager_user_id == am_user_id:
|
||||||
return row
|
return row
|
||||||
row.effective_to = start
|
|
||||||
await self.db.flush()
|
|
||||||
|
|
||||||
mapping = AMHeadquarters(
|
mapping = AMHeadquarters(
|
||||||
area_manager_user_id=am_user_id,
|
area_manager_user_id=am_user_id,
|
||||||
|
|||||||
+248
-48
@@ -17,7 +17,7 @@ from dataclasses import dataclass
|
|||||||
from datetime import date
|
from datetime import date
|
||||||
|
|
||||||
DATE_FIELDS = {"report_date", "date_of_visit"}
|
DATE_FIELDS = {"report_date", "date_of_visit"}
|
||||||
APPROVAL_FORMS = {"standard_tour_plan", "tour_plan", "fare_chart"}
|
APPROVAL_FORMS = {"standard_tour_plan", "tour_plan", "fare_chart", "expense_statement"}
|
||||||
SERIAL = "#" # pseudo-field: the running "Sl.No." column
|
SERIAL = "#" # pseudo-field: the running "Sl.No." column
|
||||||
_ALIGN = {"left": "l", "center": "c", "right": "r"}
|
_ALIGN = {"left": "l", "center": "c", "right": "r"}
|
||||||
|
|
||||||
@@ -27,7 +27,7 @@ Meta = tuple[str, str] | None # (printed label, column) — None leaves the slo
|
|||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class Col:
|
class Col:
|
||||||
header: str
|
header: str # a "\n" starts a second line in the printed heading
|
||||||
field: str
|
field: str
|
||||||
width: float # percent of the table
|
width: float # percent of the table
|
||||||
align: str = "left"
|
align: str = "left"
|
||||||
@@ -94,20 +94,19 @@ FORMS: dict[str, FormSpec] = {
|
|||||||
Col("Date", "report_date", 15.3, "center"),
|
Col("Date", "report_date", 15.3, "center"),
|
||||||
Col("From", "from_location", 30.2),
|
Col("From", "from_location", 30.2),
|
||||||
Col("To", "to_location", 27.1),
|
Col("To", "to_location", 27.1),
|
||||||
Col("Kilometers (KM)", "kilometers_km", 17.6, "center"),
|
Col("Kilometers (KM)\n(One Way)", "kilometers_km", 17.6, "center"),
|
||||||
),
|
),
|
||||||
serial_field="serial_no",
|
serial_field="serial_no",
|
||||||
serial_dot=True,
|
serial_dot=True,
|
||||||
),
|
),
|
||||||
"area_covered": FormSpec(
|
"area_covered": FormSpec(
|
||||||
"area_covered",
|
"area_covered",
|
||||||
"AREA COVERED",
|
"AREA COVERAGE",
|
||||||
_NAME_HQ_MONTH,
|
_NAME_HQ_MONTH,
|
||||||
(
|
(
|
||||||
Col("SALE STATUS", "sale_status", 34.0),
|
Col("AREA TO COVER", "area_to_cover", 40.0),
|
||||||
Col("AREA TO COVER", "area_to_cover", 24.3),
|
Col("SALE OBJECTIVE", "sale_objective", 30.0),
|
||||||
Col("SALE OBJECTIVE", "sale_objective", 20.8),
|
Col("STATUS", "status", 30.0, "center"),
|
||||||
Col("STATUS", "status", 20.9, "center"),
|
|
||||||
),
|
),
|
||||||
min_rows=28,
|
min_rows=28,
|
||||||
full_letterhead=False,
|
full_letterhead=False,
|
||||||
@@ -130,8 +129,8 @@ FORMS: dict[str, FormSpec] = {
|
|||||||
"FIELD ACTIVITY REPORT",
|
"FIELD ACTIVITY REPORT",
|
||||||
_NAME_HQ_MONTH,
|
_NAME_HQ_MONTH,
|
||||||
(
|
(
|
||||||
Col("DATE", "report_date", 14.5, "center"),
|
Col("DATE", "report_date", 17.5, "center"),
|
||||||
Col("STATION WORKED", "station_worked", 36.6),
|
Col("STATION WORKED", "station_worked", 33.6),
|
||||||
Col("NO. OF DOCTORS CALLED", "no_of_doctors_called", 19.8, "center"),
|
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"),
|
Col("NO. OF CHEMISTS/PDS CALLED", "no_of_chemists_pds_called", 29.1, "center"),
|
||||||
),
|
),
|
||||||
@@ -142,15 +141,19 @@ FORMS: dict[str, FormSpec] = {
|
|||||||
"sales_and_stock_statement": FormSpec(
|
"sales_and_stock_statement": FormSpec(
|
||||||
"sales_and_stock_statement",
|
"sales_and_stock_statement",
|
||||||
"SALES AND STOCK STATEMENT",
|
"SALES AND STOCK STATEMENT",
|
||||||
_NAME_HQ_DATE_MONTH,
|
# No date: the statement is for a month, not a day.
|
||||||
|
(
|
||||||
|
(("NAME:", "name"), None),
|
||||||
|
(("HEADQUARTER:", "headquarter"), ("Month:", "month")),
|
||||||
|
),
|
||||||
(
|
(
|
||||||
_serial("Sl.No.", 7.0),
|
_serial("Sl.No.", 7.0),
|
||||||
Col("Name of the Product", "product_name", 22.6),
|
Col("Name of the Product", "product_name", 27.0),
|
||||||
Col("Opening", "opening", 15.0, "center"),
|
Col("Value in PTS", "value_in_pts", 15.0, "center"),
|
||||||
Col("Receipt", "receipt", 14.7, "center"),
|
Col("Opening", "opening", 13.0, "center"),
|
||||||
Col("Sale", "sale", 15.0, "center"),
|
Col("Receipt", "receipt", 13.0, "center"),
|
||||||
Col("Closing", "closing", 12.2, "center"),
|
Col("Sale", "sale", 12.5, "center"),
|
||||||
Col("Value in PTS", "value_in_pts", 13.5, "center"),
|
Col("Closing", "closing", 12.5, "center"),
|
||||||
),
|
),
|
||||||
min_rows=26,
|
min_rows=26,
|
||||||
serial_field="serial_no",
|
serial_field="serial_no",
|
||||||
@@ -160,17 +163,14 @@ FORMS: dict[str, FormSpec] = {
|
|||||||
"SALES PROJECTION",
|
"SALES PROJECTION",
|
||||||
_NAME_HQ_MONTH,
|
_NAME_HQ_MONTH,
|
||||||
(
|
(
|
||||||
_serial("SL. No.", 7.1),
|
# Printed under two group headings: CLOSING and PROJECTION (see the template).
|
||||||
Col("NAME OF THE PRODUCT", "product_name", 22.7),
|
_serial("SL. No.", 7.0),
|
||||||
Col("PTS", "pts", 10.7, "center"),
|
Col("NAME OF THE PRODUCT", "product_name", 29.0),
|
||||||
Col("SEC. QTY", "secondary_qty", 9.1, "center"),
|
Col("PTS", "pts", 12.0, "center"),
|
||||||
Col("VALUE", "value", 9.6, "center"),
|
Col("QUANTITY", "closing_qty", 13.0, "center"),
|
||||||
Col("CLOSING", "closing", 11.6, "center"),
|
Col("VALUE", "closing_value", 13.0, "center"),
|
||||||
Col("SEC. VALUE", "secondary_value", 10.1, "center"),
|
Col("QUANTITY", "projection_qty", 13.0, "center"),
|
||||||
# Header text is filled in per report from the "month" column — see
|
Col("VALUE", "projection_value", 13.0, "center"),
|
||||||
# _sales_projection_columns — never a hardcoded month.
|
|
||||||
Col("SALES", "aug_sales", 9.6, "center"),
|
|
||||||
Col("VALUE", "value_2", 9.5, "center"),
|
|
||||||
),
|
),
|
||||||
min_rows=26,
|
min_rows=26,
|
||||||
serial_field="serial_no",
|
serial_field="serial_no",
|
||||||
@@ -181,6 +181,16 @@ FORMS: dict[str, FormSpec] = {
|
|||||||
"DAILY CALL REPORT",
|
"DAILY CALL REPORT",
|
||||||
_NAME_HQ_DATE_MONTH,
|
_NAME_HQ_DATE_MONTH,
|
||||||
),
|
),
|
||||||
|
"expense_statement": FormSpec(
|
||||||
|
"expense_statement",
|
||||||
|
"Expenses Statement",
|
||||||
|
(
|
||||||
|
(("Name", "name"), ("Designation", "designation")),
|
||||||
|
(("H.Q.", "headquarter"), None),
|
||||||
|
),
|
||||||
|
min_rows=27,
|
||||||
|
serial_field="serial_no",
|
||||||
|
),
|
||||||
"weekly_report": FormSpec(
|
"weekly_report": FormSpec(
|
||||||
"weekly_report",
|
"weekly_report",
|
||||||
"Weekly Report",
|
"Weekly Report",
|
||||||
@@ -208,6 +218,49 @@ _CHEMIST_COLS = (
|
|||||||
Col("POB", "pob", 57.0),
|
Col("POB", "pob", 57.0),
|
||||||
)
|
)
|
||||||
_CHEMIST_FIELDS = tuple(c.field for c in _CHEMIST_COLS if c.field != SERIAL)
|
_CHEMIST_FIELDS = tuple(c.field for c in _CHEMIST_COLS if c.field != SERIAL)
|
||||||
|
# The morning day plan: who the MR intends to visit, and when. No outcomes yet.
|
||||||
|
_PLAN_DOCTOR_COLS = (
|
||||||
|
_serial("SR. NO.", 8.6),
|
||||||
|
Col("DR. NAME", "doctor_name", 32.0),
|
||||||
|
Col("QUALIFICATION", "qualification", 17.0),
|
||||||
|
Col("PLANNED TIME", "planned_time", 14.0, "center"),
|
||||||
|
Col("REMARKS", "remarks", 28.4),
|
||||||
|
)
|
||||||
|
_PLAN_CHEMIST_COLS = (
|
||||||
|
_serial("SR. NO.", 10.2),
|
||||||
|
Col("NAME OF THE CHEMIST", "chemist_name", 52.8),
|
||||||
|
Col("PLANNED TIME", "planned_time", 37.0, "center"),
|
||||||
|
)
|
||||||
|
# End-of-day report: the planned visits that were not made, and why.
|
||||||
|
_MISSED_COLS = (
|
||||||
|
_serial("SR. NO.", 8.6),
|
||||||
|
Col("NAME", "name", 33.0),
|
||||||
|
Col("TYPE", "kind", 14.0, "center"),
|
||||||
|
Col("REASON NOT VISITED", "reason", 44.4),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Expense Statement: money columns print as Rs | P pairs, like the printed form.
|
||||||
|
_EXPENSE_COLS = (
|
||||||
|
_serial("", 3.0),
|
||||||
|
Col("DATE", "report_date", 8.6, "center"),
|
||||||
|
Col("From", "from_location", 11.6),
|
||||||
|
Col("To", "to_location", 11.6),
|
||||||
|
Col("Rs", "fare_rs", 6.0, "right"),
|
||||||
|
Col("P.", "fare_p", 3.2, "center"),
|
||||||
|
Col("H.Q", "da_hq", 5.6, "right"),
|
||||||
|
Col("EX", "da_ex", 5.6, "right"),
|
||||||
|
Col("OUT", "da_out", 5.6, "right"),
|
||||||
|
Col("Rs", "postage_rs", 5.4, "right"),
|
||||||
|
Col("P.", "postage_p", 3.2, "center"),
|
||||||
|
Col("Rs", "other_expense_rs", 6.0, "right"),
|
||||||
|
Col("P.", "other_expense_p", 3.2, "center"),
|
||||||
|
Col("Rs", "total_rs", 7.0, "right"),
|
||||||
|
Col("P.", "total_p", 3.2, "center"),
|
||||||
|
Col("Business Achived", "business_achieved", 11.2, "center"),
|
||||||
|
)
|
||||||
|
_EXPENSE_SPLIT = ("fare", "postage", "other_expense", "total")
|
||||||
|
_EXPENSE_WHOLE = ("da_hq", "da_ex", "da_out")
|
||||||
|
_EXPENSE_AMOUNTS = ("fare", "da_hq", "da_ex", "da_out", "postage", "other_expense")
|
||||||
|
|
||||||
_WEEKLY_SUMMARY = (
|
_WEEKLY_SUMMARY = (
|
||||||
("No. of Days Worked", "no_of_days_worked"),
|
("No. of Days Worked", "no_of_days_worked"),
|
||||||
@@ -234,7 +287,9 @@ def _display(field: str, value: object) -> str:
|
|||||||
text = _text(value)
|
text = _text(value)
|
||||||
if field in DATE_FIELDS and text:
|
if field in DATE_FIELDS and text:
|
||||||
try:
|
try:
|
||||||
return date.fromisoformat(text[:10]).strftime("%d/%m/%Y")
|
day = date.fromisoformat(text[:10])
|
||||||
|
# Core Doctor Call Conversion prints just the day of the month (13, 25…).
|
||||||
|
return str(day.day) if field == "date_of_visit" else day.strftime("%d/%m/%Y")
|
||||||
except ValueError:
|
except ValueError:
|
||||||
return text
|
return text
|
||||||
return text
|
return text
|
||||||
@@ -254,12 +309,79 @@ def _has(row: Row, fields: tuple[str, ...]) -> bool:
|
|||||||
return any(_text(row.get(field)) for field in fields)
|
return any(_text(row.get(field)) for field in fields)
|
||||||
|
|
||||||
|
|
||||||
def _sales_projection_columns(cols: tuple[Col, ...], rows: list[Row]) -> tuple[Col, ...]:
|
def _amount(value: object) -> float | None:
|
||||||
"""The printed form's "<Month>. Sales" column: the month it prints is whichever
|
text = _text(value).replace(",", "")
|
||||||
month the rows were actually filled in for, never a fixed month."""
|
try:
|
||||||
month = _distinct(rows, "month")
|
return float(text) if text else None
|
||||||
header = f"{month[:3].upper()}. SALES" if month else "SALES"
|
except ValueError:
|
||||||
return tuple(Col(header, c.field, c.width, c.align) if c.field == "aug_sales" else c for c in cols)
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _rupees(amount: float | None) -> tuple[str, str]:
|
||||||
|
"""(Rs, P) as the printed form splits money: 1234.5 -> ("1234", "50")."""
|
||||||
|
if amount is None:
|
||||||
|
return "", ""
|
||||||
|
paise = round(amount * 100)
|
||||||
|
return str(paise // 100), f"{paise % 100:02d}"
|
||||||
|
|
||||||
|
|
||||||
|
def _whole(amount: float | None) -> str:
|
||||||
|
if amount is None:
|
||||||
|
return ""
|
||||||
|
return f"{amount:.0f}" if amount == int(amount) else f"{amount:.2f}"
|
||||||
|
|
||||||
|
|
||||||
|
def call_average(rows: list[Row], field: str) -> str:
|
||||||
|
"""Field Activity Report: calls in `field` summed over the days worked, divided by those days.
|
||||||
|
|
||||||
|
A working day is a distinct date with a row (rows without a date count one day each); the MR
|
||||||
|
never types an average — it is always worked out from the figures."""
|
||||||
|
days = {_text(r.get("report_date"))[:10] or f"row-{i}" for i, r in enumerate(rows) if _has(r, ("report_date", field))}
|
||||||
|
if not days:
|
||||||
|
return ""
|
||||||
|
total = sum(v for v in (_amount(r.get(field)) for r in rows) if v is not None)
|
||||||
|
average = round(total / len(days), 2)
|
||||||
|
return f"{average:g}" if average == int(average) else f"{average:.2f}"
|
||||||
|
|
||||||
|
|
||||||
|
def _sales_projection_totals(rows: list[Row]) -> list[str]:
|
||||||
|
"""The TOTAL line under the Sales Projection: one sum per figure column (blank when nothing is filled in)."""
|
||||||
|
totals: list[str] = []
|
||||||
|
for field in ("closing_qty", "closing_value", "projection_qty", "projection_value"):
|
||||||
|
values = [v for v in (_amount(r.get(field)) for r in rows) if v is not None]
|
||||||
|
totals.append(_whole(round(sum(values), 2)) if values else "")
|
||||||
|
return totals
|
||||||
|
|
||||||
|
|
||||||
|
def _expense_row(row: Row) -> Row:
|
||||||
|
out: Row = dict(row)
|
||||||
|
amounts = {f: _amount(row.get(f)) for f in _EXPENSE_AMOUNTS}
|
||||||
|
# The total is always the sum of the day's amounts, whatever was stored.
|
||||||
|
present = [a for a in amounts.values() if a is not None]
|
||||||
|
amounts["total"] = sum(present) if present else None
|
||||||
|
for field in _EXPENSE_SPLIT:
|
||||||
|
out[f"{field}_rs"], out[f"{field}_p"] = _rupees(amounts[field])
|
||||||
|
for field in _EXPENSE_WHOLE:
|
||||||
|
if amounts[field] is not None:
|
||||||
|
out[field] = _whole(amounts[field])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _expense_totals(rows: list[Row]) -> dict[str, str]:
|
||||||
|
"""The TOTAL line under the table, one figure per money column."""
|
||||||
|
sums: dict[str, float | None] = {}
|
||||||
|
for field in _EXPENSE_AMOUNTS:
|
||||||
|
values = [v for v in (_amount(r.get(field)) for r in rows) if v is not None]
|
||||||
|
sums[field] = sum(values) if values else None
|
||||||
|
present = [v for v in sums.values() if v is not None]
|
||||||
|
sums["total"] = sum(present) if present else None
|
||||||
|
totals: dict[str, str] = {}
|
||||||
|
for field in _EXPENSE_SPLIT:
|
||||||
|
totals[f"{field}_rs"], totals[f"{field}_p"] = _rupees(sums[field])
|
||||||
|
for field in _EXPENSE_WHOLE:
|
||||||
|
totals[field] = _whole(sums[field])
|
||||||
|
totals["claimed"] = f"{sums['total']:,.2f}" if sums["total"] is not None else ""
|
||||||
|
return totals
|
||||||
|
|
||||||
|
|
||||||
def _grid(
|
def _grid(
|
||||||
@@ -367,6 +489,20 @@ def build_form_context(
|
|||||||
)
|
)
|
||||||
extra["stockist_visit"] = _distinct(rows, "stockist_visit")
|
extra["stockist_visit"] = _distinct(rows, "stockist_visit")
|
||||||
extra["order_value"] = _distinct(rows, "order_value")
|
extra["order_value"] = _distinct(rows, "order_value")
|
||||||
|
elif spec.template == "expense_statement":
|
||||||
|
printed = [_expense_row(r) for r in rows]
|
||||||
|
grids["main"] = _grid(
|
||||||
|
_EXPENSE_COLS,
|
||||||
|
printed,
|
||||||
|
min_rows=spec.min_rows,
|
||||||
|
serial_field=None if renumber else spec.serial_field,
|
||||||
|
)
|
||||||
|
extra["sums"] = _expense_totals(rows)
|
||||||
|
dates = sorted(
|
||||||
|
{_text(r.get("report_date"))[:10] for r in rows if _text(r.get("report_date"))}
|
||||||
|
)
|
||||||
|
extra["period_from"] = _display("report_date", dates[0]) if dates else ""
|
||||||
|
extra["period_to"] = _display("report_date", dates[-1]) if dates else ""
|
||||||
elif spec.template == "weekly_report":
|
elif spec.template == "weekly_report":
|
||||||
extra["reports"] = [
|
extra["reports"] = [
|
||||||
{
|
{
|
||||||
@@ -377,20 +513,19 @@ def build_form_context(
|
|||||||
for r in rows or [{}]
|
for r in rows or [{}]
|
||||||
]
|
]
|
||||||
else:
|
else:
|
||||||
columns = spec.columns
|
|
||||||
if table_name == "sales_projection":
|
|
||||||
columns = _sales_projection_columns(columns, rows)
|
|
||||||
grids["main"] = _grid(
|
grids["main"] = _grid(
|
||||||
columns,
|
spec.columns,
|
||||||
rows,
|
rows,
|
||||||
min_rows=spec.min_rows,
|
min_rows=spec.min_rows,
|
||||||
serial_field=None if renumber else spec.serial_field,
|
serial_field=None if renumber else spec.serial_field,
|
||||||
serial_dot=spec.serial_dot,
|
serial_dot=spec.serial_dot,
|
||||||
table_width=spec.table_width,
|
table_width=spec.table_width,
|
||||||
)
|
)
|
||||||
|
if table_name == "sales_projection":
|
||||||
|
extra["totals"] = _sales_projection_totals(rows)
|
||||||
if table_name == "field_activity_report":
|
if table_name == "field_activity_report":
|
||||||
extra["doctor_call_avg"] = _distinct(rows, "doctor_call_avg")
|
extra["doctor_call_avg"] = call_average(rows, "no_of_doctors_called")
|
||||||
extra["chemist_call_avg"] = _distinct(rows, "chemist_call_avg")
|
extra["chemist_call_avg"] = call_average(rows, "no_of_chemists_pds_called")
|
||||||
|
|
||||||
approval = None
|
approval = None
|
||||||
if table_name in APPROVAL_FORMS:
|
if table_name in APPROVAL_FORMS:
|
||||||
@@ -426,12 +561,22 @@ _OUTCOME_NOTE = {"NOT_AVAILABLE": "Not available", "RESCHEDULED": "Rescheduled"}
|
|||||||
|
|
||||||
|
|
||||||
def _doctor_remarks(call) -> str:
|
def _doctor_remarks(call) -> str:
|
||||||
"""The remarks column; a visit that did not happen is flagged, since the form has no outcome column."""
|
"""The remarks column; a visit that did not happen is flagged, since the form has no outcome column,
|
||||||
|
and so is any gift given."""
|
||||||
note = _OUTCOME_NOTE.get(getattr(call.call_outcome, "value", str(call.call_outcome)), "")
|
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)
|
# The printed form has no gift column either, so a gift is noted with the remarks.
|
||||||
|
gift = (getattr(call, "gift", None) or "").strip()
|
||||||
|
gift = f"Gift: {gift}" if gift else ""
|
||||||
|
return ". ".join(part for part in (note, gift, (call.remarks or "").strip()) if part)
|
||||||
|
|
||||||
|
|
||||||
def build_dcr_context(dcr, doctor_calls, chemist_calls, approval: dict[str, str] | None = None) -> dict[str, object]:
|
def build_dcr_context(
|
||||||
|
dcr,
|
||||||
|
doctor_calls,
|
||||||
|
chemist_calls,
|
||||||
|
approval: dict[str, str] | None = None,
|
||||||
|
missed: list[Row] | None = None,
|
||||||
|
) -> dict[str, object]:
|
||||||
"""The approved Daily Call Report, laid out exactly like the printed company form.
|
"""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
|
Same template family, headings, column widths and number of ruled lines as the
|
||||||
@@ -439,13 +584,22 @@ def build_dcr_context(dcr, doctor_calls, chemist_calls, approval: dict[str, str]
|
|||||||
from the top in visit order; more visits simply continue on the next page. The only
|
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
|
additions are the signatures: the MR's name, and (once approved) the Area Manager's
|
||||||
approval signature with its date and time.
|
approval signature with its date and time.
|
||||||
|
|
||||||
|
A morning day plan uses the same form with a PLANNED TIME column in place of the
|
||||||
|
visit details. An end-of-day report adds the planned visits that were not made
|
||||||
|
(``missed``: name / kind / reason rows).
|
||||||
"""
|
"""
|
||||||
|
report_type = getattr(dcr, "report_type", None)
|
||||||
|
report_type = getattr(report_type, "value", report_type)
|
||||||
|
if report_type == "PLAN":
|
||||||
|
return _build_plan_context(dcr, doctor_calls, chemist_calls, approval)
|
||||||
|
is_self = report_type == "SELF" # an Area Manager's own report: no approval signature
|
||||||
doctors = [
|
doctors = [
|
||||||
{
|
{
|
||||||
"doctor_name": c.doctor.name,
|
"doctor_name": c.doctor.name,
|
||||||
"qualification": c.doctor.qualification or "",
|
"qualification": c.doctor.qualification or "",
|
||||||
"product_promote": c.product_promote or "",
|
"product_promote": _products(c.product_promote),
|
||||||
"product_sample": c.product_sample or "",
|
"product_sample": _products(c.product_sample),
|
||||||
"remarks": _doctor_remarks(c),
|
"remarks": _doctor_remarks(c),
|
||||||
}
|
}
|
||||||
for c in doctor_calls
|
for c in doctor_calls
|
||||||
@@ -457,17 +611,63 @@ def build_dcr_context(dcr, doctor_calls, chemist_calls, approval: dict[str, str]
|
|||||||
]
|
]
|
||||||
return {
|
return {
|
||||||
"template": "dcr",
|
"template": "dcr",
|
||||||
"label": "Daily Call Report",
|
"label": "Daily Call Report (Self)" if is_self else "Daily Call Report",
|
||||||
"title": "DAILY CALL REPORT",
|
"title": "DAILY CALL REPORT (SELF)" if is_self else "DAILY CALL REPORT",
|
||||||
"title_suffix": f"{dcr.mr.full_name} — {dcr.report_date.strftime('%d/%m/%Y')}",
|
"title_suffix": f"{dcr.mr.full_name} — {dcr.report_date.strftime('%d/%m/%Y')}",
|
||||||
"full_letterhead": True,
|
"full_letterhead": True,
|
||||||
"meta_rows": meta,
|
"meta_rows": meta,
|
||||||
"grids": {
|
"grids": {
|
||||||
"doctors": _grid(_DOCTOR_COLS, doctors, min_rows=10),
|
"doctors": _grid(_DOCTOR_COLS, doctors, min_rows=10),
|
||||||
"chemists": _grid(_CHEMIST_COLS, chemists, min_rows=5, table_width=84),
|
"chemists": _grid(_CHEMIST_COLS, chemists, min_rows=5, table_width=84),
|
||||||
|
**({"missed": _grid(_MISSED_COLS, missed, min_rows=0)} if missed else {}),
|
||||||
},
|
},
|
||||||
|
"is_plan": False,
|
||||||
"stockist_visit": dcr.stockist_visit or "",
|
"stockist_visit": dcr.stockist_visit or "",
|
||||||
"order_value": dcr.order_value or "",
|
"order_value": dcr.order_value or "",
|
||||||
|
"signer_label": "Area Manager Signature" if is_self else "MR Signature",
|
||||||
"mr_signed": f"{dcr.mr.full_name} ({dcr.mr.employee_code})",
|
"mr_signed": f"{dcr.mr.full_name} ({dcr.mr.employee_code})",
|
||||||
"approval": approval, # {"name": ..., "at": "dd/mm/yyyy HH:MM"} or None
|
"approval": approval, # {"name": ..., "at": "dd/mm/yyyy HH:MM"} or None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _products(names: list[str] | str | None) -> str:
|
||||||
|
"""Several products share one cell of the printed form."""
|
||||||
|
return names if isinstance(names, str) else ", ".join(names or [])
|
||||||
|
|
||||||
|
|
||||||
|
def _build_plan_context(dcr, doctor_calls, chemist_calls, approval) -> dict[str, object]:
|
||||||
|
doctors = [
|
||||||
|
{
|
||||||
|
"doctor_name": c.doctor.name,
|
||||||
|
"qualification": c.doctor.qualification or "",
|
||||||
|
"planned_time": c.visit_time.strftime("%H:%M"),
|
||||||
|
"remarks": (c.remarks or "").strip(),
|
||||||
|
}
|
||||||
|
for c in doctor_calls
|
||||||
|
]
|
||||||
|
chemists = [
|
||||||
|
{"chemist_name": c.chemist.name, "planned_time": c.visit_time.strftime("%H:%M")}
|
||||||
|
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 (Plan)",
|
||||||
|
"title": "DAILY CALL REPORT (PLAN)",
|
||||||
|
"title_suffix": f"{dcr.mr.full_name} — {dcr.report_date.strftime('%d/%m/%Y')}",
|
||||||
|
"full_letterhead": True,
|
||||||
|
"meta_rows": meta,
|
||||||
|
"grids": {
|
||||||
|
"doctors": _grid(_PLAN_DOCTOR_COLS, doctors, min_rows=10),
|
||||||
|
"chemists": _grid(_PLAN_CHEMIST_COLS, chemists, min_rows=5, table_width=84),
|
||||||
|
},
|
||||||
|
"is_plan": True,
|
||||||
|
"stockist_visit": "",
|
||||||
|
"order_value": "",
|
||||||
|
"mr_remarks": dcr.mr_remarks or "",
|
||||||
|
"mr_signed": f"{dcr.mr.full_name} ({dcr.mr.employee_code})",
|
||||||
|
"approval": approval,
|
||||||
|
}
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ from app.common.enums import AuditAction, EntityType
|
|||||||
from app.config.settings import settings
|
from app.config.settings import settings
|
||||||
from app.pdf.forms import approval_signature_line, build_dcr_context, build_form_context
|
from app.pdf.forms import approval_signature_line, build_dcr_context, build_form_context
|
||||||
from app.reports.models import DailyCallReport
|
from app.reports.models import DailyCallReport
|
||||||
|
from app.reports.serializers import planned_visits
|
||||||
from app.users.models import User
|
from app.users.models import User
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -198,11 +199,17 @@ class PDFService:
|
|||||||
return {"name": approver.full_name, "at": when}
|
return {"name": approver.full_name, "at": when}
|
||||||
|
|
||||||
async def _context(self, dcr: DailyCallReport) -> dict:
|
async def _context(self, dcr: DailyCallReport) -> dict:
|
||||||
|
missed = [
|
||||||
|
{"name": p.name, "kind": p.kind.title(), "reason": p.missed_reason}
|
||||||
|
for p in planned_visits(dcr)
|
||||||
|
if p.status == "MISSED"
|
||||||
|
]
|
||||||
return build_dcr_context(
|
return build_dcr_context(
|
||||||
dcr,
|
dcr,
|
||||||
sorted(dcr.doctor_calls, key=lambda c: c.visit_time),
|
sorted(dcr.doctor_calls, key=lambda c: c.visit_time),
|
||||||
sorted(dcr.chemist_calls, key=lambda c: c.visit_time),
|
sorted(dcr.chemist_calls, key=lambda c: c.visit_time),
|
||||||
await self._approval(dcr),
|
await self._approval(dcr),
|
||||||
|
missed,
|
||||||
)
|
)
|
||||||
|
|
||||||
async def render_bytes(self, dcr: DailyCallReport) -> bytes:
|
async def render_bytes(self, dcr: DailyCallReport) -> bytes:
|
||||||
|
|||||||
@@ -19,19 +19,27 @@
|
|||||||
|
|
||||||
{% block form %}
|
{% block form %}
|
||||||
{{ grid(grids.doctors, left=True) }}
|
{{ grid(grids.doctors, left=True) }}
|
||||||
<h2 class="section">CHEMIST VISIT</h2>
|
<h2 class="section">{{ "CHEMISTS TO VISIT" if is_plan else "CHEMIST VISIT" }}</h2>
|
||||||
{{ grid(grids.chemists, left=True) }}
|
{{ grid(grids.chemists, left=True) }}
|
||||||
|
{% if is_plan %}
|
||||||
|
{% if mr_remarks %}<div class="visit"><div><b>REMARKS :</b> {{ mr_remarks }}</div></div>{% endif %}
|
||||||
|
{% else %}
|
||||||
|
{% if grids.missed %}
|
||||||
|
<h2 class="section">PLANNED VISITS NOT MADE</h2>
|
||||||
|
{{ grid(grids.missed, left=True) }}
|
||||||
|
{% endif %}
|
||||||
<div class="visit">
|
<div class="visit">
|
||||||
<div><b>STOCKIST VISIT :</b> {{ stockist_visit }}</div>
|
<div><b>STOCKIST VISIT :</b> {{ stockist_visit }}</div>
|
||||||
<div><b>ORDER :</b> {{ order_value }}</div>
|
<div><b>ORDER :</b> {{ order_value }}</div>
|
||||||
</div>
|
</div>
|
||||||
|
{% endif %}
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
{% block signature %}
|
{% block signature %}
|
||||||
<table class="dcr-sign">
|
<table class="dcr-sign">
|
||||||
<tr>
|
<tr>
|
||||||
<td class="mr">
|
<td class="mr">
|
||||||
<div class="sign-label">MR Signature</div>
|
<div class="sign-label">{{ signer_label | default("MR Signature") }}</div>
|
||||||
<div class="signed">{{ mr_signed }}</div>
|
<div class="signed">{{ mr_signed }}</div>
|
||||||
</td>
|
</td>
|
||||||
<td class="am">
|
<td class="am">
|
||||||
|
|||||||
@@ -1,19 +1,23 @@
|
|||||||
{{ company_name }}
|
{{ company_name }}
|
||||||
{{ company_address }}
|
{{ company_address }}
|
||||||
Website: {{ company_website }} E-Mail: {{ company_email }} PHONE: {{ company_phone }}
|
Website: {{ company_website }} E-Mail: {{ company_email }} PHONE: {{ company_phone }}
|
||||||
DAILY CALL REPORT
|
{{ title }}
|
||||||
{% for pair in meta_rows %}{% for slot in pair %}{% if slot %}{{ slot[0] }} {{ slot[1] }} {% endif %}{% endfor %}
|
{% for pair in meta_rows %}{% for slot in pair %}{% if slot %}{{ slot[0] }} {{ slot[1] }} {% endif %}{% endfor %}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
SR.NO | DR. NAME | QUALIFICATION | PRODUCT PROMOTE | PRODUCT SAMPLE | REMARKS
|
{{ grids.doctors.headers | join(' | ') }}
|
||||||
{% for r in grids.doctors.rows %}{{ r.cells | join(' | ') }}
|
{% for r in grids.doctors.rows %}{{ r.cells | join(' | ') }}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
CHEMIST VISIT
|
{{ "CHEMISTS TO VISIT" if is_plan else "CHEMIST VISIT" }}
|
||||||
SR.NO | NAME OF THE CHEMIST | POB
|
{{ grids.chemists.headers | join(' | ') }}
|
||||||
{% for r in grids.chemists.rows %}{{ r.cells | join(' | ') }}
|
{% for r in grids.chemists.rows %}{{ r.cells | join(' | ') }}
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
STOCKIST VISIT : {{ stockist_visit }}
|
{% if grids.missed %}PLANNED VISITS NOT MADE
|
||||||
|
{{ grids.missed.headers | join(' | ') }}
|
||||||
|
{% for r in grids.missed.rows %}{{ r.cells | join(' | ') }}
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}{% if not is_plan %}STOCKIST VISIT : {{ stockist_visit }}
|
||||||
ORDER : {{ order_value }}
|
ORDER : {{ order_value }}
|
||||||
|
{% endif %}
|
||||||
MR Signature: {{ mr_signed }}
|
MR Signature: {{ mr_signed }}
|
||||||
{% if approval %}APPROVAL SIGNATURE: {{ approval.name }} ({{ approval.at }})
|
{% if approval %}APPROVAL SIGNATURE: {{ approval.name }} ({{ approval.at }})
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -30,7 +30,7 @@
|
|||||||
<table class="grid{% if left %} left{% endif %}" style="width:{{ g.width }}">
|
<table class="grid{% if left %} left{% endif %}" style="width:{{ g.width }}">
|
||||||
<colgroup>{% for w in g.widths %}<col style="width:{{ w }}">{% endfor %}</colgroup>
|
<colgroup>{% for w in g.widths %}<col style="width:{{ w }}">{% endfor %}</colgroup>
|
||||||
<thead>
|
<thead>
|
||||||
<tr>{% for h in g.headers %}<th>{{ h }}</th>{% endfor %}</tr>
|
<tr>{% for h in g.headers %}<th>{% for part in h.split("\n") %}{{ part }}{% if not loop.last %}<br>{% endif %}{% endfor %}</th>{% endfor %}</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{% for r in g.rows %}
|
{% for r in g.rows %}
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
{% extends "forms/_form_base.html" %}
|
||||||
|
{% from "forms/_macros.html" import letterhead %}
|
||||||
|
|
||||||
|
{% block page_box %}size: A4 landscape; margin: 7mm 11mm;{% endblock %}
|
||||||
|
|
||||||
|
{% block form_styles %}
|
||||||
|
body { font-size: 10pt; }
|
||||||
|
.company .name { font-size: 24pt; }
|
||||||
|
.company .name { line-height: 1.05; }
|
||||||
|
.company .line { font-size: 9pt; line-height: 1.2; font-style: italic; }
|
||||||
|
h1.title { margin: 2mm 0 2mm; font-size: 15pt; letter-spacing: 1.5pt; font-style: italic; text-decoration: none; text-align: left; }
|
||||||
|
h1.title .ln { min-width: 34mm; font-size: 10.5pt; letter-spacing: 0; font-style: normal; }
|
||||||
|
table.who { width: 100%; border-collapse: collapse; margin: 1.5mm 0 0; }
|
||||||
|
table.who td { padding: 0; font-size: 10pt; font-style: italic; font-weight: bold; white-space: nowrap; }
|
||||||
|
table.who .ln { min-width: 52mm; font-style: normal; font-weight: normal; }
|
||||||
|
table.who .ln.short { min-width: 30mm; }
|
||||||
|
table.grid th, table.grid td { padding: 0 .9mm; }
|
||||||
|
table.grid th { height: 5mm; font-size: 9pt; font-weight: normal; }
|
||||||
|
table.grid thead tr:first-child th { font-weight: bold; }
|
||||||
|
table.grid td { height: 4.2mm; font-size: 9pt; overflow-wrap: normal; white-space: nowrap; overflow: hidden; }
|
||||||
|
table.grid tr.total td { font-weight: bold; }
|
||||||
|
table.grid td.no { font-size: 8pt; }
|
||||||
|
table.foot { width: 100%; margin-top: 2mm; border-collapse: collapse; page-break-inside: avoid; }
|
||||||
|
table.foot td { vertical-align: top; padding: 0 2mm 0 0; font-size: 9pt; }
|
||||||
|
.box { border: .7pt solid #000; padding: 1mm 2mm; }
|
||||||
|
.box .office { text-align: center; font-style: italic; font-weight: bold; letter-spacing: 1.5pt; margin-bottom: 1mm; }
|
||||||
|
.box .ln { min-width: 34mm; text-align: left; padding-left: 1mm; }
|
||||||
|
.line-row { margin: 1.2mm 0; white-space: nowrap; }
|
||||||
|
.status div { margin: .3mm 0; white-space: nowrap; }
|
||||||
|
.status .ln { min-width: 18mm; height: 3.8mm; }
|
||||||
|
{% endblock %}
|
||||||
|
|
||||||
|
{% block body %}
|
||||||
|
{{ letterhead(full_letterhead) }}
|
||||||
|
<table class="who">
|
||||||
|
<tr>
|
||||||
|
<td>Name <span class="ln">{{ meta_rows[0][0][1] }}</span></td>
|
||||||
|
<td>Designation <span class="ln">{{ meta_rows[0][1][1] }}</span></td>
|
||||||
|
<td>H.Q. <span class="ln short">{{ meta_rows[1][0][1] }}</span></td>
|
||||||
|
<td>Date <span class="ln short"></span></td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
<h1 class="title">Expenses Statement from Dt. <span class="ln">{{ period_from }}</span> to <span class="ln">{{ period_to }}</span></h1>
|
||||||
|
|
||||||
|
{% set g = grids.main %}
|
||||||
|
<table class="grid" style="width:{{ g.width }}">
|
||||||
|
<colgroup>{% for w in g.widths %}<col style="width:{{ w }}">{% endfor %}</colgroup>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th rowspan="2"></th>
|
||||||
|
<th rowspan="2">DATE</th>
|
||||||
|
<th colspan="2">Place Of Visit</th>
|
||||||
|
<th colspan="2">Fare</th>
|
||||||
|
<th colspan="3">Daily Allowance</th>
|
||||||
|
<th colspan="2">Postage</th>
|
||||||
|
<th colspan="2">Other Expence</th>
|
||||||
|
<th colspan="2">Total</th>
|
||||||
|
<th rowspan="2">Business Achived</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
{% for h in g.headers[2:-1] %}<th>{{ h }}</th>{% endfor %}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for r in g.rows %}
|
||||||
|
<tr>{% for c in r.cells %}<td class="{{ g.aligns[loop.index0] }}{% if loop.first %} no{% endif %}">{{ c }}</td>{% endfor %}</tr>
|
||||||
|
{% endfor %}
|
||||||
|
<tr class="total">
|
||||||
|
<td colspan="4" class="c">TOTAL</td>
|
||||||
|
<td class="r">{{ sums.fare_rs }}</td><td class="c">{{ sums.fare_p }}</td>
|
||||||
|
<td class="r">{{ sums.da_hq }}</td><td class="r">{{ sums.da_ex }}</td><td class="r">{{ sums.da_out }}</td>
|
||||||
|
<td class="r">{{ sums.postage_rs }}</td><td class="c">{{ sums.postage_p }}</td>
|
||||||
|
<td class="r">{{ sums.other_expense_rs }}</td><td class="c">{{ sums.other_expense_p }}</td>
|
||||||
|
<td class="r">{{ sums.total_rs }}</td><td class="c">{{ sums.total_p }}</td>
|
||||||
|
<td></td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<table class="foot">
|
||||||
|
<tr>
|
||||||
|
<td style="width:46%">
|
||||||
|
<div class="box">
|
||||||
|
<div class="office">For Office Use Only</div>
|
||||||
|
<div class="line-row">Amount Claimed <span class="ln">{{ sums.claimed }}</span> Amt. Passed <span class="ln"></span></div>
|
||||||
|
<div class="line-row">Deduction / Addition with reason <span class="ln" style="min-width:60mm"></span></div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td style="width:26%">
|
||||||
|
<div class="box status">
|
||||||
|
<div class="office">Report Status</div>
|
||||||
|
<div>Daily Report :- <span class="ln"></span></div>
|
||||||
|
<div>Stock and Sale Statement :- <span class="ln"></span></div>
|
||||||
|
<div>Weekly Report :- <span class="ln"></span></div>
|
||||||
|
<div>Monthly Apprasal :- <span class="ln"></span></div>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td style="width:28%">
|
||||||
|
<div class="line-row">Signature :- <span class="ln">{{ approval.mr_name }}</span></div>
|
||||||
|
<div class="line-row">Checked by :- <span class="ln">{% if approval.value != "PENDING" %}{{ approval.value }}{% endif %}</span></div>
|
||||||
|
<div class="line-row">DATE :- <span class="ln">{{ approval.when }}</span></div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
{% endblock %}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
{% extends "forms/_form_base.html" %}
|
{% extends "forms/_form_base.html" %}
|
||||||
{% from "forms/_macros.html" import grid %}
|
|
||||||
|
|
||||||
{# Arial throughout, title tucked directly under the company name — as printed. #}
|
{# Arial throughout, title tucked directly under the company name — as printed. #}
|
||||||
{% block form_styles %}
|
{% block form_styles %}
|
||||||
@@ -10,11 +9,35 @@
|
|||||||
font-size: 14pt;
|
font-size: 14pt;
|
||||||
}
|
}
|
||||||
table.grid th, table.grid td { font-family: "Liberation Sans", Arial, "DejaVu Sans", sans-serif; }
|
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 th { height: 7mm; font-size: 9.5pt; }
|
||||||
|
table.grid th.sub { height: 6mm; font-size: 8.5pt; }
|
||||||
table.grid td { font-size: 9.5pt; }
|
table.grid td { font-size: 9.5pt; }
|
||||||
table.grid td:nth-child(2) { font-weight: bold; }
|
table.grid td:nth-child(2) { font-weight: bold; }
|
||||||
|
table.grid tr.total td { font-weight: bold; }
|
||||||
|
table.grid tr.total td:nth-child(2) { text-align: right; }
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|
||||||
|
{# Two heading rows: CLOSING and PROJECTION each span their QUANTITY and VALUE. #}
|
||||||
{% block form %}
|
{% block form %}
|
||||||
{{ grid(grids.main) }}
|
{% set g = grids.main %}
|
||||||
|
<table class="grid" style="width:{{ g.width }}">
|
||||||
|
<colgroup>{% for w in g.widths %}<col style="width:{{ w }}">{% endfor %}</colgroup>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
{% for h in g.headers[:3] %}<th rowspan="2">{{ h }}</th>{% endfor %}
|
||||||
|
<th colspan="2">CLOSING</th>
|
||||||
|
<th colspan="2">PROJECTION</th>
|
||||||
|
</tr>
|
||||||
|
<tr>{% for h in g.headers[3:] %}<th class="sub">{{ 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 %}
|
||||||
|
<tr class="total">
|
||||||
|
<td></td><td>TOTAL</td><td></td>
|
||||||
|
{% for t in totals %}<td class="{{ g.aligns[loop.index0 + 3] }}">{{ t }}</td>{% endfor %}
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from sqlalchemy.exc import IntegrityError
|
|||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.audit.service import AuditService
|
from app.audit.service import AuditService
|
||||||
from app.common.enums import AuditAction, EntityType, Role
|
from app.common.enums import AuditAction, EntityType, Role, FIELD_ROLES
|
||||||
from app.common.exceptions import ConflictError, NotFoundError
|
from app.common.exceptions import ConflictError, NotFoundError
|
||||||
from app.common.utils import snapshot
|
from app.common.utils import snapshot
|
||||||
from app.products.models import Product
|
from app.products.models import Product
|
||||||
@@ -27,7 +27,7 @@ class ProductService:
|
|||||||
|
|
||||||
async def list_for(self, actor: User) -> list[Product]:
|
async def list_for(self, actor: User) -> list[Product]:
|
||||||
stmt = select(Product).where(Product.company_id == actor.company_id).order_by(Product.name)
|
stmt = select(Product).where(Product.company_id == actor.company_id).order_by(Product.name)
|
||||||
if actor.role == Role.MR:
|
if actor.role in FIELD_ROLES:
|
||||||
stmt = stmt.where(Product.is_active.is_(True))
|
stmt = stmt.where(Product.is_active.is_(True))
|
||||||
return list((await self.db.execute(stmt)).scalars().all())
|
return list((await self.db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
|
|||||||
+82
-11
@@ -1,4 +1,12 @@
|
|||||||
"""The Daily Call Report and its call rows — the core artefact of the MVP."""
|
"""The Daily Call Report and its call rows — the core artefact of the MVP.
|
||||||
|
|
||||||
|
Each working day an MR files two reports (see ``ReportType``): a morning PLAN of the
|
||||||
|
doctors and chemists they intend to visit, and an end-of-day ACTUAL report of the visits
|
||||||
|
that happened. Both share this table and its call rows; the ACTUAL report points at its
|
||||||
|
plan, and records why any planned visit was missed in ``missed_visit``.
|
||||||
|
|
||||||
|
An Area Manager files a SELF report of their own visits in the same table; ``mr_user_id``
|
||||||
|
is then the Area Manager (the report's owner), and submitting it makes it final."""
|
||||||
|
|
||||||
import uuid
|
import uuid
|
||||||
from datetime import date, datetime, time
|
from datetime import date, datetime, time
|
||||||
@@ -14,19 +22,24 @@ from sqlalchemy import (
|
|||||||
Time,
|
Time,
|
||||||
UniqueConstraint,
|
UniqueConstraint,
|
||||||
)
|
)
|
||||||
|
from sqlalchemy.dialects.postgresql import ARRAY
|
||||||
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
from sqlalchemy.dialects.postgresql import UUID as PGUUID
|
||||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
from app.common.enums import CallOutcome, ConversionStatus, DCRStatus, Role
|
from app.common.enums import CallOutcome, ConversionStatus, DCRStatus, ReportType, Role
|
||||||
from app.database.base import Base, TimestampMixin, UUIDMixin
|
from app.database.base import Base, TimestampMixin, UUIDMixin
|
||||||
|
|
||||||
|
|
||||||
class DailyCallReport(Base, UUIDMixin, TimestampMixin):
|
class DailyCallReport(Base, UUIDMixin, TimestampMixin):
|
||||||
__tablename__ = "daily_call_report"
|
__tablename__ = "daily_call_report"
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
# V1 / A9 — ONE report per MR per calendar date. Enforced in the database and
|
# V1 / A9 — ONE report of each type per MR per calendar date. Enforced in the
|
||||||
# not only in the service, so a double-submit race cannot create two reports.
|
# database and not only in the service, so a double-submit race cannot create two.
|
||||||
UniqueConstraint("mr_user_id", "report_date", name="uq_dcr_mr_date"),
|
UniqueConstraint("mr_user_id", "report_date", "report_type", name="uq_dcr_mr_date_type"),
|
||||||
|
# A plan is followed by at most one end-of-day report.
|
||||||
|
UniqueConstraint("plan_id", name="uq_dcr_plan_id"),
|
||||||
|
# Only an end-of-day report points at a plan.
|
||||||
|
CheckConstraint("report_type = 'ACTUAL' OR plan_id IS NULL", name="ck_dcr_plan_link"),
|
||||||
# An approved report must carry its approval timestamp, and nothing else may.
|
# An approved report must carry its approval timestamp, and nothing else may.
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
"(status = 'APPROVED' AND approved_at IS NOT NULL) "
|
"(status = 'APPROVED' AND approved_at IS NOT NULL) "
|
||||||
@@ -44,6 +57,16 @@ class DailyCallReport(Base, UUIDMixin, TimestampMixin):
|
|||||||
PGUUID(as_uuid=True), ForeignKey("headquarters.id", ondelete="RESTRICT"), nullable=False
|
PGUUID(as_uuid=True), ForeignKey("headquarters.id", ondelete="RESTRICT"), nullable=False
|
||||||
)
|
)
|
||||||
report_date: Mapped[date] = mapped_column(Date, nullable=False)
|
report_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||||
|
report_type: Mapped[ReportType] = mapped_column(
|
||||||
|
Enum(ReportType, name="report_type_enum", native_enum=False, length=10),
|
||||||
|
default=ReportType.ACTUAL,
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
#: The approved morning plan an end-of-day report is filed against. NULL for plans,
|
||||||
|
#: and for end-of-day reports filed before plans existed.
|
||||||
|
plan_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("daily_call_report.id", ondelete="RESTRICT")
|
||||||
|
)
|
||||||
status: Mapped[DCRStatus] = mapped_column(
|
status: Mapped[DCRStatus] = mapped_column(
|
||||||
Enum(DCRStatus, name="dcr_status_enum", native_enum=False, length=20),
|
Enum(DCRStatus, name="dcr_status_enum", native_enum=False, length=20),
|
||||||
default=DCRStatus.DRAFT,
|
default=DCRStatus.DRAFT,
|
||||||
@@ -81,6 +104,16 @@ class DailyCallReport(Base, UUIDMixin, TimestampMixin):
|
|||||||
chemist_calls: Mapped[list["ChemistCall"]] = relationship(
|
chemist_calls: Mapped[list["ChemistCall"]] = relationship(
|
||||||
back_populates="dcr", cascade="all, delete-orphan", lazy="selectin"
|
back_populates="dcr", cascade="all, delete-orphan", lazy="selectin"
|
||||||
)
|
)
|
||||||
|
missed_visits: Mapped[list["MissedVisit"]] = relationship(
|
||||||
|
back_populates="dcr", cascade="all, delete-orphan", lazy="selectin"
|
||||||
|
)
|
||||||
|
#: Loaded explicitly by the repository (self-referential, so never eagerly by default).
|
||||||
|
plan: Mapped["DailyCallReport | None"] = relationship(
|
||||||
|
remote_side="DailyCallReport.id", foreign_keys=[plan_id], back_populates="actual"
|
||||||
|
)
|
||||||
|
actual: Mapped["DailyCallReport | None"] = relationship(
|
||||||
|
foreign_keys=[plan_id], back_populates="plan", uselist=False
|
||||||
|
)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def is_locked(self) -> bool:
|
def is_locked(self) -> bool:
|
||||||
@@ -103,18 +136,25 @@ class DoctorCall(Base, UUIDMixin, TimestampMixin):
|
|||||||
doctor_id: Mapped[uuid.UUID] = mapped_column(
|
doctor_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
PGUUID(as_uuid=True), ForeignKey("doctor.id", ondelete="RESTRICT"), nullable=False
|
PGUUID(as_uuid=True), ForeignKey("doctor.id", ondelete="RESTRICT"), nullable=False
|
||||||
)
|
)
|
||||||
|
#: On a plan this is the planned time; on an end-of-day report, when the visit happened.
|
||||||
visit_time: Mapped[time] = mapped_column(Time, nullable=False)
|
visit_time: Mapped[time] = mapped_column(Time, nullable=False)
|
||||||
call_outcome: Mapped[CallOutcome] = mapped_column(
|
#: Required on an end-of-day report; a planned visit has no outcome yet (NULL).
|
||||||
Enum(CallOutcome, name="call_outcome_enum", native_enum=False, length=20),
|
call_outcome: Mapped[CallOutcome | None] = mapped_column(
|
||||||
nullable=False,
|
Enum(CallOutcome, name="call_outcome_enum", native_enum=False, length=20)
|
||||||
)
|
)
|
||||||
#: V7 — only permitted when the doctor is a core doctor.
|
#: V7 — only permitted when the doctor is a core doctor.
|
||||||
conversion_status: Mapped[ConversionStatus | None] = mapped_column(
|
conversion_status: Mapped[ConversionStatus | None] = mapped_column(
|
||||||
Enum(ConversionStatus, name="conversion_status_enum", native_enum=False, length=20)
|
Enum(ConversionStatus, name="conversion_status_enum", native_enum=False, length=20)
|
||||||
)
|
)
|
||||||
#: The printed form's "PRODUCT PROMOTE" and "PRODUCT SAMPLE" columns.
|
#: The printed form's "PRODUCT PROMOTE" and "PRODUCT SAMPLE" columns; several per visit.
|
||||||
product_promote: Mapped[str | None] = mapped_column(String(200))
|
product_promote: Mapped[list[str]] = mapped_column(
|
||||||
product_sample: Mapped[str | None] = mapped_column(String(200))
|
ARRAY(String(200)), default=list, server_default="{}", nullable=False
|
||||||
|
)
|
||||||
|
product_sample: Mapped[list[str]] = mapped_column(
|
||||||
|
ARRAY(String(200)), default=list, server_default="{}", nullable=False
|
||||||
|
)
|
||||||
|
#: A gift given to the doctor on this visit, typed in by the MR.
|
||||||
|
gift: Mapped[str | None] = mapped_column(String(200))
|
||||||
remarks: Mapped[str | None] = mapped_column(Text)
|
remarks: Mapped[str | None] = mapped_column(Text)
|
||||||
|
|
||||||
dcr: Mapped["DailyCallReport"] = relationship(back_populates="doctor_calls")
|
dcr: Mapped["DailyCallReport"] = relationship(back_populates="doctor_calls")
|
||||||
@@ -142,3 +182,34 @@ class ChemistCall(Base, UUIDMixin, TimestampMixin):
|
|||||||
|
|
||||||
dcr: Mapped["DailyCallReport"] = relationship(back_populates="chemist_calls")
|
dcr: Mapped["DailyCallReport"] = relationship(back_populates="chemist_calls")
|
||||||
chemist: Mapped["Chemist"] = relationship(lazy="selectin") # noqa: F821
|
chemist: Mapped["Chemist"] = relationship(lazy="selectin") # noqa: F821
|
||||||
|
|
||||||
|
|
||||||
|
class MissedVisit(Base, UUIDMixin, TimestampMixin):
|
||||||
|
"""Why a doctor or chemist on the approved plan was not visited that day.
|
||||||
|
|
||||||
|
Belongs to the end-of-day report; exactly one of doctor/chemist is set.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "missed_visit"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("dcr_id", "doctor_id", name="uq_missed_dcr_doctor"),
|
||||||
|
UniqueConstraint("dcr_id", "chemist_id", name="uq_missed_dcr_chemist"),
|
||||||
|
CheckConstraint(
|
||||||
|
"(doctor_id IS NULL) <> (chemist_id IS NULL)", name="ck_missed_one_target"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
dcr_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True),
|
||||||
|
ForeignKey("daily_call_report.id", ondelete="CASCADE"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
doctor_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("doctor.id", ondelete="RESTRICT")
|
||||||
|
)
|
||||||
|
chemist_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("chemist.id", ondelete="RESTRICT")
|
||||||
|
)
|
||||||
|
reason: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
|
||||||
|
dcr: Mapped["DailyCallReport"] = relationship(back_populates="missed_visits")
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from datetime import date
|
|||||||
from sqlalchemy import func, select
|
from sqlalchemy import func, select
|
||||||
from sqlalchemy.orm import selectinload
|
from sqlalchemy.orm import selectinload
|
||||||
|
|
||||||
from app.common.enums import DCRStatus
|
from app.common.enums import DCRStatus, ReportType
|
||||||
from app.common.repository import BaseRepository
|
from app.common.repository import BaseRepository
|
||||||
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall
|
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall
|
||||||
|
|
||||||
@@ -19,8 +19,17 @@ class DCRRepository(BaseRepository[DailyCallReport]):
|
|||||||
.options(
|
.options(
|
||||||
selectinload(DailyCallReport.doctor_calls).selectinload(DoctorCall.doctor),
|
selectinload(DailyCallReport.doctor_calls).selectinload(DoctorCall.doctor),
|
||||||
selectinload(DailyCallReport.chemist_calls).selectinload(ChemistCall.chemist),
|
selectinload(DailyCallReport.chemist_calls).selectinload(ChemistCall.chemist),
|
||||||
|
selectinload(DailyCallReport.missed_visits),
|
||||||
selectinload(DailyCallReport.mr),
|
selectinload(DailyCallReport.mr),
|
||||||
selectinload(DailyCallReport.headquarters),
|
selectinload(DailyCallReport.headquarters),
|
||||||
|
# The plan's visits are the checklist an end-of-day report is measured against.
|
||||||
|
selectinload(DailyCallReport.plan)
|
||||||
|
.selectinload(DailyCallReport.doctor_calls)
|
||||||
|
.selectinload(DoctorCall.doctor),
|
||||||
|
selectinload(DailyCallReport.plan)
|
||||||
|
.selectinload(DailyCallReport.chemist_calls)
|
||||||
|
.selectinload(ChemistCall.chemist),
|
||||||
|
selectinload(DailyCallReport.actual),
|
||||||
)
|
)
|
||||||
# The session keeps objects after commit (expire_on_commit=False), so without this the
|
# The session keeps objects after commit (expire_on_commit=False), so without this the
|
||||||
# report comes back with the call lists it had *before* an add or remove.
|
# report comes back with the call lists it had *before* an add or remove.
|
||||||
@@ -29,12 +38,13 @@ class DCRRepository(BaseRepository[DailyCallReport]):
|
|||||||
return (await self.db.execute(stmt)).scalar_one_or_none()
|
return (await self.db.execute(stmt)).scalar_one_or_none()
|
||||||
|
|
||||||
async def get_for_date(
|
async def get_for_date(
|
||||||
self, mr_user_id: uuid.UUID, report_date: date
|
self, mr_user_id: uuid.UUID, report_date: date, report_type: ReportType
|
||||||
) -> DailyCallReport | None:
|
) -> DailyCallReport | None:
|
||||||
"""V1 pre-check. The database unique constraint is the real guarantee."""
|
"""V1 pre-check. The database unique constraint is the real guarantee."""
|
||||||
stmt = select(DailyCallReport).where(
|
stmt = select(DailyCallReport).where(
|
||||||
DailyCallReport.mr_user_id == mr_user_id,
|
DailyCallReport.mr_user_id == mr_user_id,
|
||||||
DailyCallReport.report_date == report_date,
|
DailyCallReport.report_date == report_date,
|
||||||
|
DailyCallReport.report_type == report_type,
|
||||||
)
|
)
|
||||||
return (await self.db.execute(stmt)).scalar_one_or_none()
|
return (await self.db.execute(stmt)).scalar_one_or_none()
|
||||||
|
|
||||||
@@ -46,6 +56,7 @@ class DCRRepository(BaseRepository[DailyCallReport]):
|
|||||||
status: DCRStatus | None,
|
status: DCRStatus | None,
|
||||||
date_from: date | None,
|
date_from: date | None,
|
||||||
date_to: date | None,
|
date_to: date | None,
|
||||||
|
report_type: ReportType | None = None,
|
||||||
):
|
):
|
||||||
stmt = select(DailyCallReport)
|
stmt = select(DailyCallReport)
|
||||||
if mr_user_id is not None:
|
if mr_user_id is not None:
|
||||||
@@ -55,6 +66,12 @@ class DCRRepository(BaseRepository[DailyCallReport]):
|
|||||||
stmt = stmt.where(DailyCallReport.headquarters_id.in_(hq_ids or [None]))
|
stmt = stmt.where(DailyCallReport.headquarters_id.in_(hq_ids or [None]))
|
||||||
if status is not None:
|
if status is not None:
|
||||||
stmt = stmt.where(DailyCallReport.status == status)
|
stmt = stmt.where(DailyCallReport.status == status)
|
||||||
|
if report_type is not None:
|
||||||
|
stmt = stmt.where(DailyCallReport.report_type == report_type)
|
||||||
|
else:
|
||||||
|
# Without a type, lists and counts cover the MR approval workflow; an Area
|
||||||
|
# Manager's own SELF reports are asked for by type.
|
||||||
|
stmt = stmt.where(DailyCallReport.report_type != ReportType.SELF)
|
||||||
if date_from is not None:
|
if date_from is not None:
|
||||||
stmt = stmt.where(DailyCallReport.report_date >= date_from)
|
stmt = stmt.where(DailyCallReport.report_date >= date_from)
|
||||||
if date_to is not None:
|
if date_to is not None:
|
||||||
@@ -69,13 +86,14 @@ class DCRRepository(BaseRepository[DailyCallReport]):
|
|||||||
status: DCRStatus | None = None,
|
status: DCRStatus | None = None,
|
||||||
date_from: date | None = None,
|
date_from: date | None = None,
|
||||||
date_to: date | None = None,
|
date_to: date | None = None,
|
||||||
|
report_type: ReportType | None = None,
|
||||||
limit: int = 50,
|
limit: int = 50,
|
||||||
offset: int = 0,
|
offset: int = 0,
|
||||||
) -> list[DailyCallReport]:
|
) -> list[DailyCallReport]:
|
||||||
stmt = (
|
stmt = (
|
||||||
self._scoped(
|
self._scoped(
|
||||||
mr_user_id=mr_user_id, hq_ids=hq_ids, status=status,
|
mr_user_id=mr_user_id, hq_ids=hq_ids, status=status,
|
||||||
date_from=date_from, date_to=date_to,
|
date_from=date_from, date_to=date_to, report_type=report_type,
|
||||||
)
|
)
|
||||||
.options(
|
.options(
|
||||||
selectinload(DailyCallReport.doctor_calls),
|
selectinload(DailyCallReport.doctor_calls),
|
||||||
|
|||||||
+49
-11
@@ -5,7 +5,7 @@ from fastapi import APIRouter, Depends, Query, Request, Response, status
|
|||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.auth.dependencies import client_ip, get_current_user, require_role
|
from app.auth.dependencies import client_ip, get_current_user, require_role
|
||||||
from app.common.enums import DCRStatus, Role
|
from app.common.enums import DCRStatus, ReportType, Role
|
||||||
from app.common.exceptions import ValidationError
|
from app.common.exceptions import ValidationError
|
||||||
from app.database.session import get_db
|
from app.database.session import get_db
|
||||||
from app.pdf.service import PDFService
|
from app.pdf.service import PDFService
|
||||||
@@ -17,6 +17,7 @@ from app.reports.schemas import (
|
|||||||
DCRRead,
|
DCRRead,
|
||||||
DCRUpdate,
|
DCRUpdate,
|
||||||
DoctorCallCreate,
|
DoctorCallCreate,
|
||||||
|
MissedVisitSet,
|
||||||
ReturnRequest,
|
ReturnRequest,
|
||||||
StatusCounts,
|
StatusCounts,
|
||||||
)
|
)
|
||||||
@@ -33,17 +34,22 @@ router = APIRouter(prefix="/dcr", tags=["reports"])
|
|||||||
@router.get("", response_model=list[DCRListItem])
|
@router.get("", response_model=list[DCRListItem])
|
||||||
async def list_reports(
|
async def list_reports(
|
||||||
status_filter: DCRStatus | None = Query(default=None, alias="status"),
|
status_filter: DCRStatus | None = Query(default=None, alias="status"),
|
||||||
|
report_type: ReportType | None = Query(default=None, alias="type"),
|
||||||
date_from: date | None = None,
|
date_from: date | None = None,
|
||||||
date_to: date | None = None,
|
date_to: date | None = None,
|
||||||
limit: int = Query(default=50, ge=1, le=200),
|
limit: int = Query(default=50, ge=1, le=200),
|
||||||
offset: int = Query(default=0, ge=0),
|
offset: int = Query(default=0, ge=0),
|
||||||
|
headquarters_id: uuid.UUID | None = None,
|
||||||
current_user: User = Depends(get_current_user),
|
current_user: User = Depends(get_current_user),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> list[DCRListItem]:
|
) -> list[DCRListItem]:
|
||||||
"""S2 (MR) and S6 (manager queue). Scope is applied in the service, never here."""
|
"""S2 (MR) and S6 (manager queue). Scope is applied in the service, never here;
|
||||||
|
`headquarters_id` only narrows a manager's list to one of their headquarters."""
|
||||||
reports = await DCRService(db).list_for(
|
reports = await DCRService(db).list_for(
|
||||||
current_user,
|
current_user,
|
||||||
|
headquarters_id=headquarters_id,
|
||||||
status=status_filter,
|
status=status_filter,
|
||||||
|
report_type=report_type,
|
||||||
date_from=date_from,
|
date_from=date_from,
|
||||||
date_to=date_to,
|
date_to=date_to,
|
||||||
limit=limit,
|
limit=limit,
|
||||||
@@ -54,10 +60,12 @@ async def list_reports(
|
|||||||
|
|
||||||
@router.get("/counts", response_model=StatusCounts)
|
@router.get("/counts", response_model=StatusCounts)
|
||||||
async def status_counts(
|
async def status_counts(
|
||||||
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
|
headquarters_id: uuid.UUID | None = None,
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> StatusCounts:
|
) -> StatusCounts:
|
||||||
"""Header counts — the deliberate, cheap replacement for the cut dashboards."""
|
"""Header counts — the deliberate, cheap replacement for the cut dashboards."""
|
||||||
return StatusCounts(**await DCRService(db).counts_for(current_user))
|
return StatusCounts(**await DCRService(db).counts_for(current_user, headquarters_id))
|
||||||
|
|
||||||
|
|
||||||
@router.get("/{dcr_id}", response_model=DCRRead)
|
@router.get("/{dcr_id}", response_model=DCRRead)
|
||||||
@@ -87,7 +95,8 @@ async def download_pdf(
|
|||||||
# uses the current form layout, even for reports approved before the layout changed.
|
# uses the current form layout, even for reports approved before the layout changed.
|
||||||
content = await PDFService(db).render_bytes(dcr)
|
content = await PDFService(db).render_bytes(dcr)
|
||||||
|
|
||||||
filename = f"DCR-{dcr.mr.employee_code}-{dcr.report_date.isoformat()}.pdf"
|
prefix = {ReportType.PLAN: "PLAN", ReportType.SELF: "DCR-SELF"}.get(dcr.report_type, "DCR")
|
||||||
|
filename = f"{prefix}-{dcr.mr.employee_code}-{dcr.report_date.isoformat()}.pdf"
|
||||||
return Response(
|
return Response(
|
||||||
content=content,
|
content=content,
|
||||||
media_type="application/pdf",
|
media_type="application/pdf",
|
||||||
@@ -102,7 +111,7 @@ async def download_pdf(
|
|||||||
async def create_report(
|
async def create_report(
|
||||||
payload: DCRCreate,
|
payload: DCRCreate,
|
||||||
request: Request,
|
request: Request,
|
||||||
current_user: User = Depends(require_role(Role.MR)),
|
current_user: User = Depends(require_role(Role.MR, Role.AM)),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> DCRRead:
|
) -> DCRRead:
|
||||||
return to_read(await DCRService(db).create(payload, current_user, client_ip(request)))
|
return to_read(await DCRService(db).create(payload, current_user, client_ip(request)))
|
||||||
@@ -113,7 +122,7 @@ async def update_report(
|
|||||||
dcr_id: uuid.UUID,
|
dcr_id: uuid.UUID,
|
||||||
payload: DCRUpdate,
|
payload: DCRUpdate,
|
||||||
request: Request,
|
request: Request,
|
||||||
current_user: User = Depends(require_role(Role.MR)),
|
current_user: User = Depends(require_role(Role.MR, Role.AM)),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> DCRRead:
|
) -> DCRRead:
|
||||||
return to_read(
|
return to_read(
|
||||||
@@ -128,7 +137,7 @@ async def add_doctor_call(
|
|||||||
dcr_id: uuid.UUID,
|
dcr_id: uuid.UUID,
|
||||||
payload: DoctorCallCreate,
|
payload: DoctorCallCreate,
|
||||||
request: Request,
|
request: Request,
|
||||||
current_user: User = Depends(require_role(Role.MR)),
|
current_user: User = Depends(require_role(Role.MR, Role.AM)),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> DCRRead:
|
) -> DCRRead:
|
||||||
return to_read(
|
return to_read(
|
||||||
@@ -141,7 +150,7 @@ async def add_chemist_call(
|
|||||||
dcr_id: uuid.UUID,
|
dcr_id: uuid.UUID,
|
||||||
payload: ChemistCallCreate,
|
payload: ChemistCallCreate,
|
||||||
request: Request,
|
request: Request,
|
||||||
current_user: User = Depends(require_role(Role.MR)),
|
current_user: User = Depends(require_role(Role.MR, Role.AM)),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> DCRRead:
|
) -> DCRRead:
|
||||||
return to_read(
|
return to_read(
|
||||||
@@ -154,7 +163,7 @@ async def delete_call(
|
|||||||
dcr_id: uuid.UUID,
|
dcr_id: uuid.UUID,
|
||||||
call_id: uuid.UUID,
|
call_id: uuid.UUID,
|
||||||
request: Request,
|
request: Request,
|
||||||
current_user: User = Depends(require_role(Role.MR)),
|
current_user: User = Depends(require_role(Role.MR, Role.AM)),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> DCRRead:
|
) -> DCRRead:
|
||||||
return to_read(
|
return to_read(
|
||||||
@@ -162,6 +171,35 @@ async def delete_call(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{dcr_id}/missed", response_model=DCRRead)
|
||||||
|
async def set_missed_reason(
|
||||||
|
dcr_id: uuid.UUID,
|
||||||
|
payload: MissedVisitSet,
|
||||||
|
request: Request,
|
||||||
|
current_user: User = Depends(require_role(Role.MR)),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> DCRRead:
|
||||||
|
"""End-of-day report: why a doctor or chemist on the day plan was not visited."""
|
||||||
|
return to_read(
|
||||||
|
await DCRService(db).set_missed_reason(dcr_id, payload, current_user, client_ip(request))
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{dcr_id}/missed/{missed_id}", response_model=DCRRead)
|
||||||
|
async def clear_missed_reason(
|
||||||
|
dcr_id: uuid.UUID,
|
||||||
|
missed_id: uuid.UUID,
|
||||||
|
request: Request,
|
||||||
|
current_user: User = Depends(require_role(Role.MR)),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> DCRRead:
|
||||||
|
return to_read(
|
||||||
|
await DCRService(db).clear_missed_reason(
|
||||||
|
dcr_id, missed_id, current_user, client_ip(request)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# ------------------------------------------------------------- transitions
|
# ------------------------------------------------------------- transitions
|
||||||
|
|
||||||
|
|
||||||
@@ -169,7 +207,7 @@ async def delete_call(
|
|||||||
async def submit(
|
async def submit(
|
||||||
dcr_id: uuid.UUID,
|
dcr_id: uuid.UUID,
|
||||||
request: Request,
|
request: Request,
|
||||||
current_user: User = Depends(require_role(Role.MR)),
|
current_user: User = Depends(require_role(Role.MR, Role.AM)),
|
||||||
db: AsyncSession = Depends(get_db),
|
db: AsyncSession = Depends(get_db),
|
||||||
) -> DCRRead:
|
) -> DCRRead:
|
||||||
return to_read(await DCRService(db).submit(dcr_id, current_user, client_ip(request)))
|
return to_read(await DCRService(db).submit(dcr_id, current_user, client_ip(request)))
|
||||||
|
|||||||
+71
-8
@@ -1,22 +1,49 @@
|
|||||||
import uuid
|
import uuid
|
||||||
from datetime import date, datetime, time
|
from datetime import date, datetime, time
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field
|
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||||
|
|
||||||
from app.common.enums import CallOutcome, ConversionStatus, DCRStatus, Role
|
from app.common.enums import CallOutcome, ConversionStatus, DCRStatus, ReportType, Role
|
||||||
from app.config.settings import settings
|
from app.config.settings import settings
|
||||||
|
|
||||||
|
#: How many promoted (or sample) products one doctor visit may name.
|
||||||
|
MAX_PRODUCTS_PER_VISIT = 10
|
||||||
|
|
||||||
|
|
||||||
|
def _product_list(value: str | list[str] | None) -> list[str]:
|
||||||
|
"""Trimmed, de-duplicated product names. A single string is still accepted."""
|
||||||
|
items = [value] if isinstance(value, str) else value or []
|
||||||
|
names: list[str] = []
|
||||||
|
for item in items:
|
||||||
|
if not isinstance(item, str):
|
||||||
|
raise ValueError("Product names must be text")
|
||||||
|
name = item.strip()
|
||||||
|
if len(name) > 200:
|
||||||
|
raise ValueError("A product name must be 200 characters or fewer")
|
||||||
|
if name and name.casefold() not in {n.casefold() for n in names}:
|
||||||
|
names.append(name)
|
||||||
|
if len(names) > MAX_PRODUCTS_PER_VISIT:
|
||||||
|
raise ValueError(f"Choose at most {MAX_PRODUCTS_PER_VISIT} products")
|
||||||
|
return names
|
||||||
|
|
||||||
|
|
||||||
class DoctorCallCreate(BaseModel):
|
class DoctorCallCreate(BaseModel):
|
||||||
doctor_id: uuid.UUID
|
doctor_id: uuid.UUID
|
||||||
visit_time: time
|
visit_time: time
|
||||||
call_outcome: CallOutcome
|
#: Required on an end-of-day report; ignored on a plan (a planned visit has no outcome).
|
||||||
|
call_outcome: CallOutcome | None = None
|
||||||
#: V7 — accepted only when the doctor is flagged as a core doctor.
|
#: V7 — accepted only when the doctor is flagged as a core doctor.
|
||||||
conversion_status: ConversionStatus | None = None
|
conversion_status: ConversionStatus | None = None
|
||||||
product_promote: str | None = Field(default=None, max_length=200)
|
product_promote: list[str] = Field(default_factory=list)
|
||||||
product_sample: str | None = Field(default=None, max_length=200)
|
product_sample: list[str] = Field(default_factory=list)
|
||||||
|
gift: str | None = Field(default=None, max_length=200)
|
||||||
remarks: str | None = Field(default=None, max_length=2000)
|
remarks: str | None = Field(default=None, max_length=2000)
|
||||||
|
|
||||||
|
_products = field_validator("product_promote", "product_sample", mode="before")(
|
||||||
|
_product_list
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class ChemistCallCreate(BaseModel):
|
class ChemistCallCreate(BaseModel):
|
||||||
chemist_id: uuid.UUID
|
chemist_id: uuid.UUID
|
||||||
@@ -34,10 +61,11 @@ class DoctorCallRead(BaseModel):
|
|||||||
doctor_speciality: str | None
|
doctor_speciality: str | None
|
||||||
is_core_doctor: bool
|
is_core_doctor: bool
|
||||||
visit_time: time
|
visit_time: time
|
||||||
call_outcome: CallOutcome
|
call_outcome: CallOutcome | None
|
||||||
conversion_status: ConversionStatus | None
|
conversion_status: ConversionStatus | None
|
||||||
product_promote: str | None
|
product_promote: list[str]
|
||||||
product_sample: str | None
|
product_sample: list[str]
|
||||||
|
gift: str | None = None
|
||||||
remarks: str | None
|
remarks: str | None
|
||||||
|
|
||||||
|
|
||||||
@@ -54,6 +82,9 @@ class ChemistCallRead(BaseModel):
|
|||||||
|
|
||||||
class DCRCreate(BaseModel):
|
class DCRCreate(BaseModel):
|
||||||
report_date: date
|
report_date: date
|
||||||
|
report_type: ReportType = ReportType.ACTUAL
|
||||||
|
#: SELF reports only: which of the Area Manager's headquarters the visits were in.
|
||||||
|
headquarters_id: uuid.UUID | None = None
|
||||||
mr_remarks: str | None = Field(default=None, max_length=2000)
|
mr_remarks: str | None = Field(default=None, max_length=2000)
|
||||||
doctor_calls: list[DoctorCallCreate] = Field(default_factory=list)
|
doctor_calls: list[DoctorCallCreate] = Field(default_factory=list)
|
||||||
chemist_calls: list[ChemistCallCreate] = Field(default_factory=list)
|
chemist_calls: list[ChemistCallCreate] = Field(default_factory=list)
|
||||||
@@ -65,6 +96,31 @@ class DCRUpdate(BaseModel):
|
|||||||
order_value: str | None = Field(default=None, max_length=100)
|
order_value: str | None = Field(default=None, max_length=100)
|
||||||
|
|
||||||
|
|
||||||
|
class MissedVisitSet(BaseModel):
|
||||||
|
"""Why one planned doctor OR chemist was not visited (end-of-day report only)."""
|
||||||
|
|
||||||
|
doctor_id: uuid.UUID | None = None
|
||||||
|
chemist_id: uuid.UUID | None = None
|
||||||
|
reason: str = Field(min_length=3, max_length=500)
|
||||||
|
|
||||||
|
|
||||||
|
class PlannedVisitRead(BaseModel):
|
||||||
|
"""One line of the approved plan, checked against the end-of-day report.
|
||||||
|
|
||||||
|
VISITED — the MR recorded a visit; MISSED — the MR explained why not;
|
||||||
|
PENDING — neither yet (the report cannot be submitted while any remain).
|
||||||
|
"""
|
||||||
|
|
||||||
|
kind: Literal["DOCTOR", "CHEMIST"]
|
||||||
|
target_id: uuid.UUID
|
||||||
|
name: str
|
||||||
|
is_core_doctor: bool
|
||||||
|
planned_time: time
|
||||||
|
status: Literal["VISITED", "MISSED", "PENDING"]
|
||||||
|
missed_visit_id: uuid.UUID | None
|
||||||
|
missed_reason: str | None
|
||||||
|
|
||||||
|
|
||||||
class ReturnRequest(BaseModel):
|
class ReturnRequest(BaseModel):
|
||||||
"""V8 — a manager must say WHY. This reason is what makes the audit trail useful."""
|
"""V8 — a manager must say WHY. This reason is what makes the audit trail useful."""
|
||||||
|
|
||||||
@@ -82,6 +138,7 @@ class DCRListItem(BaseModel):
|
|||||||
|
|
||||||
id: uuid.UUID
|
id: uuid.UUID
|
||||||
report_date: date
|
report_date: date
|
||||||
|
report_type: ReportType
|
||||||
status: DCRStatus
|
status: DCRStatus
|
||||||
mr_user_id: uuid.UUID
|
mr_user_id: uuid.UUID
|
||||||
mr_name: str
|
mr_name: str
|
||||||
@@ -104,8 +161,12 @@ class DCRRead(BaseModel):
|
|||||||
headquarters_id: uuid.UUID
|
headquarters_id: uuid.UUID
|
||||||
headquarters_name: str
|
headquarters_name: str
|
||||||
report_date: date
|
report_date: date
|
||||||
|
report_type: ReportType
|
||||||
status: DCRStatus
|
status: DCRStatus
|
||||||
is_locked: bool
|
is_locked: bool
|
||||||
|
#: End-of-day report → its plan; plan → its end-of-day report, once started.
|
||||||
|
plan_id: uuid.UUID | None
|
||||||
|
actual_report_id: uuid.UUID | None
|
||||||
mr_remarks: str | None
|
mr_remarks: str | None
|
||||||
stockist_visit: str | None
|
stockist_visit: str | None
|
||||||
order_value: str | None
|
order_value: str | None
|
||||||
@@ -115,6 +176,8 @@ class DCRRead(BaseModel):
|
|||||||
approved_at: datetime | None
|
approved_at: datetime | None
|
||||||
doctor_calls: list[DoctorCallRead]
|
doctor_calls: list[DoctorCallRead]
|
||||||
chemist_calls: list[ChemistCallRead]
|
chemist_calls: list[ChemistCallRead]
|
||||||
|
#: End-of-day report only: the approved plan, line by line, with what became of it.
|
||||||
|
planned_visits: list[PlannedVisitRead]
|
||||||
|
|
||||||
|
|
||||||
class StatusCounts(BaseModel):
|
class StatusCounts(BaseModel):
|
||||||
|
|||||||
@@ -6,9 +6,42 @@ from app.reports.schemas import (
|
|||||||
DCRListItem,
|
DCRListItem,
|
||||||
DCRRead,
|
DCRRead,
|
||||||
DoctorCallRead,
|
DoctorCallRead,
|
||||||
|
PlannedVisitRead,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def planned_visits(dcr: DailyCallReport) -> list[PlannedVisitRead]:
|
||||||
|
"""The approved plan, line by line, checked against this end-of-day report."""
|
||||||
|
plan = dcr.plan
|
||||||
|
if plan is None:
|
||||||
|
return []
|
||||||
|
visited = {c.doctor_id for c in dcr.doctor_calls} | {c.chemist_id for c in dcr.chemist_calls}
|
||||||
|
missed = {m.doctor_id or m.chemist_id: m for m in dcr.missed_visits}
|
||||||
|
|
||||||
|
def line(kind, target_id, name, is_core, planned_time) -> PlannedVisitRead:
|
||||||
|
note = missed.get(target_id)
|
||||||
|
status = "VISITED" if target_id in visited else "MISSED" if note else "PENDING"
|
||||||
|
return PlannedVisitRead(
|
||||||
|
kind=kind,
|
||||||
|
target_id=target_id,
|
||||||
|
name=name,
|
||||||
|
is_core_doctor=is_core,
|
||||||
|
planned_time=planned_time,
|
||||||
|
status=status,
|
||||||
|
missed_visit_id=note.id if note and status == "MISSED" else None,
|
||||||
|
missed_reason=note.reason if note and status == "MISSED" else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
lines = [
|
||||||
|
line("DOCTOR", c.doctor_id, c.doctor.name, c.doctor.is_core_doctor, c.visit_time)
|
||||||
|
for c in plan.doctor_calls
|
||||||
|
] + [
|
||||||
|
line("CHEMIST", c.chemist_id, c.chemist.name, False, c.visit_time)
|
||||||
|
for c in plan.chemist_calls
|
||||||
|
]
|
||||||
|
return sorted(lines, key=lambda x: x.planned_time)
|
||||||
|
|
||||||
|
|
||||||
def to_read(dcr: DailyCallReport) -> DCRRead:
|
def to_read(dcr: DailyCallReport) -> DCRRead:
|
||||||
return DCRRead(
|
return DCRRead(
|
||||||
id=dcr.id,
|
id=dcr.id,
|
||||||
@@ -18,8 +51,11 @@ def to_read(dcr: DailyCallReport) -> DCRRead:
|
|||||||
headquarters_id=dcr.headquarters_id,
|
headquarters_id=dcr.headquarters_id,
|
||||||
headquarters_name=dcr.headquarters.name,
|
headquarters_name=dcr.headquarters.name,
|
||||||
report_date=dcr.report_date,
|
report_date=dcr.report_date,
|
||||||
|
report_type=dcr.report_type,
|
||||||
status=dcr.status,
|
status=dcr.status,
|
||||||
is_locked=dcr.is_locked,
|
is_locked=dcr.is_locked,
|
||||||
|
plan_id=dcr.plan_id,
|
||||||
|
actual_report_id=dcr.actual.id if dcr.actual else None,
|
||||||
mr_remarks=dcr.mr_remarks,
|
mr_remarks=dcr.mr_remarks,
|
||||||
stockist_visit=dcr.stockist_visit,
|
stockist_visit=dcr.stockist_visit,
|
||||||
order_value=dcr.order_value,
|
order_value=dcr.order_value,
|
||||||
@@ -39,6 +75,7 @@ def to_read(dcr: DailyCallReport) -> DCRRead:
|
|||||||
conversion_status=c.conversion_status,
|
conversion_status=c.conversion_status,
|
||||||
product_promote=c.product_promote,
|
product_promote=c.product_promote,
|
||||||
product_sample=c.product_sample,
|
product_sample=c.product_sample,
|
||||||
|
gift=c.gift,
|
||||||
remarks=c.remarks,
|
remarks=c.remarks,
|
||||||
)
|
)
|
||||||
for c in sorted(dcr.doctor_calls, key=lambda x: x.visit_time)
|
for c in sorted(dcr.doctor_calls, key=lambda x: x.visit_time)
|
||||||
@@ -54,6 +91,7 @@ def to_read(dcr: DailyCallReport) -> DCRRead:
|
|||||||
)
|
)
|
||||||
for c in sorted(dcr.chemist_calls, key=lambda x: x.visit_time)
|
for c in sorted(dcr.chemist_calls, key=lambda x: x.visit_time)
|
||||||
],
|
],
|
||||||
|
planned_visits=planned_visits(dcr),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -61,6 +99,7 @@ def to_list_item(dcr: DailyCallReport) -> DCRListItem:
|
|||||||
return DCRListItem(
|
return DCRListItem(
|
||||||
id=dcr.id,
|
id=dcr.id,
|
||||||
report_date=dcr.report_date,
|
report_date=dcr.report_date,
|
||||||
|
report_type=dcr.report_type,
|
||||||
status=dcr.status,
|
status=dcr.status,
|
||||||
mr_user_id=dcr.mr_user_id,
|
mr_user_id=dcr.mr_user_id,
|
||||||
mr_name=dcr.mr.full_name,
|
mr_name=dcr.mr.full_name,
|
||||||
|
|||||||
+324
-46
@@ -2,6 +2,22 @@
|
|||||||
|
|
||||||
Routers never contain rules; repositories never contain rules. This module is the
|
Routers never contain rules; repositories never contain rules. This module is the
|
||||||
single place a reviewer needs to read to understand what the system enforces.
|
single place a reviewer needs to read to understand what the system enforces.
|
||||||
|
|
||||||
|
Plan / end-of-day rules (P1-P5):
|
||||||
|
P1 A PLAN lists the visits the MR intends to make; it carries no outcomes, and its
|
||||||
|
times are planned times, so they may be later than "now".
|
||||||
|
P2 An ACTUAL (end-of-day) report can be created only once the PLAN for that date is
|
||||||
|
APPROVED by the Area Manager; it is linked to that plan.
|
||||||
|
P3 Every planned doctor/chemist must, before submit, either have a visit recorded on
|
||||||
|
the end-of-day report or a short note saying why it was missed.
|
||||||
|
P4 Recording a visit for a doctor/chemist drops any "missed" note for them.
|
||||||
|
P5 Visits not on the plan may still be added to the end-of-day report.
|
||||||
|
|
||||||
|
Area Manager's own report (S1-S3):
|
||||||
|
S1 An Area Manager files one SELF report per date, for one headquarters they manage;
|
||||||
|
it needs no plan.
|
||||||
|
S2 Its visits may be to any active doctor or chemist of that headquarters.
|
||||||
|
S3 There is no approval: submitting it makes it final (APPROVED, locked, PDF stored).
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import uuid
|
import uuid
|
||||||
@@ -13,30 +29,37 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||||||
|
|
||||||
from app.approvals.state_machine import assert_editable, assert_transition
|
from app.approvals.state_machine import assert_editable, assert_transition
|
||||||
from app.audit.service import AuditService
|
from app.audit.service import AuditService
|
||||||
from app.auth.dependencies import assert_can_view_dcr, visible_hq_ids
|
from app.auth.dependencies import active_hq_ids_for_am, assert_can_view_dcr, visible_hq_ids
|
||||||
from app.chemists.models import Chemist, ChemistAssignment
|
from app.chemists.models import Chemist, ChemistAssignment
|
||||||
from app.common.enums import (
|
from app.common.enums import (
|
||||||
|
FIELD_ROLES,
|
||||||
AuditAction,
|
AuditAction,
|
||||||
DCRStatus,
|
DCRStatus,
|
||||||
EntityType,
|
EntityType,
|
||||||
|
MasterApproval,
|
||||||
|
ReportType,
|
||||||
Role,
|
Role,
|
||||||
WorkflowAction,
|
WorkflowAction,
|
||||||
|
FIELD_ROLES,
|
||||||
)
|
)
|
||||||
from app.common.exceptions import (
|
from app.common.exceptions import (
|
||||||
ConflictError,
|
ConflictError,
|
||||||
|
ForbiddenError,
|
||||||
NotFoundError,
|
NotFoundError,
|
||||||
ValidationError,
|
ValidationError,
|
||||||
)
|
)
|
||||||
from app.common.utils import local_now, local_today, snapshot, utcnow
|
from app.common.utils import local_now, local_today, snapshot, utcnow
|
||||||
from app.config.settings import settings
|
from app.config.settings import settings
|
||||||
from app.doctors.models import Doctor, DoctorAssignment
|
from app.doctors.models import Doctor, DoctorAssignment
|
||||||
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall
|
from app.reports.models import ChemistCall, DailyCallReport, DoctorCall, MissedVisit
|
||||||
from app.reports.repository import DCRRepository
|
from app.reports.repository import DCRRepository
|
||||||
from app.reports.schemas import ChemistCallCreate, DCRCreate, DoctorCallCreate
|
from app.reports.schemas import ChemistCallCreate, DCRCreate, DoctorCallCreate, MissedVisitSet
|
||||||
|
from app.reports.serializers import planned_visits
|
||||||
from app.users.models import User
|
from app.users.models import User
|
||||||
|
|
||||||
#: Audit fields — the columns worth recording on a state change.
|
#: Audit fields — the columns worth recording on a state change.
|
||||||
_AUDIT_FIELDS = [
|
_AUDIT_FIELDS = [
|
||||||
|
"report_type",
|
||||||
"status",
|
"status",
|
||||||
"report_date",
|
"report_date",
|
||||||
"mr_remarks",
|
"mr_remarks",
|
||||||
@@ -49,6 +72,15 @@ _AUDIT_FIELDS = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
#: Who files (and alone may edit or submit) each type of report.
|
||||||
|
_OWNER_ROLE = {ReportType.PLAN: FIELD_ROLES, ReportType.ACTUAL: FIELD_ROLES, ReportType.SELF: frozenset({Role.AM})}
|
||||||
|
_LABEL = {
|
||||||
|
ReportType.PLAN: "Daily Call Report (Plan)",
|
||||||
|
ReportType.ACTUAL: "Daily Call Report (Done)",
|
||||||
|
ReportType.SELF: "Daily Call Report (Self)",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def _clean(value: str | None) -> str | None:
|
def _clean(value: str | None) -> str | None:
|
||||||
"""Trimmed text, with blank input stored as NULL."""
|
"""Trimmed text, with blank input stored as NULL."""
|
||||||
value = (value or "").strip()
|
value = (value or "").strip()
|
||||||
@@ -65,13 +97,15 @@ class DCRService:
|
|||||||
# Validation helpers
|
# Validation helpers
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
def _validate_report_date(self, report_date: date) -> None:
|
def _validate_report_date(self, report_date: date, report_type: ReportType) -> None:
|
||||||
today = local_today()
|
today = local_today()
|
||||||
# V2 — no future reports.
|
# V2 — no future reports, except a plan, which may be made PLAN_AHEAD_DAYS ahead.
|
||||||
if report_date > today:
|
ahead = settings.PLAN_AHEAD_DAYS if report_type == ReportType.PLAN else 0
|
||||||
|
latest = today + timedelta(days=ahead)
|
||||||
|
if report_date > latest:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
"Report date cannot be in the future",
|
f"A plan can be made at most {ahead} days ahead" if ahead else "Report date cannot be in the future",
|
||||||
{"report_date": report_date.isoformat(), "today": today.isoformat()},
|
{"report_date": report_date.isoformat(), "latest_allowed": latest.isoformat()},
|
||||||
)
|
)
|
||||||
# V3 / A10 / Q8 — back-dating window.
|
# V3 / A10 / Q8 — back-dating window.
|
||||||
earliest = today - timedelta(days=settings.BACKDATING_WINDOW_DAYS)
|
earliest = today - timedelta(days=settings.BACKDATING_WINDOW_DAYS)
|
||||||
@@ -91,17 +125,49 @@ class DCRService:
|
|||||||
{"report_date": report_date.isoformat(), "deadline": deadline.isoformat()},
|
{"report_date": report_date.isoformat(), "deadline": deadline.isoformat()},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
async def _allowed_doctor_ids(self, dcr: DailyCallReport) -> set[uuid.UUID]:
|
||||||
|
"""V6 — an MR's assigned doctors; for a SELF report, those of its headquarters (S2)."""
|
||||||
|
if dcr.report_type != ReportType.SELF:
|
||||||
|
return await self._assigned_doctor_ids(dcr.mr_user_id)
|
||||||
|
stmt = select(Doctor.id).where(
|
||||||
|
Doctor.headquarters_id == dcr.headquarters_id,
|
||||||
|
Doctor.is_active.is_(True),
|
||||||
|
Doctor.approval_status == MasterApproval.APPROVED,
|
||||||
|
)
|
||||||
|
return set((await self.db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
|
async def _allowed_chemist_ids(self, dcr: DailyCallReport) -> set[uuid.UUID]:
|
||||||
|
if dcr.report_type != ReportType.SELF:
|
||||||
|
return await self._assigned_chemist_ids(dcr.mr_user_id)
|
||||||
|
stmt = select(Chemist.id).where(
|
||||||
|
Chemist.headquarters_id == dcr.headquarters_id,
|
||||||
|
Chemist.is_active.is_(True),
|
||||||
|
Chemist.approval_status == MasterApproval.APPROVED,
|
||||||
|
)
|
||||||
|
return set((await self.db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
async def _assigned_doctor_ids(self, mr_user_id: uuid.UUID) -> set[uuid.UUID]:
|
async def _assigned_doctor_ids(self, mr_user_id: uuid.UUID) -> set[uuid.UUID]:
|
||||||
stmt = select(DoctorAssignment.doctor_id).where(
|
# A doctor the MR added is visitable only once the Area Manager has approved it.
|
||||||
|
stmt = (
|
||||||
|
select(DoctorAssignment.doctor_id)
|
||||||
|
.join(Doctor, Doctor.id == DoctorAssignment.doctor_id)
|
||||||
|
.where(
|
||||||
DoctorAssignment.mr_user_id == mr_user_id,
|
DoctorAssignment.mr_user_id == mr_user_id,
|
||||||
DoctorAssignment.effective_to.is_(None),
|
DoctorAssignment.effective_to.is_(None),
|
||||||
|
Doctor.approval_status == MasterApproval.APPROVED,
|
||||||
|
)
|
||||||
)
|
)
|
||||||
return set((await self.db.execute(stmt)).scalars().all())
|
return set((await self.db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
async def _assigned_chemist_ids(self, mr_user_id: uuid.UUID) -> set[uuid.UUID]:
|
async def _assigned_chemist_ids(self, mr_user_id: uuid.UUID) -> set[uuid.UUID]:
|
||||||
stmt = select(ChemistAssignment.chemist_id).where(
|
stmt = (
|
||||||
|
select(ChemistAssignment.chemist_id)
|
||||||
|
.join(Chemist, Chemist.id == ChemistAssignment.chemist_id)
|
||||||
|
.where(
|
||||||
ChemistAssignment.mr_user_id == mr_user_id,
|
ChemistAssignment.mr_user_id == mr_user_id,
|
||||||
ChemistAssignment.effective_to.is_(None),
|
ChemistAssignment.effective_to.is_(None),
|
||||||
|
Chemist.approval_status == MasterApproval.APPROVED,
|
||||||
|
)
|
||||||
)
|
)
|
||||||
return set((await self.db.execute(stmt)).scalars().all())
|
return set((await self.db.execute(stmt)).scalars().all())
|
||||||
|
|
||||||
@@ -111,12 +177,21 @@ class DCRService:
|
|||||||
# V6 — only doctors currently assigned to this MR may be called.
|
# V6 — only doctors currently assigned to this MR may be called.
|
||||||
if payload.doctor_id not in assigned:
|
if payload.doctor_id not in assigned:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
"Doctor is not assigned to this MR",
|
"Doctor is not in this report's headquarters"
|
||||||
|
if dcr.report_type == ReportType.SELF
|
||||||
|
else "Doctor is not assigned to this MR",
|
||||||
{"doctor_id": str(payload.doctor_id)},
|
{"doctor_id": str(payload.doctor_id)},
|
||||||
)
|
)
|
||||||
doctor = await self.db.get(Doctor, payload.doctor_id)
|
doctor = await self.db.get(Doctor, payload.doctor_id)
|
||||||
if doctor is None:
|
if doctor is None:
|
||||||
raise NotFoundError("Doctor not found", {"doctor_id": str(payload.doctor_id)})
|
raise NotFoundError("Doctor not found", {"doctor_id": str(payload.doctor_id)})
|
||||||
|
# P1 — a planned visit has not happened yet, so it has no outcome.
|
||||||
|
is_plan = dcr.report_type == ReportType.PLAN
|
||||||
|
if not is_plan and payload.call_outcome is None:
|
||||||
|
raise ValidationError(
|
||||||
|
"call_outcome is required for a visit on a Daily Call Report (Done)",
|
||||||
|
{"doctor_id": str(doctor.id)},
|
||||||
|
)
|
||||||
# V7 — conversion status is meaningful only for core doctors.
|
# V7 — conversion status is meaningful only for core doctors.
|
||||||
if payload.conversion_status is not None and not doctor.is_core_doctor:
|
if payload.conversion_status is not None and not doctor.is_core_doctor:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
@@ -127,10 +202,11 @@ class DCRService:
|
|||||||
dcr_id=dcr.id,
|
dcr_id=dcr.id,
|
||||||
doctor_id=payload.doctor_id,
|
doctor_id=payload.doctor_id,
|
||||||
visit_time=payload.visit_time,
|
visit_time=payload.visit_time,
|
||||||
call_outcome=payload.call_outcome,
|
call_outcome=None if is_plan else payload.call_outcome,
|
||||||
conversion_status=payload.conversion_status,
|
conversion_status=None if is_plan else payload.conversion_status,
|
||||||
product_promote=_clean(payload.product_promote),
|
product_promote=payload.product_promote,
|
||||||
product_sample=_clean(payload.product_sample),
|
product_sample=payload.product_sample,
|
||||||
|
gift=None if is_plan else payload.gift,
|
||||||
remarks=payload.remarks,
|
remarks=payload.remarks,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -139,7 +215,10 @@ class DCRService:
|
|||||||
) -> ChemistCall:
|
) -> ChemistCall:
|
||||||
if payload.chemist_id not in assigned:
|
if payload.chemist_id not in assigned:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
"Chemist is not assigned to this MR", {"chemist_id": str(payload.chemist_id)}
|
"Chemist is not in this report's headquarters"
|
||||||
|
if dcr.report_type == ReportType.SELF
|
||||||
|
else "Chemist is not assigned to this MR",
|
||||||
|
{"chemist_id": str(payload.chemist_id)},
|
||||||
)
|
)
|
||||||
if await self.db.get(Chemist, payload.chemist_id) is None:
|
if await self.db.get(Chemist, payload.chemist_id) is None:
|
||||||
raise NotFoundError("Chemist not found", {"chemist_id": str(payload.chemist_id)})
|
raise NotFoundError("Chemist not found", {"chemist_id": str(payload.chemist_id)})
|
||||||
@@ -158,30 +237,47 @@ class DCRService:
|
|||||||
async def create(
|
async def create(
|
||||||
self, data: DCRCreate, actor: User, ip: str | None = None
|
self, data: DCRCreate, actor: User, ip: str | None = None
|
||||||
) -> DailyCallReport:
|
) -> DailyCallReport:
|
||||||
if actor.role != Role.MR or actor.headquarters_id is None:
|
if data.report_type == ReportType.SELF:
|
||||||
|
if actor.role != Role.AM:
|
||||||
|
raise ForbiddenError("Only an Area Manager files a Daily Call Report (Self)")
|
||||||
|
headquarters_id = await self._self_report_hq(actor, data.headquarters_id)
|
||||||
|
elif actor.role not in FIELD_ROLES:
|
||||||
|
raise ForbiddenError("Only an MR files a Daily Call Report (Plan) or (Done)")
|
||||||
|
elif actor.headquarters_id is None:
|
||||||
raise ValidationError("Only an MR with a headquarters can create a report")
|
raise ValidationError("Only an MR with a headquarters can create a report")
|
||||||
|
else:
|
||||||
|
headquarters_id = actor.headquarters_id # snapshot (A1)
|
||||||
|
|
||||||
self._validate_report_date(data.report_date)
|
self._validate_report_date(data.report_date, data.report_type)
|
||||||
|
|
||||||
# V1 pre-check for a friendly 409; the unique constraint below is the guarantee.
|
# V1 pre-check for a friendly 409; the unique constraint below is the guarantee.
|
||||||
if await self.repo.get_for_date(actor.id, data.report_date):
|
if await self.repo.get_for_date(actor.id, data.report_date, data.report_type):
|
||||||
raise ConflictError(
|
raise ConflictError(
|
||||||
"A report already exists for this date",
|
f"A {_LABEL[data.report_type]} already exists for this date",
|
||||||
{"report_date": data.report_date.isoformat()},
|
{
|
||||||
|
"report_date": data.report_date.isoformat(),
|
||||||
|
"report_type": data.report_type.value,
|
||||||
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
plan_id = None
|
||||||
|
if data.report_type == ReportType.ACTUAL:
|
||||||
|
plan_id = (await self._approved_plan(actor.id, data.report_date)).id
|
||||||
|
|
||||||
dcr = DailyCallReport(
|
dcr = DailyCallReport(
|
||||||
id=uuid.uuid4(),
|
id=uuid.uuid4(),
|
||||||
mr_user_id=actor.id,
|
mr_user_id=actor.id,
|
||||||
headquarters_id=actor.headquarters_id, # snapshot (A1)
|
headquarters_id=headquarters_id,
|
||||||
report_date=data.report_date,
|
report_date=data.report_date,
|
||||||
|
report_type=data.report_type,
|
||||||
|
plan_id=plan_id,
|
||||||
status=DCRStatus.DRAFT,
|
status=DCRStatus.DRAFT,
|
||||||
mr_remarks=data.mr_remarks,
|
mr_remarks=data.mr_remarks,
|
||||||
)
|
)
|
||||||
self.db.add(dcr)
|
self.db.add(dcr)
|
||||||
|
|
||||||
doctor_ids = await self._assigned_doctor_ids(actor.id)
|
doctor_ids = await self._allowed_doctor_ids(dcr)
|
||||||
chemist_ids = await self._assigned_chemist_ids(actor.id)
|
chemist_ids = await self._allowed_chemist_ids(dcr)
|
||||||
|
|
||||||
seen_doctors: set[uuid.UUID] = set()
|
seen_doctors: set[uuid.UUID] = set()
|
||||||
for payload in data.doctor_calls:
|
for payload in data.doctor_calls:
|
||||||
@@ -217,7 +313,8 @@ class DCRService:
|
|||||||
except IntegrityError as exc:
|
except IntegrityError as exc:
|
||||||
await self.db.rollback()
|
await self.db.rollback()
|
||||||
raise ConflictError(
|
raise ConflictError(
|
||||||
"A report already exists for this MR and date", {"cause": "uq_dcr_mr_date"}
|
"A report of this type already exists for this MR and date",
|
||||||
|
{"cause": "uq_dcr_mr_date_type"},
|
||||||
) from exc
|
) from exc
|
||||||
|
|
||||||
return await self.repo.get_full(dcr.id)
|
return await self.repo.get_full(dcr.id)
|
||||||
@@ -247,7 +344,7 @@ class DCRService:
|
|||||||
self, dcr_id: uuid.UUID, payload: DoctorCallCreate, actor: User, ip: str | None = None
|
self, dcr_id: uuid.UUID, payload: DoctorCallCreate, actor: User, ip: str | None = None
|
||||||
) -> DailyCallReport:
|
) -> DailyCallReport:
|
||||||
dcr = await self._get_owned_editable(dcr_id, actor)
|
dcr = await self._get_owned_editable(dcr_id, actor)
|
||||||
assigned = await self._assigned_doctor_ids(actor.id)
|
assigned = await self._allowed_doctor_ids(dcr)
|
||||||
call = await self._build_doctor_call(dcr, payload, assigned)
|
call = await self._build_doctor_call(dcr, payload, assigned)
|
||||||
self._validate_visit_time(dcr, payload.visit_time)
|
self._validate_visit_time(dcr, payload.visit_time)
|
||||||
self.db.add(call)
|
self.db.add(call)
|
||||||
@@ -264,6 +361,7 @@ class DCRService:
|
|||||||
{"doctor_id": str(payload.doctor_id), "cause": "uq_call_dcr_doctor"},
|
{"doctor_id": str(payload.doctor_id), "cause": "uq_call_dcr_doctor"},
|
||||||
) from exc
|
) from exc
|
||||||
|
|
||||||
|
await self._drop_missed_note(dcr, doctor_id=payload.doctor_id)
|
||||||
await self.audit.log(
|
await self.audit.log(
|
||||||
actor_user_id=actor.id,
|
actor_user_id=actor.id,
|
||||||
entity_type=EntityType.DCR,
|
entity_type=EntityType.DCR,
|
||||||
@@ -279,7 +377,7 @@ class DCRService:
|
|||||||
self, dcr_id: uuid.UUID, payload: ChemistCallCreate, actor: User, ip: str | None = None
|
self, dcr_id: uuid.UUID, payload: ChemistCallCreate, actor: User, ip: str | None = None
|
||||||
) -> DailyCallReport:
|
) -> DailyCallReport:
|
||||||
dcr = await self._get_owned_editable(dcr_id, actor)
|
dcr = await self._get_owned_editable(dcr_id, actor)
|
||||||
assigned = await self._assigned_chemist_ids(actor.id)
|
assigned = await self._allowed_chemist_ids(dcr)
|
||||||
call = await self._build_chemist_call(dcr, payload, assigned)
|
call = await self._build_chemist_call(dcr, payload, assigned)
|
||||||
self._validate_visit_time(dcr, payload.visit_time)
|
self._validate_visit_time(dcr, payload.visit_time)
|
||||||
self.db.add(call)
|
self.db.add(call)
|
||||||
@@ -293,6 +391,7 @@ class DCRService:
|
|||||||
{"chemist_id": str(payload.chemist_id), "cause": "uq_call_dcr_chemist"},
|
{"chemist_id": str(payload.chemist_id), "cause": "uq_call_dcr_chemist"},
|
||||||
) from exc
|
) from exc
|
||||||
|
|
||||||
|
await self._drop_missed_note(dcr, chemist_id=payload.chemist_id)
|
||||||
await self.audit.log(
|
await self.audit.log(
|
||||||
actor_user_id=actor.id,
|
actor_user_id=actor.id,
|
||||||
entity_type=EntityType.DCR,
|
entity_type=EntityType.DCR,
|
||||||
@@ -305,8 +404,8 @@ class DCRService:
|
|||||||
return await self.repo.get_full(dcr.id)
|
return await self.repo.get_full(dcr.id)
|
||||||
|
|
||||||
def _validate_visit_time(self, dcr: DailyCallReport, visit_time) -> None:
|
def _validate_visit_time(self, dcr: DailyCallReport, visit_time) -> None:
|
||||||
"""V11 — a visit time on today's report cannot be in the future."""
|
"""V11 — a visit time on today's report cannot be in the future (P1: plans excepted)."""
|
||||||
if dcr.report_date == local_today():
|
if dcr.report_type != ReportType.PLAN and dcr.report_date == local_today():
|
||||||
# Visit times are entered in the company's local time (APP_TIMEZONE), so they
|
# Visit times are entered in the company's local time (APP_TIMEZONE), so they
|
||||||
# must be compared with local "now" — not the server's UTC clock.
|
# must be compared with local "now" — not the server's UTC clock.
|
||||||
if visit_time > local_now().time() and settings.ENVIRONMENT == "production":
|
if visit_time > local_now().time() and settings.ENVIRONMENT == "production":
|
||||||
@@ -333,6 +432,79 @@ class DCRService:
|
|||||||
await self.db.commit()
|
await self.db.commit()
|
||||||
return await self.repo.get_full(dcr.id)
|
return await self.repo.get_full(dcr.id)
|
||||||
|
|
||||||
|
async def set_missed_reason(
|
||||||
|
self, dcr_id: uuid.UUID, payload: MissedVisitSet, actor: User, ip: str | None = None
|
||||||
|
) -> DailyCallReport:
|
||||||
|
"""P3 — record (or reword) why a planned doctor/chemist was not visited."""
|
||||||
|
dcr = await self._get_owned_editable(dcr_id, actor)
|
||||||
|
if dcr.report_type != ReportType.ACTUAL or dcr.plan is None:
|
||||||
|
raise ValidationError("Missed-visit notes belong on a Daily Call Report (Done)")
|
||||||
|
if (payload.doctor_id is None) == (payload.chemist_id is None):
|
||||||
|
raise ValidationError("Give exactly one of doctor_id or chemist_id")
|
||||||
|
reason = _clean(payload.reason)
|
||||||
|
if reason is None:
|
||||||
|
raise ValidationError("Say briefly why the visit was missed")
|
||||||
|
|
||||||
|
target_id = payload.doctor_id or payload.chemist_id
|
||||||
|
line = next((p for p in planned_visits(dcr) if p.target_id == target_id), None)
|
||||||
|
if line is None:
|
||||||
|
raise ValidationError(
|
||||||
|
"This doctor or chemist is not on the plan", {"target_id": str(target_id)}
|
||||||
|
)
|
||||||
|
if line.status == "VISITED":
|
||||||
|
raise ConflictError(
|
||||||
|
"A visit is already recorded for this doctor or chemist; remove it first",
|
||||||
|
{"target_id": str(target_id)},
|
||||||
|
)
|
||||||
|
|
||||||
|
note = next(
|
||||||
|
(m for m in dcr.missed_visits if (m.doctor_id or m.chemist_id) == target_id), None
|
||||||
|
)
|
||||||
|
before = {"reason": note.reason} if note else None
|
||||||
|
if note is None:
|
||||||
|
self.db.add(
|
||||||
|
MissedVisit(
|
||||||
|
dcr_id=dcr.id,
|
||||||
|
doctor_id=payload.doctor_id,
|
||||||
|
chemist_id=payload.chemist_id,
|
||||||
|
reason=reason,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
note.reason = reason
|
||||||
|
await self.audit.log(
|
||||||
|
actor_user_id=actor.id,
|
||||||
|
entity_type=EntityType.DCR,
|
||||||
|
entity_id=dcr.id,
|
||||||
|
action=AuditAction.UPDATE,
|
||||||
|
before=before,
|
||||||
|
after={"missed_visit": str(target_id), "reason": reason},
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
|
await self.db.commit()
|
||||||
|
return await self.repo.get_full(dcr.id)
|
||||||
|
|
||||||
|
async def clear_missed_reason(
|
||||||
|
self, dcr_id: uuid.UUID, missed_id: uuid.UUID, actor: User, ip: str | None = None
|
||||||
|
) -> DailyCallReport:
|
||||||
|
dcr = await self._get_owned_editable(dcr_id, actor)
|
||||||
|
note = next((m for m in dcr.missed_visits if m.id == missed_id), None)
|
||||||
|
if note is None:
|
||||||
|
raise NotFoundError(
|
||||||
|
"Missed-visit note not found on this report", {"id": str(missed_id)}
|
||||||
|
)
|
||||||
|
await self.db.delete(note)
|
||||||
|
await self.audit.log(
|
||||||
|
actor_user_id=actor.id,
|
||||||
|
entity_type=EntityType.DCR,
|
||||||
|
entity_id=dcr.id,
|
||||||
|
action=AuditAction.DELETE,
|
||||||
|
before={"missed_visit": str(note.doctor_id or note.chemist_id), "reason": note.reason},
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
|
await self.db.commit()
|
||||||
|
return await self.repo.get_full(dcr.id)
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
# Workflow transitions
|
# Workflow transitions
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
@@ -344,19 +516,18 @@ class DCRService:
|
|||||||
if dcr is None:
|
if dcr is None:
|
||||||
raise NotFoundError("Report not found", {"id": str(dcr_id)})
|
raise NotFoundError("Report not found", {"id": str(dcr_id)})
|
||||||
await assert_can_view_dcr(self.db, actor, dcr)
|
await assert_can_view_dcr(self.db, actor, dcr)
|
||||||
if dcr.mr_user_id != actor.id:
|
if dcr.mr_user_id != actor.id or actor.role not in _OWNER_ROLE[dcr.report_type]:
|
||||||
from app.common.exceptions import ForbiddenError
|
raise ForbiddenError("Only the report's owner can submit it")
|
||||||
|
|
||||||
raise ForbiddenError("Only the owning MR can submit this report")
|
if dcr.report_type == ReportType.SELF:
|
||||||
|
return await self._finalise_self_report(dcr, actor, ip)
|
||||||
|
|
||||||
if dcr.status == DCRStatus.PENDING_AM:
|
if dcr.status == DCRStatus.PENDING_AM:
|
||||||
return dcr # already submitted (a double click): nothing more to do
|
return dcr # already submitted (a double click): nothing more to do
|
||||||
|
|
||||||
transition = assert_transition(dcr.status, WorkflowAction.SUBMIT, actor.role)
|
transition = assert_transition(dcr.status, WorkflowAction.SUBMIT, actor.role)
|
||||||
|
|
||||||
# V4 — at least one doctor call is required to submit.
|
self._check_submit_contents(dcr)
|
||||||
if not dcr.doctor_calls:
|
|
||||||
raise ValidationError("A report must contain at least one doctor call to submit")
|
|
||||||
self._check_submission_deadline(dcr.report_date)
|
self._check_submission_deadline(dcr.report_date)
|
||||||
|
|
||||||
before = snapshot(dcr, _AUDIT_FIELDS)
|
before = snapshot(dcr, _AUDIT_FIELDS)
|
||||||
@@ -378,6 +549,36 @@ class DCRService:
|
|||||||
await self.db.commit()
|
await self.db.commit()
|
||||||
return await self.repo.get_full(dcr.id)
|
return await self.repo.get_full(dcr.id)
|
||||||
|
|
||||||
|
async def _finalise_self_report(
|
||||||
|
self, dcr: DailyCallReport, actor: User, ip: str | None
|
||||||
|
) -> DailyCallReport:
|
||||||
|
"""S3 — an Area Manager's own report is final once submitted; nobody approves it."""
|
||||||
|
if dcr.status == DCRStatus.APPROVED:
|
||||||
|
return dcr # already submitted (a double click)
|
||||||
|
assert_editable(dcr.status)
|
||||||
|
self._check_submit_contents(dcr)
|
||||||
|
self._check_submission_deadline(dcr.report_date)
|
||||||
|
|
||||||
|
before = snapshot(dcr, _AUDIT_FIELDS)
|
||||||
|
dcr.status = DCRStatus.APPROVED
|
||||||
|
dcr.submitted_at = dcr.approved_at = utcnow()
|
||||||
|
await self.audit.log(
|
||||||
|
actor_user_id=actor.id,
|
||||||
|
entity_type=EntityType.DCR,
|
||||||
|
entity_id=dcr.id,
|
||||||
|
action=AuditAction.SUBMIT,
|
||||||
|
before=before,
|
||||||
|
after=snapshot(dcr, _AUDIT_FIELDS),
|
||||||
|
ip_address=ip,
|
||||||
|
)
|
||||||
|
|
||||||
|
from app.pdf.service import PDFService
|
||||||
|
|
||||||
|
full = await self.repo.get_full(dcr.id)
|
||||||
|
dcr.pdf_path = await PDFService(self.db).render_and_store(full, approver=actor)
|
||||||
|
await self.db.commit()
|
||||||
|
return await self.repo.get_full(dcr.id)
|
||||||
|
|
||||||
async def return_report(
|
async def return_report(
|
||||||
self, dcr_id: uuid.UUID, reason: str, actor: User, ip: str | None = None
|
self, dcr_id: uuid.UUID, reason: str, actor: User, ip: str | None = None
|
||||||
) -> DailyCallReport:
|
) -> DailyCallReport:
|
||||||
@@ -447,16 +648,33 @@ class DCRService:
|
|||||||
await assert_can_view_dcr(self.db, actor, dcr)
|
await assert_can_view_dcr(self.db, actor, dcr)
|
||||||
return dcr
|
return dcr
|
||||||
|
|
||||||
async def list_for(self, actor: User, **filters) -> list[DailyCallReport]:
|
async def _hq_scope(
|
||||||
if actor.role == Role.MR:
|
self, actor: User, headquarters_id: uuid.UUID | None
|
||||||
|
) -> set[uuid.UUID] | None:
|
||||||
|
"""The headquarters a manager's lists cover: all they may see, or the one they chose —
|
||||||
|
narrowed, never widened (one outside their scope gives nothing)."""
|
||||||
|
allowed = await visible_hq_ids(self.db, actor)
|
||||||
|
if headquarters_id is None:
|
||||||
|
return allowed
|
||||||
|
return {headquarters_id} if allowed is None or headquarters_id in allowed else set()
|
||||||
|
|
||||||
|
async def list_for(
|
||||||
|
self, actor: User, headquarters_id: uuid.UUID | None = None, **filters
|
||||||
|
) -> list[DailyCallReport]:
|
||||||
|
# An Area Manager's SELF list is their own reports, not their headquarters'.
|
||||||
|
if actor.role in FIELD_ROLES or (
|
||||||
|
actor.role == Role.AM and filters.get("report_type") == ReportType.SELF
|
||||||
|
):
|
||||||
return await self.repo.list_scoped(mr_user_id=actor.id, **filters)
|
return await self.repo.list_scoped(mr_user_id=actor.id, **filters)
|
||||||
hq_ids = await visible_hq_ids(self.db, actor)
|
hq_ids = await self._hq_scope(actor, headquarters_id)
|
||||||
return await self.repo.list_scoped(hq_ids=hq_ids, **filters)
|
return await self.repo.list_scoped(hq_ids=hq_ids, **filters)
|
||||||
|
|
||||||
async def counts_for(self, actor: User) -> dict[str, int]:
|
async def counts_for(
|
||||||
if actor.role == Role.MR:
|
self, actor: User, headquarters_id: uuid.UUID | None = None
|
||||||
|
) -> dict[str, int]:
|
||||||
|
if actor.role in FIELD_ROLES:
|
||||||
return await self.repo.status_counts(mr_user_id=actor.id)
|
return await self.repo.status_counts(mr_user_id=actor.id)
|
||||||
return await self.repo.status_counts(hq_ids=await visible_hq_ids(self.db, actor))
|
return await self.repo.status_counts(hq_ids=await self._hq_scope(actor, headquarters_id))
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
# Internals
|
# Internals
|
||||||
@@ -468,13 +686,22 @@ class DCRService:
|
|||||||
if dcr is None:
|
if dcr is None:
|
||||||
raise NotFoundError("Report not found", {"id": str(dcr_id)})
|
raise NotFoundError("Report not found", {"id": str(dcr_id)})
|
||||||
await assert_can_view_dcr(self.db, actor, dcr)
|
await assert_can_view_dcr(self.db, actor, dcr)
|
||||||
if actor.role != Role.MR or dcr.mr_user_id != actor.id:
|
if dcr.mr_user_id != actor.id or actor.role not in _OWNER_ROLE[dcr.report_type]:
|
||||||
from app.common.exceptions import ForbiddenError
|
raise ForbiddenError("Only the report's owner can modify report data")
|
||||||
|
|
||||||
raise ForbiddenError("Only the owning MR can modify report data")
|
|
||||||
assert_editable(dcr.status)
|
assert_editable(dcr.status)
|
||||||
return dcr
|
return dcr
|
||||||
|
|
||||||
|
async def _self_report_hq(self, actor: User, headquarters_id: uuid.UUID | None) -> uuid.UUID:
|
||||||
|
"""S1 — one of the headquarters this Area Manager manages; implied when there is one."""
|
||||||
|
managed = await active_hq_ids_for_am(self.db, actor.id)
|
||||||
|
if headquarters_id is None and len(managed) == 1:
|
||||||
|
return next(iter(managed))
|
||||||
|
if headquarters_id is None:
|
||||||
|
raise ValidationError("Choose the headquarters this report is for")
|
||||||
|
if headquarters_id not in managed:
|
||||||
|
raise ForbiddenError("You do not manage this headquarters")
|
||||||
|
return headquarters_id
|
||||||
|
|
||||||
async def _get_in_scope(self, dcr_id: uuid.UUID, actor: User) -> DailyCallReport:
|
async def _get_in_scope(self, dcr_id: uuid.UUID, actor: User) -> DailyCallReport:
|
||||||
dcr = await self.repo.get_full(dcr_id)
|
dcr = await self.repo.get_full(dcr_id)
|
||||||
if dcr is None:
|
if dcr is None:
|
||||||
@@ -482,11 +709,62 @@ class DCRService:
|
|||||||
await assert_can_view_dcr(self.db, actor, dcr)
|
await assert_can_view_dcr(self.db, actor, dcr)
|
||||||
return dcr
|
return dcr
|
||||||
|
|
||||||
|
def _check_submit_contents(self, dcr: DailyCallReport) -> None:
|
||||||
|
if dcr.report_type == ReportType.PLAN:
|
||||||
|
if not dcr.doctor_calls and not dcr.chemist_calls:
|
||||||
|
raise ValidationError("Plan at least one doctor or chemist visit to submit")
|
||||||
|
return
|
||||||
|
# P3 — every planned visit is either recorded or explained.
|
||||||
|
pending = [p for p in planned_visits(dcr) if p.status == "PENDING"]
|
||||||
|
if pending:
|
||||||
|
raise ValidationError(
|
||||||
|
"Record a visit or add a missed-visit note for every planned doctor and chemist",
|
||||||
|
{"pending": [p.name for p in pending]},
|
||||||
|
)
|
||||||
|
# V4 — at least one doctor call, unless the planned visits were all explained.
|
||||||
|
if not dcr.doctor_calls and not dcr.missed_visits:
|
||||||
|
raise ValidationError("A report must contain at least one doctor call to submit")
|
||||||
|
|
||||||
|
async def _approved_plan(self, mr_user_id: uuid.UUID, report_date: date) -> DailyCallReport:
|
||||||
|
"""P2 — the end-of-day report follows an Area-Manager-approved plan."""
|
||||||
|
plan = await self.repo.get_for_date(mr_user_id, report_date, ReportType.PLAN)
|
||||||
|
if plan is None:
|
||||||
|
raise ValidationError(
|
||||||
|
"Create your Daily Call Report (Plan) for this date first; "
|
||||||
|
"the Done report follows it",
|
||||||
|
{"report_date": report_date.isoformat()},
|
||||||
|
)
|
||||||
|
if plan.status != DCRStatus.APPROVED:
|
||||||
|
raise ValidationError(
|
||||||
|
"Your Daily Call Report (Plan) for this date must be approved "
|
||||||
|
"by the Area Manager first",
|
||||||
|
{"report_date": report_date.isoformat(), "plan_status": plan.status.value},
|
||||||
|
)
|
||||||
|
return plan
|
||||||
|
|
||||||
|
async def _drop_missed_note(
|
||||||
|
self,
|
||||||
|
dcr: DailyCallReport,
|
||||||
|
doctor_id: uuid.UUID | None = None,
|
||||||
|
chemist_id: uuid.UUID | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""P4 — a recorded visit replaces any note saying it was missed."""
|
||||||
|
for note in dcr.missed_visits:
|
||||||
|
if (doctor_id and note.doctor_id == doctor_id) or (
|
||||||
|
chemist_id and note.chemist_id == chemist_id
|
||||||
|
):
|
||||||
|
await self.db.delete(note)
|
||||||
|
|
||||||
async def _current_am_for_hq(self, headquarters_id: uuid.UUID) -> uuid.UUID | None:
|
async def _current_am_for_hq(self, headquarters_id: uuid.UUID) -> uuid.UUID | None:
|
||||||
from app.organization.models import AMHeadquarters
|
from app.organization.models import AMHeadquarters
|
||||||
|
|
||||||
stmt = select(AMHeadquarters.area_manager_user_id).where(
|
# Recorded only; any Area Manager of the headquarters may act on the report.
|
||||||
|
stmt = (
|
||||||
|
select(AMHeadquarters.area_manager_user_id)
|
||||||
|
.where(
|
||||||
AMHeadquarters.headquarters_id == headquarters_id,
|
AMHeadquarters.headquarters_id == headquarters_id,
|
||||||
AMHeadquarters.effective_to.is_(None),
|
AMHeadquarters.effective_to.is_(None),
|
||||||
)
|
)
|
||||||
|
.order_by(AMHeadquarters.effective_from, AMHeadquarters.created_at)
|
||||||
|
)
|
||||||
return (await self.db.execute(stmt)).scalars().first()
|
return (await self.db.execute(stmt)).scalars().first()
|
||||||
|
|||||||
+37
-2
@@ -22,8 +22,8 @@ class User(Base, UUIDMixin, TimestampMixin):
|
|||||||
UniqueConstraint("company_id", "employee_code", name="uq_user_company_empcode"),
|
UniqueConstraint("company_id", "employee_code", name="uq_user_company_empcode"),
|
||||||
# An MR must have a headquarters; nobody else may have one (R4, R8).
|
# An MR must have a headquarters; nobody else may have one (R4, R8).
|
||||||
CheckConstraint(
|
CheckConstraint(
|
||||||
"(role = 'MR' AND headquarters_id IS NOT NULL) "
|
"(role IN ('MR', 'SFE') AND headquarters_id IS NOT NULL) "
|
||||||
"OR (role <> 'MR' AND headquarters_id IS NULL)",
|
"OR (role NOT IN ('MR', 'SFE') AND headquarters_id IS NULL)",
|
||||||
name="ck_user_mr_requires_hq",
|
name="ck_user_mr_requires_hq",
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -45,6 +45,41 @@ class User(Base, UUIDMixin, TimestampMixin):
|
|||||||
)
|
)
|
||||||
#: Checked on EVERY request, not only at login (SEC-5).
|
#: Checked on EVERY request, not only at login (SEC-5).
|
||||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||||
|
#: The one protected owner account. Nobody — not even itself — can edit, deactivate,
|
||||||
|
#: re-role or delete it through the API; a DB trigger backs that up. It acts as an
|
||||||
|
#: ADMIN everywhere (role is ADMIN), and is created only by `scripts/create_superadmin.py`.
|
||||||
|
is_superadmin: Mapped[bool] = mapped_column(
|
||||||
|
Boolean, default=False, server_default="false", nullable=False
|
||||||
|
)
|
||||||
failed_login_attempts: Mapped[int] = mapped_column(default=0, nullable=False)
|
failed_login_attempts: Mapped[int] = mapped_column(default=0, nullable=False)
|
||||||
|
|
||||||
headquarters: Mapped["Headquarters | None"] = relationship() # noqa: F821
|
headquarters: Mapped["Headquarters | None"] = relationship() # noqa: F821
|
||||||
|
#: SFE only — the other headquarters (districts) covered besides the primary one.
|
||||||
|
extra_headquarters: Mapped[list["UserExtraHeadquarters"]] = relationship(
|
||||||
|
lazy="selectin", cascade="all, delete-orphan"
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def extra_headquarter_ids(self) -> list[uuid.UUID]:
|
||||||
|
return [e.headquarters_id for e in self.extra_headquarters]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def covered_headquarter_ids(self) -> set[uuid.UUID]:
|
||||||
|
"""Every headquarters this field user works in: the primary one plus the extra ones."""
|
||||||
|
ids = set(self.extra_headquarter_ids)
|
||||||
|
if self.headquarters_id:
|
||||||
|
ids.add(self.headquarters_id)
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
class UserExtraHeadquarters(Base):
|
||||||
|
"""An SFE covers more than one district: each extra headquarters is one row here."""
|
||||||
|
|
||||||
|
__tablename__ = "user_extra_headquarters"
|
||||||
|
|
||||||
|
user_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="CASCADE"), primary_key=True
|
||||||
|
)
|
||||||
|
headquarters_id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
PGUUID(as_uuid=True), ForeignKey("headquarters.id", ondelete="RESTRICT"), primary_key=True
|
||||||
|
)
|
||||||
|
|||||||
@@ -0,0 +1,168 @@
|
|||||||
|
"""One person's whole picture for the General Manager and Admin: who they are, where they
|
||||||
|
work, who they report to, their doctors and chemists, their reports and their company forms."""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import func, select, text
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.chemists.models import Chemist, ChemistAssignment
|
||||||
|
from app.common.enums import FIELD_ROLES, ReportType, Role
|
||||||
|
from app.common.exceptions import NotFoundError
|
||||||
|
from app.csv_data.config import CSV_LABELS, FORM_ORDER, TABLES
|
||||||
|
from app.csv_data.models import FormApproval
|
||||||
|
from app.doctors.models import Doctor, DoctorAssignment
|
||||||
|
from app.organization.models import AMHeadquarters, Headquarters
|
||||||
|
from app.reports.models import DailyCallReport
|
||||||
|
from app.reports.repository import DCRRepository
|
||||||
|
from app.reports.serializers import to_list_item
|
||||||
|
from app.users.models import User
|
||||||
|
|
||||||
|
|
||||||
|
def _hq(h: Headquarters, main: bool = False) -> dict[str, Any]:
|
||||||
|
return {"id": str(h.id), "code": h.code, "name": h.name, "district": h.district, "state": h.state, "main": main}
|
||||||
|
|
||||||
|
|
||||||
|
def _person(u: User) -> dict[str, Any]:
|
||||||
|
return {"id": str(u.id), "full_name": u.full_name, "email": u.email, "role": u.role.value, "is_active": u.is_active}
|
||||||
|
|
||||||
|
|
||||||
|
async def _report_counts(db: AsyncSession, **where: Any) -> dict[str, dict[str, int]]:
|
||||||
|
stmt = select(DailyCallReport.report_type, DailyCallReport.status, func.count()).group_by(
|
||||||
|
DailyCallReport.report_type, DailyCallReport.status
|
||||||
|
)
|
||||||
|
if "mr_user_id" in where:
|
||||||
|
stmt = stmt.where(DailyCallReport.mr_user_id == where["mr_user_id"])
|
||||||
|
if "hq_ids" in where:
|
||||||
|
stmt = stmt.where(DailyCallReport.headquarters_id.in_(where["hq_ids"] or [None]))
|
||||||
|
out: dict[str, dict[str, int]] = {}
|
||||||
|
for kind, status, n in (await db.execute(stmt)).all():
|
||||||
|
out.setdefault(str(getattr(kind, "value", kind)), {})[str(getattr(status, "value", status))] = n
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
async def _forms(db: AsyncSession, user: User) -> list[dict[str, Any]]:
|
||||||
|
from app.csv_data.approval import APPROVAL_TABLES
|
||||||
|
from app.csv_data.router import HIDDEN_TABLES, PER_MR_PRODUCT_TABLES
|
||||||
|
|
||||||
|
owned = APPROVAL_TABLES | PER_MR_PRODUCT_TABLES
|
||||||
|
approvals = {
|
||||||
|
a.table_name: a.status
|
||||||
|
for a in (await db.execute(select(FormApproval).where(FormApproval.owner_user_id == user.id))).scalars()
|
||||||
|
}
|
||||||
|
out = []
|
||||||
|
for name in FORM_ORDER:
|
||||||
|
if name in HIDDEN_TABLES:
|
||||||
|
continue
|
||||||
|
columns = TABLES[name]
|
||||||
|
if name in owned:
|
||||||
|
where, params = "owner_user_id = :v", {"v": user.id}
|
||||||
|
else:
|
||||||
|
who = "name" if "name" in columns else "employee_name"
|
||||||
|
where, params = f"lower(btrim(COALESCE({who}, ''))) = :v", {"v": user.full_name.strip().lower()}
|
||||||
|
rows = (await db.execute(text(f'SELECT COUNT(*) FROM "{name}" WHERE {where}'), params)).scalar_one()
|
||||||
|
months: list[str] = []
|
||||||
|
if "month" in columns:
|
||||||
|
found = await db.execute(
|
||||||
|
text(f'SELECT DISTINCT btrim(month) FROM "{name}" WHERE {where} AND btrim(COALESCE(month, \'\')) <> \'\''),
|
||||||
|
params,
|
||||||
|
)
|
||||||
|
months = sorted(m for (m,) in found.all())
|
||||||
|
out.append(
|
||||||
|
{
|
||||||
|
"table": name,
|
||||||
|
"label": CSV_LABELS[name],
|
||||||
|
"rows": rows,
|
||||||
|
"months": months,
|
||||||
|
"approval_status": approvals.get(name, "draft") if name in APPROVAL_TABLES else None,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
async def user_overview(db: AsyncSession, actor: User, user_id: uuid.UUID) -> dict[str, Any]:
|
||||||
|
user = await db.get(User, user_id)
|
||||||
|
if user is None or user.company_id != actor.company_id:
|
||||||
|
raise NotFoundError("User not found")
|
||||||
|
repo = DCRRepository(db)
|
||||||
|
data: dict[str, Any] = {
|
||||||
|
"user": {
|
||||||
|
"id": str(user.id), "full_name": user.full_name, "email": user.email,
|
||||||
|
"employee_code": user.employee_code, "phone": user.phone, "role": user.role.value,
|
||||||
|
"is_active": user.is_active, "is_superadmin": user.is_superadmin,
|
||||||
|
},
|
||||||
|
"headquarters": [], "reporting_managers": [], "doctors": [], "chemists": [],
|
||||||
|
"reports": {"counts": {}, "recent": []}, "forms": [], "team": [], "own_reports": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
if user.role in FIELD_ROLES:
|
||||||
|
covered = (
|
||||||
|
await db.execute(select(Headquarters).where(Headquarters.id.in_(user.covered_headquarter_ids or [None])))
|
||||||
|
).scalars().all()
|
||||||
|
data["headquarters"] = sorted((_hq(h, h.id == user.headquarters_id) for h in covered), key=lambda h: not h["main"])
|
||||||
|
if user.headquarters_id:
|
||||||
|
managers = (
|
||||||
|
await db.execute(
|
||||||
|
select(User)
|
||||||
|
.join(AMHeadquarters, AMHeadquarters.area_manager_user_id == User.id)
|
||||||
|
.where(AMHeadquarters.headquarters_id == user.headquarters_id, AMHeadquarters.effective_to.is_(None))
|
||||||
|
.order_by(User.full_name)
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
data["reporting_managers"] = [_person(m) for m in managers]
|
||||||
|
doctors = await db.execute(
|
||||||
|
select(Doctor, Headquarters.name)
|
||||||
|
.join(DoctorAssignment, DoctorAssignment.doctor_id == Doctor.id)
|
||||||
|
.join(Headquarters, Headquarters.id == Doctor.headquarters_id)
|
||||||
|
.where(DoctorAssignment.mr_user_id == user.id, DoctorAssignment.effective_to.is_(None))
|
||||||
|
.order_by(Doctor.name)
|
||||||
|
)
|
||||||
|
data["doctors"] = [
|
||||||
|
{"id": str(d.id), "name": d.name, "speciality": d.speciality, "clinic_address": d.clinic_address,
|
||||||
|
"headquarters_name": hq, "is_core_doctor": d.is_core_doctor, "is_active": d.is_active}
|
||||||
|
for d, hq in doctors.all()
|
||||||
|
]
|
||||||
|
chemists = await db.execute(
|
||||||
|
select(Chemist, Headquarters.name)
|
||||||
|
.join(ChemistAssignment, ChemistAssignment.chemist_id == Chemist.id)
|
||||||
|
.join(Headquarters, Headquarters.id == Chemist.headquarters_id)
|
||||||
|
.where(ChemistAssignment.mr_user_id == user.id, ChemistAssignment.effective_to.is_(None))
|
||||||
|
.order_by(Chemist.name)
|
||||||
|
)
|
||||||
|
data["chemists"] = [
|
||||||
|
{"id": str(c.id), "name": c.name, "shop_address": c.shop_address, "headquarters_name": hq, "is_active": c.is_active}
|
||||||
|
for c, hq in chemists.all()
|
||||||
|
]
|
||||||
|
data["reports"]["counts"] = await _report_counts(db, mr_user_id=user.id)
|
||||||
|
recent = await repo.list_scoped(mr_user_id=user.id, limit=15)
|
||||||
|
data["reports"]["recent"] = [to_list_item(r).model_dump(mode="json") for r in recent]
|
||||||
|
data["forms"] = await _forms(db, user)
|
||||||
|
|
||||||
|
elif user.role == Role.AM:
|
||||||
|
managed = (
|
||||||
|
await db.execute(
|
||||||
|
select(Headquarters)
|
||||||
|
.join(AMHeadquarters, AMHeadquarters.headquarters_id == Headquarters.id)
|
||||||
|
.where(AMHeadquarters.area_manager_user_id == user.id, AMHeadquarters.effective_to.is_(None))
|
||||||
|
.order_by(Headquarters.name)
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
ids = {h.id for h in managed}
|
||||||
|
team = (
|
||||||
|
await db.execute(
|
||||||
|
select(User).where(User.role.in_(FIELD_ROLES), User.headquarters_id.in_(ids or [None])).order_by(User.full_name)
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
counts_by_hq = {
|
||||||
|
hq_id: n for hq_id, n in (
|
||||||
|
await db.execute(select(User.headquarters_id, func.count()).where(User.role.in_(FIELD_ROLES), User.is_active.is_(True)).group_by(User.headquarters_id))
|
||||||
|
).all()
|
||||||
|
}
|
||||||
|
data["headquarters"] = [{**_hq(h), "field_staff": counts_by_hq.get(h.id, 0)} for h in managed]
|
||||||
|
data["team"] = [{**_person(t), "headquarters": next((h.code for h in managed if h.id == t.headquarters_id), None)} for t in team]
|
||||||
|
data["reports"]["counts"] = await _report_counts(db, hq_ids=ids)
|
||||||
|
data["reports"]["recent"] = [to_list_item(r).model_dump(mode="json") for r in await repo.list_scoped(hq_ids=ids, limit=15)]
|
||||||
|
own = await repo.list_scoped(mr_user_id=user.id, report_type=ReportType.SELF, limit=10)
|
||||||
|
data["own_reports"] = [to_list_item(r).model_dump(mode="json") for r in own]
|
||||||
|
return data
|
||||||
@@ -6,6 +6,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||||||
from app.auth.dependencies import client_ip, get_current_user, require_role
|
from app.auth.dependencies import client_ip, get_current_user, require_role
|
||||||
from app.common.enums import Role
|
from app.common.enums import Role
|
||||||
from app.database.session import get_db
|
from app.database.session import get_db
|
||||||
|
from app.users import overview
|
||||||
from app.users.models import User
|
from app.users.models import User
|
||||||
from app.users.schemas import MyProfile, UserCreate, UserRead, UserUpdate
|
from app.users.schemas import MyProfile, UserCreate, UserRead, UserUpdate
|
||||||
from app.users.service import UserService
|
from app.users.service import UserService
|
||||||
@@ -20,6 +21,16 @@ async def my_profile(
|
|||||||
return await UserService(db).my_profile(current_user)
|
return await UserService(db).my_profile(current_user)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{user_id}/overview")
|
||||||
|
async def user_overview(
|
||||||
|
user_id: uuid.UUID,
|
||||||
|
current_user: User = Depends(require_role(Role.ADMIN, Role.GM)),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> dict:
|
||||||
|
"""The whole picture of one person, for the General Manager and Admin."""
|
||||||
|
return await overview.user_overview(db, current_user, user_id)
|
||||||
|
|
||||||
|
|
||||||
@router.get("", response_model=list[UserRead])
|
@router.get("", response_model=list[UserRead])
|
||||||
async def list_users(
|
async def list_users(
|
||||||
role: Role | None = None,
|
role: Role | None = None,
|
||||||
|
|||||||
+14
-3
@@ -2,7 +2,7 @@ import uuid
|
|||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, EmailStr, Field, model_validator
|
from pydantic import BaseModel, ConfigDict, EmailStr, Field, model_validator
|
||||||
|
|
||||||
from app.common.enums import Role
|
from app.common.enums import Role, FIELD_ROLES
|
||||||
|
|
||||||
|
|
||||||
class UserCreate(BaseModel):
|
class UserCreate(BaseModel):
|
||||||
@@ -14,12 +14,16 @@ class UserCreate(BaseModel):
|
|||||||
phone: str | None = Field(default=None, max_length=20)
|
phone: str | None = Field(default=None, max_length=20)
|
||||||
#: Required for MR, forbidden for every other role (R4/R8).
|
#: Required for MR, forbidden for every other role (R4/R8).
|
||||||
headquarters_id: uuid.UUID | None = None
|
headquarters_id: uuid.UUID | None = None
|
||||||
|
#: SFE only: the other districts they cover besides `headquarters_id`.
|
||||||
|
extra_headquarter_ids: list[uuid.UUID] = []
|
||||||
|
|
||||||
@model_validator(mode="after")
|
@model_validator(mode="after")
|
||||||
def check_hq_matches_role(self):
|
def check_hq_matches_role(self):
|
||||||
if self.role == Role.MR and self.headquarters_id is None:
|
if self.extra_headquarter_ids and self.role != Role.SFE:
|
||||||
|
raise ValueError("extra_headquarter_ids may only be set for an SFE")
|
||||||
|
if self.role in FIELD_ROLES and self.headquarters_id is None:
|
||||||
raise ValueError("headquarters_id is required for an MR")
|
raise ValueError("headquarters_id is required for an MR")
|
||||||
if self.role != Role.MR and self.headquarters_id is not None:
|
if self.role not in FIELD_ROLES and self.headquarters_id is not None:
|
||||||
raise ValueError("headquarters_id may only be set for an MR")
|
raise ValueError("headquarters_id may only be set for an MR")
|
||||||
return self
|
return self
|
||||||
|
|
||||||
@@ -32,7 +36,12 @@ class UserUpdate(BaseModel):
|
|||||||
#: A new password. Signs the user out everywhere and clears a lockout.
|
#: A new password. Signs the user out everywhere and clears a lockout.
|
||||||
password: str | None = Field(default=None, min_length=8, max_length=128)
|
password: str | None = Field(default=None, min_length=8, max_length=128)
|
||||||
phone: str | None = Field(default=None, max_length=20)
|
phone: str | None = Field(default=None, max_length=20)
|
||||||
|
#: Admin-only. Moving to MR needs `headquarters_id`; leaving MR or AM ends that role's
|
||||||
|
#: assignments, and the user is signed out so they sign in again with the new role.
|
||||||
|
role: Role | None = None
|
||||||
headquarters_id: uuid.UUID | None = None
|
headquarters_id: uuid.UUID | None = None
|
||||||
|
#: SFE only. The full list of extra districts; omit to leave it unchanged.
|
||||||
|
extra_headquarter_ids: list[uuid.UUID] | None = None
|
||||||
is_active: bool | None = None
|
is_active: bool | None = None
|
||||||
|
|
||||||
|
|
||||||
@@ -47,6 +56,8 @@ class UserRead(BaseModel):
|
|||||||
phone: str | None
|
phone: str | None
|
||||||
headquarters_id: uuid.UUID | None
|
headquarters_id: uuid.UUID | None
|
||||||
is_active: bool
|
is_active: bool
|
||||||
|
is_superadmin: bool = False
|
||||||
|
extra_headquarter_ids: list[uuid.UUID] = []
|
||||||
|
|
||||||
|
|
||||||
class MyProfile(BaseModel):
|
class MyProfile(BaseModel):
|
||||||
|
|||||||
+95
-11
@@ -1,17 +1,25 @@
|
|||||||
import uuid
|
import uuid
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select, update
|
||||||
from sqlalchemy.exc import IntegrityError
|
from sqlalchemy.exc import IntegrityError
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.audit.service import AuditService
|
from app.audit.service import AuditService
|
||||||
from app.auth.security import hash_password
|
from app.auth.security import hash_password
|
||||||
from app.auth.service import AuthService
|
from app.auth.service import AuthService
|
||||||
from app.common.enums import AuditAction, EntityType, Role
|
from app.chemists.models import ChemistAssignment
|
||||||
from app.common.exceptions import ConflictError, NotFoundError, ValidationError
|
from app.common.enums import AuditAction, EntityType, Role, FIELD_ROLES
|
||||||
|
from app.common.exceptions import (
|
||||||
|
ConflictError,
|
||||||
|
ForbiddenError,
|
||||||
|
NotFoundError,
|
||||||
|
ValidationError,
|
||||||
|
)
|
||||||
from app.common.utils import snapshot
|
from app.common.utils import snapshot
|
||||||
|
from app.doctors.models import DoctorAssignment
|
||||||
from app.organization.models import AMHeadquarters, Headquarters
|
from app.organization.models import AMHeadquarters, Headquarters
|
||||||
from app.users.models import User
|
from app.users.models import User, UserExtraHeadquarters
|
||||||
from app.users.schemas import MyProfile, UserCreate, UserUpdate
|
from app.users.schemas import MyProfile, UserCreate, UserUpdate
|
||||||
|
|
||||||
_AUDIT_FIELDS = ["email", "full_name", "employee_code", "role", "headquarters_id", "is_active"]
|
_AUDIT_FIELDS = ["email", "full_name", "employee_code", "role", "headquarters_id", "is_active"]
|
||||||
@@ -30,7 +38,9 @@ class UserService:
|
|||||||
if hq.company_id != actor.company_id:
|
if hq.company_id != actor.company_id:
|
||||||
raise ValidationError("Headquarters belongs to another company")
|
raise ValidationError("Headquarters belongs to another company")
|
||||||
|
|
||||||
|
extras = await self._extra_headquarters(data.extra_headquarter_ids, data.headquarters_id, actor)
|
||||||
user = User(
|
user = User(
|
||||||
|
extra_headquarters=[UserExtraHeadquarters(headquarters_id=h) for h in extras],
|
||||||
company_id=actor.company_id,
|
company_id=actor.company_id,
|
||||||
email=str(data.email).lower(),
|
email=str(data.email).lower(),
|
||||||
password_hash=hash_password(data.password),
|
password_hash=hash_password(data.password),
|
||||||
@@ -58,6 +68,17 @@ class UserService:
|
|||||||
await self.db.commit()
|
await self.db.commit()
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
async def _extra_headquarters(
|
||||||
|
self, ids: list[uuid.UUID], primary: uuid.UUID | None, actor: User
|
||||||
|
) -> list[uuid.UUID]:
|
||||||
|
"""The extra districts an SFE covers: each must exist in this company; the primary one and repeats are dropped."""
|
||||||
|
wanted = list(dict.fromkeys(h for h in ids if h != primary))
|
||||||
|
for hq_id in wanted:
|
||||||
|
hq = await self.db.get(Headquarters, hq_id)
|
||||||
|
if hq is None or hq.company_id != actor.company_id:
|
||||||
|
raise NotFoundError("Headquarters not found")
|
||||||
|
return wanted
|
||||||
|
|
||||||
async def update(
|
async def update(
|
||||||
self, user_id: uuid.UUID, data: UserUpdate, actor: User, ip: str | None = None
|
self, user_id: uuid.UUID, data: UserUpdate, actor: User, ip: str | None = None
|
||||||
) -> User:
|
) -> User:
|
||||||
@@ -67,6 +88,8 @@ class UserService:
|
|||||||
|
|
||||||
if user.company_id != actor.company_id:
|
if user.company_id != actor.company_id:
|
||||||
raise NotFoundError("User not found")
|
raise NotFoundError("User not found")
|
||||||
|
if user.is_superadmin:
|
||||||
|
raise ForbiddenError("The super admin account cannot be edited or deactivated")
|
||||||
|
|
||||||
before = snapshot(user, _AUDIT_FIELDS)
|
before = snapshot(user, _AUDIT_FIELDS)
|
||||||
deactivating = data.is_active is False and user.is_active
|
deactivating = data.is_active is False and user.is_active
|
||||||
@@ -77,8 +100,33 @@ class UserService:
|
|||||||
if changes["email"] is None:
|
if changes["email"] is None:
|
||||||
raise ValidationError("Email cannot be empty")
|
raise ValidationError("Email cannot be empty")
|
||||||
changes["email"] = str(changes["email"]).lower()
|
changes["email"] = str(changes["email"]).lower()
|
||||||
|
if changes.get("role") is None:
|
||||||
|
changes.pop("role", None)
|
||||||
|
old_role = user.role
|
||||||
|
old_hq = user.headquarters_id
|
||||||
|
role_changed = "role" in changes and changes["role"] != old_role
|
||||||
|
if role_changed:
|
||||||
|
if user.id == actor.id:
|
||||||
|
raise ValidationError("You cannot change your own role")
|
||||||
|
# Only an MR has a headquarters; other roles drop it unless told otherwise.
|
||||||
|
if changes["role"] not in FIELD_ROLES:
|
||||||
|
changes.setdefault("headquarters_id", None)
|
||||||
|
if changes.get("headquarters_id") is not None:
|
||||||
|
hq = await self.db.get(Headquarters, changes["headquarters_id"])
|
||||||
|
if hq is None or hq.company_id != actor.company_id:
|
||||||
|
raise NotFoundError("Headquarters not found")
|
||||||
|
new_extras = changes.pop("extra_headquarter_ids", None)
|
||||||
for field, value in changes.items():
|
for field, value in changes.items():
|
||||||
setattr(user, field, value)
|
setattr(user, field, value)
|
||||||
|
# Only an SFE has extra districts; leaving the SFE role drops them.
|
||||||
|
if user.role != Role.SFE:
|
||||||
|
new_extras = []
|
||||||
|
if new_extras is not None:
|
||||||
|
wanted = await self._extra_headquarters(new_extras, user.headquarters_id, actor)
|
||||||
|
user.extra_headquarters = [UserExtraHeadquarters(headquarters_id=h) for h in wanted]
|
||||||
|
elif user.role == Role.SFE and "headquarters_id" in changes:
|
||||||
|
# Moving the primary headquarters: it can no longer also be an extra one.
|
||||||
|
user.extra_headquarters = [e for e in user.extra_headquarters if e.headquarters_id != user.headquarters_id]
|
||||||
|
|
||||||
password_reset = new_password is not None
|
password_reset = new_password is not None
|
||||||
if password_reset:
|
if password_reset:
|
||||||
@@ -86,14 +134,25 @@ class UserService:
|
|||||||
user.failed_login_attempts = 0 # a reset also unlocks the account
|
user.failed_login_attempts = 0 # a reset also unlocks the account
|
||||||
|
|
||||||
# An MR must keep a headquarters; nobody else may gain one (DB check mirrors this).
|
# An MR must keep a headquarters; nobody else may gain one (DB check mirrors this).
|
||||||
if user.role == Role.MR and user.headquarters_id is None:
|
if user.role in FIELD_ROLES and user.headquarters_id is None:
|
||||||
raise ValidationError("An MR must have a headquarters")
|
raise ValidationError("An MR must have a headquarters")
|
||||||
if user.role != Role.MR and user.headquarters_id is not None:
|
if user.role not in FIELD_ROLES and user.headquarters_id is not None:
|
||||||
raise ValidationError("Only an MR can have a headquarters")
|
raise ValidationError("Only an MR can have a headquarters")
|
||||||
|
|
||||||
|
hq_changed = not role_changed and user.role in FIELD_ROLES and user.headquarters_id != old_hq
|
||||||
|
# Changing role, or moving an MR to another headquarters, ends what the old post held.
|
||||||
|
switched_field_role = role_changed and old_role in FIELD_ROLES and user.role in FIELD_ROLES # MR <-> SFE keeps its work
|
||||||
|
released = (
|
||||||
|
await self._end_role_assignments(user.id, old_role)
|
||||||
|
if (role_changed and not switched_field_role) or hq_changed
|
||||||
|
else {}
|
||||||
|
)
|
||||||
|
|
||||||
after = snapshot(user, _AUDIT_FIELDS)
|
after = snapshot(user, _AUDIT_FIELDS)
|
||||||
if password_reset:
|
if password_reset:
|
||||||
after["password_reset"] = True # the fact is logged, never the password or its hash
|
after["password_reset"] = True # the fact is logged, never the password or its hash
|
||||||
|
if released:
|
||||||
|
after["released"] = released
|
||||||
try:
|
try:
|
||||||
await self.audit.log(
|
await self.audit.log(
|
||||||
actor_user_id=actor.id,
|
actor_user_id=actor.id,
|
||||||
@@ -110,11 +169,34 @@ class UserService:
|
|||||||
raise ConflictError("A user with this email or employee code already exists") from exc
|
raise ConflictError("A user with this email or employee code already exists") from exc
|
||||||
|
|
||||||
# SEC-5 — revoke refresh tokens the moment a user is deactivated, or their
|
# SEC-5 — revoke refresh tokens the moment a user is deactivated, or their
|
||||||
# credentials are changed, so an old session cannot outlive the old password/email.
|
# credentials or role are changed, so an old session cannot outlive them.
|
||||||
if deactivating or password_reset or "email" in changes:
|
if deactivating or password_reset or "email" in changes or role_changed:
|
||||||
await AuthService(self.db).logout(user.id)
|
await AuthService(self.db).logout(user.id)
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
async def _end_role_assignments(self, user_id: uuid.UUID, old_role: Role) -> dict[str, int]:
|
||||||
|
"""Close what the old role held: an MR's doctors and chemists, an AM's headquarters."""
|
||||||
|
today = date.today()
|
||||||
|
if old_role in FIELD_ROLES:
|
||||||
|
targets = [
|
||||||
|
("doctors", DoctorAssignment, DoctorAssignment.mr_user_id),
|
||||||
|
("chemists", ChemistAssignment, ChemistAssignment.mr_user_id),
|
||||||
|
]
|
||||||
|
elif old_role == Role.AM:
|
||||||
|
targets = [("headquarters", AMHeadquarters, AMHeadquarters.area_manager_user_id)]
|
||||||
|
else:
|
||||||
|
return {}
|
||||||
|
released = {}
|
||||||
|
for label, model, owner in targets:
|
||||||
|
result = await self.db.execute(
|
||||||
|
update(model)
|
||||||
|
.where(owner == user_id, model.effective_to.is_(None))
|
||||||
|
.values(effective_to=today)
|
||||||
|
)
|
||||||
|
if result.rowcount:
|
||||||
|
released[label] = result.rowcount
|
||||||
|
return released
|
||||||
|
|
||||||
async def list_users(self, actor: User, role: Role | None = None) -> list[User]:
|
async def list_users(self, actor: User, role: Role | None = None) -> list[User]:
|
||||||
stmt = select(User).where(User.company_id == actor.company_id)
|
stmt = select(User).where(User.company_id == actor.company_id)
|
||||||
if role is not None:
|
if role is not None:
|
||||||
@@ -139,9 +221,11 @@ class UserService:
|
|||||||
AMHeadquarters.effective_to.is_(None),
|
AMHeadquarters.effective_to.is_(None),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
manager = (await self.db.execute(stmt)).scalars().first()
|
# A headquarters may have several Area Managers: name every one.
|
||||||
if manager:
|
managers = list((await self.db.execute(stmt.order_by(User.full_name))).scalars())
|
||||||
manager_id, manager_name = manager.id, manager.full_name
|
if managers:
|
||||||
|
manager_id = managers[0].id
|
||||||
|
manager_name = ", ".join(m.full_name for m in managers)
|
||||||
|
|
||||||
return MyProfile(
|
return MyProfile(
|
||||||
id=user.id,
|
id=user.id,
|
||||||
|
|||||||
@@ -29,6 +29,26 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
logging: *default-logging
|
logging: *default-logging
|
||||||
|
|
||||||
|
# Daily pg_dump of the whole database into ./backups on the host, the last 14 days kept.
|
||||||
|
# See scripts/backup.sh for how to restore one.
|
||||||
|
backup:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
environment:
|
||||||
|
PGHOST: db
|
||||||
|
PGUSER: ${POSTGRES_USER:-pharma}
|
||||||
|
PGPASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
|
||||||
|
PGDATABASE: ${POSTGRES_DB:-pharma}
|
||||||
|
BACKUP_KEEP_DAYS: ${BACKUP_KEEP_DAYS:-14}
|
||||||
|
volumes:
|
||||||
|
- ./backups:/backups
|
||||||
|
- ./scripts/backup.sh:/backup.sh:ro
|
||||||
|
entrypoint: ["/bin/sh", "/backup.sh"]
|
||||||
|
restart: unless-stopped
|
||||||
|
logging: *default-logging
|
||||||
|
|
||||||
api:
|
api:
|
||||||
build: .
|
build: .
|
||||||
depends_on:
|
depends_on:
|
||||||
@@ -42,6 +62,7 @@ services:
|
|||||||
PDF_STORAGE_PATH: /srv/storage/pdf
|
PDF_STORAGE_PATH: /srv/storage/pdf
|
||||||
BACKDATING_WINDOW_DAYS: ${BACKDATING_WINDOW_DAYS:-7}
|
BACKDATING_WINDOW_DAYS: ${BACKDATING_WINDOW_DAYS:-7}
|
||||||
SUBMISSION_DEADLINE_DAYS: ${SUBMISSION_DEADLINE_DAYS:-1}
|
SUBMISSION_DEADLINE_DAYS: ${SUBMISSION_DEADLINE_DAYS:-1}
|
||||||
|
PLAN_AHEAD_DAYS: ${PLAN_AHEAD_DAYS:-2}
|
||||||
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2}
|
WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2}
|
||||||
volumes:
|
volumes:
|
||||||
- pdfstore:/srv/storage/pdf
|
- pdfstore:/srv/storage/pdf
|
||||||
|
|||||||
Executable
+27
@@ -0,0 +1,27 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Daily database backup, run by the `backup` service in docker-compose.yml.
|
||||||
|
#
|
||||||
|
# Takes a compressed pg_dump of the whole database once a day (and once straight away on
|
||||||
|
# start), keeps the last BACKUP_KEEP_DAYS days, and writes them to ./backups on the host so
|
||||||
|
# they can be copied off the server. Restore one with:
|
||||||
|
# gunzip -c backups/pharma-YYYYMMDD-HHMMSS.sql.gz | docker compose exec -T db psql -U pharma -d pharma
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
KEEP_DAYS="${BACKUP_KEEP_DAYS:-14}"
|
||||||
|
INTERVAL="${BACKUP_INTERVAL_SECONDS:-86400}"
|
||||||
|
mkdir -p /backups
|
||||||
|
|
||||||
|
while true; do
|
||||||
|
stamp=$(date -u +%Y%m%d-%H%M%S)
|
||||||
|
target="/backups/${PGDATABASE}-${stamp}.sql.gz"
|
||||||
|
# Written under a temporary name, so a half-written file is never taken for a backup.
|
||||||
|
if pg_dump --clean --if-exists --no-owner | gzip > "${target}.part"; then
|
||||||
|
mv "${target}.part" "${target}"
|
||||||
|
echo "backup: wrote ${target} ($(du -h "${target}" | cut -f1))"
|
||||||
|
else
|
||||||
|
rm -f "${target}.part"
|
||||||
|
echo "backup: pg_dump FAILED at ${stamp}" >&2
|
||||||
|
fi
|
||||||
|
find /backups -name "${PGDATABASE}-*.sql.gz" -mtime "+${KEEP_DAYS}" -delete
|
||||||
|
sleep "${INTERVAL}"
|
||||||
|
done
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
"""Create (or rotate the password of) the protected super admin.
|
||||||
|
|
||||||
|
python -m scripts.create_superadmin --email owner@example.com --password 'S3cret-...'
|
||||||
|
|
||||||
|
The super admin has the ADMIN role, so it can do everything an administrator can, but no
|
||||||
|
one can edit, deactivate, re-role or delete it afterwards (API and DB trigger both refuse).
|
||||||
|
Re-running with the same email only resets its password and clears any lockout.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import asyncio
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from app.auth.security import hash_password
|
||||||
|
from app.common.enums import Role
|
||||||
|
from app.database.session import AsyncSessionLocal
|
||||||
|
from app.organization.models import Company
|
||||||
|
from app.users.models import User
|
||||||
|
|
||||||
|
|
||||||
|
async def run(email: str, password: str, name: str, code: str) -> None:
|
||||||
|
async with AsyncSessionLocal() as db:
|
||||||
|
existing = (
|
||||||
|
await db.execute(select(User).where(User.is_superadmin.is_(True)))
|
||||||
|
).scalar_one_or_none()
|
||||||
|
if existing is not None:
|
||||||
|
if existing.email != email.lower():
|
||||||
|
sys.exit(f"A super admin already exists ({existing.email}); only one is allowed.")
|
||||||
|
existing.password_hash = hash_password(password)
|
||||||
|
existing.failed_login_attempts = 0
|
||||||
|
await db.commit()
|
||||||
|
print(f"Super admin {existing.email}: password reset.")
|
||||||
|
return
|
||||||
|
|
||||||
|
company = (await db.execute(select(Company).order_by(Company.created_at))).scalars().first()
|
||||||
|
if company is None:
|
||||||
|
sys.exit("No company exists yet — seed or create one first.")
|
||||||
|
db.add(
|
||||||
|
User(
|
||||||
|
company_id=company.id, email=email.lower(), password_hash=hash_password(password),
|
||||||
|
full_name=name, employee_code=code, role=Role.ADMIN, is_superadmin=True,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
print(f"Super admin created: {email.lower()}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
p = argparse.ArgumentParser()
|
||||||
|
p.add_argument("--email", required=True)
|
||||||
|
p.add_argument("--password", required=True)
|
||||||
|
p.add_argument("--name", default="Super Admin")
|
||||||
|
p.add_argument("--code", default="SUPERADMIN")
|
||||||
|
a = p.parse_args()
|
||||||
|
if len(a.password) < 12:
|
||||||
|
sys.exit("Use a password of at least 12 characters.")
|
||||||
|
asyncio.run(run(a.email, a.password, a.name, a.code))
|
||||||
@@ -29,7 +29,7 @@ CSV_TABLES = {
|
|||||||
"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"]),
|
"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"]),
|
"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"]),
|
"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"]),
|
"sales_projection.csv": ("sales_projection", ["name", "headquarter", "report_date", "month", "serial_no", "product_name", "pts", "closing_qty", "closing_value", "projection_qty", "projection_value"]),
|
||||||
}
|
}
|
||||||
SERIAL_COLUMNS = {"serial_no", "doctor_sr_no", "chemist_sr_no"}
|
SERIAL_COLUMNS = {"serial_no", "doctor_sr_no", "chemist_sr_no"}
|
||||||
|
|
||||||
@@ -57,7 +57,7 @@ async def apply_sales_projection_account(db) -> None:
|
|||||||
headquarter = headquarters.name
|
headquarter = headquarters.name
|
||||||
FROM "user" AS account
|
FROM "user" AS account
|
||||||
LEFT JOIN headquarters ON headquarters.id = account.headquarters_id
|
LEFT JOIN headquarters ON headquarters.id = account.headquarters_id
|
||||||
WHERE account.role = 'MR' '''
|
WHERE account.id = projection.owner_user_id '''
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -76,13 +76,12 @@ async def import_csv_data(only_empty: bool = False) -> None:
|
|||||||
continue
|
continue
|
||||||
else:
|
else:
|
||||||
await db.execute(text(f'DELETE FROM "{table_name}"'))
|
await db.execute(text(f'DELETE FROM "{table_name}"'))
|
||||||
source_columns = columns[4:] if table_name == "sales_projection" else columns
|
# The Sales Projection CSV is the product list: only Sl. No., product and PTS come
|
||||||
|
# from it; every figure is filled in later, per month, on the form.
|
||||||
|
source_columns = ["serial_no", "product_name", "pts"] if table_name == "sales_projection" else columns
|
||||||
rows = read_rows(path, source_columns)
|
rows = read_rows(path, source_columns)
|
||||||
if table_name == "sales_projection":
|
if table_name == "sales_projection":
|
||||||
rows = [
|
rows = [(row_number, {**{c: "" for c in columns}, **data}) for row_number, data in rows]
|
||||||
(row_number, {"name": "", "headquarter": "", "report_date": "", "month": "", **data})
|
|
||||||
for row_number, data in rows
|
|
||||||
]
|
|
||||||
if rows:
|
if rows:
|
||||||
column_names = ", ".join(f'"{column}"' for column in columns)
|
column_names = ", ".join(f'"{column}"' for column in columns)
|
||||||
parameters = ", ".join(f":{column}" for column in columns)
|
parameters = ", ".join(f":{column}" for column in columns)
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ from app.users.models import User # noqa: E402
|
|||||||
TABLES = [
|
TABLES = [
|
||||||
"audit_log",
|
"audit_log",
|
||||||
"product",
|
"product",
|
||||||
|
"missed_visit",
|
||||||
"doctor_call",
|
"doctor_call",
|
||||||
"chemist_call",
|
"chemist_call",
|
||||||
"daily_call_report",
|
"daily_call_report",
|
||||||
@@ -169,6 +170,34 @@ async def org(db: AsyncSession) -> dict:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
async def approved_plan(db: AsyncSession, org: dict):
|
||||||
|
"""An empty day plan, already approved, so an end-of-day report may be filed.
|
||||||
|
|
||||||
|
For tests about end-of-day rules where the plan is incidental; the plan flow itself
|
||||||
|
is exercised through the API in tests/e2e/test_day_plan.py.
|
||||||
|
"""
|
||||||
|
from app.common.enums import DCRStatus, ReportType
|
||||||
|
from app.common.utils import utcnow
|
||||||
|
from app.reports.models import DailyCallReport
|
||||||
|
|
||||||
|
async def make(day: date | None = None, mr: str = "mr1") -> DailyCallReport:
|
||||||
|
plan = DailyCallReport(
|
||||||
|
id=uuid.uuid4(),
|
||||||
|
mr_user_id=org[mr].id,
|
||||||
|
headquarters_id=org[mr].headquarters_id,
|
||||||
|
report_date=day or date.today(),
|
||||||
|
report_type=ReportType.PLAN,
|
||||||
|
status=DCRStatus.APPROVED,
|
||||||
|
approved_at=utcnow(),
|
||||||
|
)
|
||||||
|
db.add(plan)
|
||||||
|
await db.commit()
|
||||||
|
return plan
|
||||||
|
|
||||||
|
return make
|
||||||
|
|
||||||
|
|
||||||
async def login(client: AsyncClient, user: User) -> dict[str, str]:
|
async def login(client: AsyncClient, user: User) -> dict[str, str]:
|
||||||
resp = await client.post(
|
resp = await client.post(
|
||||||
"/api/v1/auth/login",
|
"/api/v1/auth/login",
|
||||||
|
|||||||
@@ -38,16 +38,26 @@ class TestAreaManagerHeadquarters:
|
|||||||
mine = {r["headquarters_id"] for r in listing.json() if r["area_manager_user_id"] == str(org["am1"].id)}
|
mine = {r["headquarters_id"] for r in listing.json() if r["area_manager_user_id"] == str(org["am1"].id)}
|
||||||
assert mine == set(wanted)
|
assert mine == set(wanted)
|
||||||
|
|
||||||
async def test_taking_a_headquarters_moves_it_from_the_other_am(self, client, auth, org):
|
async def test_a_headquarters_can_have_several_area_managers(self, client, auth, org):
|
||||||
# am2 currently manages hq2; give hq2 to am1 as well.
|
# am2 manages hq2; give hq2 to am1 as well — am2 keeps it.
|
||||||
|
resp = await client.put(
|
||||||
|
f"{API}/area-managers/{org['am1'].id}", headers=auth["admin"],
|
||||||
|
json={"headquarters_ids": [str(org["hq1"].id), str(org["hq2"].id)]},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
listing = (await client.get(f"{API}/area-managers", headers=auth["admin"])).json()
|
||||||
|
managers = {r["area_manager_user_id"] for r in listing if r["headquarters_id"] == str(org["hq2"].id)}
|
||||||
|
assert managers == {str(org["am1"].id), str(org["am2"].id)}
|
||||||
|
# Both see it, so either may review its MRs' reports and forms.
|
||||||
|
for am in ("am1", "am2"):
|
||||||
|
assert str(org["hq2"].id) in {h["id"] for h in (await client.get(API, headers=auth[am])).json()}
|
||||||
|
# Saving the same set again adds nothing twice.
|
||||||
await client.put(
|
await client.put(
|
||||||
f"{API}/area-managers/{org['am1'].id}", headers=auth["admin"],
|
f"{API}/area-managers/{org['am1'].id}", headers=auth["admin"],
|
||||||
json={"headquarters_ids": [str(org["hq1"].id), str(org["hq2"].id)]},
|
json={"headquarters_ids": [str(org["hq1"].id), str(org["hq2"].id)]},
|
||||||
)
|
)
|
||||||
listing = (await client.get(f"{API}/area-managers", headers=auth["admin"])).json()
|
again = (await client.get(f"{API}/area-managers", headers=auth["admin"])).json()
|
||||||
owners = {r["headquarters_id"]: r["area_manager_user_id"] for r in listing}
|
assert len(again) == len(listing)
|
||||||
assert owners[str(org["hq2"].id)] == str(org["am1"].id) # one AM per HQ still holds
|
|
||||||
assert len(listing) == len(owners)
|
|
||||||
|
|
||||||
async def test_omitted_headquarters_are_released(self, client, auth, org):
|
async def test_omitted_headquarters_are_released(self, client, auth, org):
|
||||||
resp = await client.put(
|
resp = await client.put(
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""The dashboard's headquarters filter narrows a manager's reports and counts, never widens them."""
|
||||||
|
|
||||||
|
API = "/api/v1"
|
||||||
|
|
||||||
|
|
||||||
|
class TestHeadquartersFilter:
|
||||||
|
async def test_reports_and_counts_narrow_to_the_chosen_headquarters(self, client, auth, org, approved_plan):
|
||||||
|
await approved_plan(mr="mr1") # hq1
|
||||||
|
await approved_plan(mr="mr2") # hq2
|
||||||
|
hq1, hq2 = str(org["hq1"].id), str(org["hq2"].id)
|
||||||
|
|
||||||
|
everything = (await client.get(f"{API}/dcr", headers=auth["gm"])).json()
|
||||||
|
assert len(everything) == 2
|
||||||
|
only_hq1 = (await client.get(f"{API}/dcr", headers=auth["gm"], params={"headquarters_id": hq1})).json()
|
||||||
|
assert [r["mr_name"] for r in only_hq1] == ["Ravi Das"]
|
||||||
|
counts = (await client.get(f"{API}/dcr/counts", headers=auth["admin"], params={"headquarters_id": hq2})).json()
|
||||||
|
assert counts["APPROVED"] == 1
|
||||||
|
|
||||||
|
async def test_a_headquarters_outside_the_users_scope_gives_nothing(self, client, auth, org, approved_plan):
|
||||||
|
await approved_plan(mr="mr2") # hq2, not am1's
|
||||||
|
outside = await client.get(f"{API}/dcr", headers=auth["am1"], params={"headquarters_id": str(org["hq2"].id)})
|
||||||
|
assert outside.status_code == 200 and outside.json() == []
|
||||||
|
counts = (await client.get(f"{API}/dcr/counts", headers=auth["am1"], params={"headquarters_id": str(org["hq2"].id)})).json()
|
||||||
|
assert counts["APPROVED"] == 0
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
"""Morning day plan → Area Manager approval → end-of-day report against it (rules P1-P5)."""
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from tests.e2e.test_full_approval_flow import _create_masters
|
||||||
|
|
||||||
|
API = "/api/v1"
|
||||||
|
TODAY = date.today().isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
async def _plan(client, auth, doctors, chemists, *, approve=True):
|
||||||
|
"""A plan for today with the given doctors/chemists, submitted (and by default approved)."""
|
||||||
|
resp = await client.post(
|
||||||
|
f"{API}/dcr", headers=auth["mr1"],
|
||||||
|
json={
|
||||||
|
"report_date": TODAY, "report_type": "PLAN",
|
||||||
|
"doctor_calls": [{"doctor_id": d["id"], "visit_time": "23:00:00"} for d in doctors],
|
||||||
|
"chemist_calls": [{"chemist_id": c["id"], "visit_time": "23:30:00"} for c in chemists],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 201, resp.text
|
||||||
|
plan_id = resp.json()["id"]
|
||||||
|
assert (await client.post(f"{API}/dcr/{plan_id}/submit", headers=auth["mr1"])).status_code == 200
|
||||||
|
if approve:
|
||||||
|
approved = await client.post(f"{API}/dcr/{plan_id}/approve", headers=auth["am1"], json={})
|
||||||
|
assert approved.status_code == 200, approved.text
|
||||||
|
return plan_id
|
||||||
|
|
||||||
|
|
||||||
|
async def _actual(client, auth):
|
||||||
|
resp = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "ACTUAL"})
|
||||||
|
assert resp.status_code == 201, resp.text
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
|
||||||
|
async def _visit_doctor(client, auth, dcr_id, doctor):
|
||||||
|
return await client.post(
|
||||||
|
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
||||||
|
json={"doctor_id": doctor["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestDayPlan:
|
||||||
|
async def test_a_plan_has_planned_times_and_no_outcomes(self, client, auth, org):
|
||||||
|
doctors, chemists = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
||||||
|
resp = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "PLAN"})
|
||||||
|
assert resp.status_code == 201, resp.text
|
||||||
|
plan = resp.json()
|
||||||
|
assert plan["report_type"] == "PLAN" and plan["plan_id"] is None
|
||||||
|
# P1 — a planned time later than now is fine, and an outcome is not stored.
|
||||||
|
added = await client.post(
|
||||||
|
f"{API}/dcr/{plan['id']}/calls/doctor", headers=auth["mr1"],
|
||||||
|
json={"doctor_id": doctors[0]["id"], "visit_time": "23:59:00", "call_outcome": "MET"},
|
||||||
|
)
|
||||||
|
assert added.status_code == 201, added.text
|
||||||
|
assert added.json()["doctor_calls"][0]["call_outcome"] is None
|
||||||
|
|
||||||
|
async def test_an_empty_plan_cannot_be_submitted(self, client, auth, org):
|
||||||
|
resp = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "PLAN"})
|
||||||
|
submit = await client.post(f"{API}/dcr/{resp.json()['id']}/submit", headers=auth["mr1"])
|
||||||
|
assert submit.status_code == 422
|
||||||
|
assert "at least one" in submit.json()["error"]["message"]
|
||||||
|
|
||||||
|
async def test_one_plan_and_one_end_of_day_report_per_day(self, client, auth, org):
|
||||||
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
|
||||||
|
await _plan(client, auth, doctors[:1], [])
|
||||||
|
again = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "PLAN"})
|
||||||
|
assert again.status_code == 409
|
||||||
|
await _actual(client, auth)
|
||||||
|
twice = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "ACTUAL"})
|
||||||
|
assert twice.status_code == 409
|
||||||
|
|
||||||
|
async def test_the_area_manager_can_return_a_plan(self, client, auth, org):
|
||||||
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
|
||||||
|
plan_id = await _plan(client, auth, doctors, [], approve=False)
|
||||||
|
resp = await client.post(
|
||||||
|
f"{API}/dcr/{plan_id}/return", headers=auth["am1"], json={"reason": "Add the chemists on MG Road."}
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200 and resp.json()["status"] == "RETURNED"
|
||||||
|
|
||||||
|
async def test_reports_can_be_listed_by_type(self, client, auth, org):
|
||||||
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
|
||||||
|
plan_id = await _plan(client, auth, doctors, [])
|
||||||
|
actual = await _actual(client, auth)
|
||||||
|
plans = (await client.get(f"{API}/dcr?type=PLAN", headers=auth["mr1"])).json()
|
||||||
|
actuals = (await client.get(f"{API}/dcr?type=ACTUAL", headers=auth["mr1"])).json()
|
||||||
|
assert [r["id"] for r in plans] == [plan_id]
|
||||||
|
assert [r["id"] for r in actuals] == [actual["id"]]
|
||||||
|
|
||||||
|
|
||||||
|
class TestEndOfDayNeedsAnApprovedPlan:
|
||||||
|
async def test_without_a_plan_it_is_refused(self, client, auth, org):
|
||||||
|
resp = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "ACTUAL"})
|
||||||
|
assert resp.status_code == 422
|
||||||
|
assert "Daily Call Report (Plan)" in resp.json()["error"]["message"]
|
||||||
|
|
||||||
|
async def test_while_the_plan_awaits_approval_it_is_refused(self, client, auth, org):
|
||||||
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
|
||||||
|
await _plan(client, auth, doctors, [], approve=False)
|
||||||
|
resp = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "ACTUAL"})
|
||||||
|
assert resp.status_code == 422
|
||||||
|
assert "approved by the Area Manager" in resp.json()["error"]["message"]
|
||||||
|
|
||||||
|
async def test_once_approved_it_is_linked_to_the_plan(self, client, auth, org):
|
||||||
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
|
||||||
|
plan_id = await _plan(client, auth, doctors, [])
|
||||||
|
actual = await _actual(client, auth)
|
||||||
|
assert actual["plan_id"] == plan_id
|
||||||
|
plan = (await client.get(f"{API}/dcr/{plan_id}", headers=auth["mr1"])).json()
|
||||||
|
assert plan["actual_report_id"] == actual["id"]
|
||||||
|
|
||||||
|
|
||||||
|
class TestPlanVersusActual:
|
||||||
|
async def test_every_planned_visit_must_be_made_or_explained(self, client, auth, org):
|
||||||
|
doctors, chemists = await _create_masters(client, auth, org, n_doctors=3, n_chemists=1)
|
||||||
|
await _plan(client, auth, doctors[:2], chemists)
|
||||||
|
dcr = await _actual(client, auth)
|
||||||
|
assert {p["status"] for p in dcr["planned_visits"]} == {"PENDING"}
|
||||||
|
assert len(dcr["planned_visits"]) == 3
|
||||||
|
|
||||||
|
# P5 — an unplanned visit is allowed; it is not on the checklist.
|
||||||
|
assert (await _visit_doctor(client, auth, dcr["id"], doctors[2])).status_code == 201
|
||||||
|
body = (await _visit_doctor(client, auth, dcr["id"], doctors[0])).json()
|
||||||
|
by_name = {p["name"]: p["status"] for p in body["planned_visits"]}
|
||||||
|
assert by_name[doctors[0]["name"]] == "VISITED"
|
||||||
|
|
||||||
|
# P3 — the doctor and chemist still pending block the submit, by name.
|
||||||
|
blocked = await client.post(f"{API}/dcr/{dcr['id']}/submit", headers=auth["mr1"])
|
||||||
|
assert blocked.status_code == 422
|
||||||
|
assert set(blocked.json()["error"]["details"]["pending"]) == {doctors[1]["name"], chemists[0]["name"]}
|
||||||
|
|
||||||
|
await client.put(f"{API}/dcr/{dcr['id']}/missed", headers=auth["mr1"],
|
||||||
|
json={"doctor_id": doctors[1]["id"], "reason": "Clinic closed for the day"})
|
||||||
|
explained = await client.put(f"{API}/dcr/{dcr['id']}/missed", headers=auth["mr1"],
|
||||||
|
json={"chemist_id": chemists[0]["id"], "reason": "Shop shut"})
|
||||||
|
assert explained.status_code == 200, explained.text
|
||||||
|
missed = [p for p in explained.json()["planned_visits"] if p["status"] == "MISSED"]
|
||||||
|
assert {p["missed_reason"] for p in missed} == {"Clinic closed for the day", "Shop shut"}
|
||||||
|
|
||||||
|
submit = await client.post(f"{API}/dcr/{dcr['id']}/submit", headers=auth["mr1"])
|
||||||
|
assert submit.status_code == 200, submit.text
|
||||||
|
approve = await client.post(f"{API}/dcr/{dcr['id']}/approve", headers=auth["am1"], json={})
|
||||||
|
assert approve.status_code == 200, approve.text
|
||||||
|
pdf = await client.get(f"{API}/dcr/{dcr['id']}/pdf", headers=auth["mr1"])
|
||||||
|
assert pdf.status_code == 200 and pdf.content.startswith(b"%PDF-")
|
||||||
|
|
||||||
|
async def test_recording_the_visit_later_replaces_the_missed_note(self, client, auth, org):
|
||||||
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
|
||||||
|
await _plan(client, auth, doctors, [])
|
||||||
|
dcr = await _actual(client, auth)
|
||||||
|
await client.put(f"{API}/dcr/{dcr['id']}/missed", headers=auth["mr1"],
|
||||||
|
json={"doctor_id": doctors[0]["id"], "reason": "Doctor on leave"})
|
||||||
|
body = (await _visit_doctor(client, auth, dcr["id"], doctors[0])).json()
|
||||||
|
assert body["planned_visits"][0]["status"] == "VISITED"
|
||||||
|
assert body["planned_visits"][0]["missed_reason"] is None
|
||||||
|
# ...and removing the visit brings the line back to pending, not to the old note.
|
||||||
|
call_id = body["doctor_calls"][0]["id"]
|
||||||
|
removed = (await client.delete(f"{API}/dcr/{dcr['id']}/calls/{call_id}", headers=auth["mr1"])).json()
|
||||||
|
assert removed["planned_visits"][0]["status"] == "PENDING"
|
||||||
|
|
||||||
|
async def test_missed_notes_are_validated(self, client, auth, org):
|
||||||
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
||||||
|
plan_id = await _plan(client, auth, doctors[:1], [])
|
||||||
|
dcr = await _actual(client, auth)
|
||||||
|
url = f"{API}/dcr/{dcr['id']}/missed"
|
||||||
|
# Not on the plan.
|
||||||
|
off_plan = await client.put(url, headers=auth["mr1"], json={"doctor_id": doctors[1]["id"], "reason": "Busy day"})
|
||||||
|
assert off_plan.status_code == 422
|
||||||
|
# Exactly one target, and a real reason.
|
||||||
|
assert (await client.put(url, headers=auth["mr1"], json={"reason": "Busy day"})).status_code == 422
|
||||||
|
assert (await client.put(url, headers=auth["mr1"], json={"doctor_id": doctors[0]["id"], "reason": " "})).status_code == 422
|
||||||
|
# Already visited.
|
||||||
|
await _visit_doctor(client, auth, dcr["id"], doctors[0])
|
||||||
|
visited = await client.put(url, headers=auth["mr1"], json={"doctor_id": doctors[0]["id"], "reason": "Busy day"})
|
||||||
|
assert visited.status_code == 409
|
||||||
|
# Not on a plan at all.
|
||||||
|
plan_note = await client.put(f"{API}/dcr/{plan_id}/missed", headers=auth["mr1"],
|
||||||
|
json={"doctor_id": doctors[0]["id"], "reason": "Busy day"})
|
||||||
|
assert plan_note.status_code in (409, 422)
|
||||||
|
|
||||||
|
async def test_a_note_can_be_reworded_and_cleared(self, client, auth, org):
|
||||||
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
|
||||||
|
await _plan(client, auth, doctors, [])
|
||||||
|
dcr = await _actual(client, auth)
|
||||||
|
url = f"{API}/dcr/{dcr['id']}/missed"
|
||||||
|
await client.put(url, headers=auth["mr1"], json={"doctor_id": doctors[0]["id"], "reason": "Doctor on leave"})
|
||||||
|
body = (await client.put(url, headers=auth["mr1"], json={"doctor_id": doctors[0]["id"], "reason": "On leave till Monday"})).json()
|
||||||
|
line = body["planned_visits"][0]
|
||||||
|
assert line["missed_reason"] == "On leave till Monday"
|
||||||
|
cleared = await client.delete(f"{url}/{line['missed_visit_id']}", headers=auth["mr1"])
|
||||||
|
assert cleared.status_code == 200 and cleared.json()["planned_visits"][0]["status"] == "PENDING"
|
||||||
|
|
||||||
|
async def test_an_end_of_day_visit_needs_an_outcome(self, client, auth, org):
|
||||||
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
|
||||||
|
await _plan(client, auth, doctors, [])
|
||||||
|
dcr = await _actual(client, auth)
|
||||||
|
resp = await client.post(
|
||||||
|
f"{API}/dcr/{dcr['id']}/calls/doctor", headers=auth["mr1"],
|
||||||
|
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 422
|
||||||
|
assert "call_outcome" in resp.json()["error"]["message"]
|
||||||
|
|
||||||
|
async def test_only_the_owning_mr_writes_missed_notes(self, client, auth, org):
|
||||||
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
|
||||||
|
await _plan(client, auth, doctors, [])
|
||||||
|
dcr = await _actual(client, auth)
|
||||||
|
body = {"doctor_id": doctors[0]["id"], "reason": "Doctor on leave"}
|
||||||
|
assert (await client.put(f"{API}/dcr/{dcr['id']}/missed", headers=auth["am1"], json=body)).status_code == 403
|
||||||
|
assert (await client.put(f"{API}/dcr/{dcr['id']}/missed", headers=auth["mr2"], json=body)).status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
class TestPlanPdf:
|
||||||
|
async def test_an_approved_plan_downloads_as_a_daily_call_plan(self, client, auth, org, db):
|
||||||
|
from app.pdf.service import PDFService
|
||||||
|
from app.reports.repository import DCRRepository
|
||||||
|
|
||||||
|
doctors, chemists = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
|
||||||
|
plan_id = await _plan(client, auth, doctors, chemists)
|
||||||
|
pdf = await client.get(f"{API}/dcr/{plan_id}/pdf", headers=auth["mr1"])
|
||||||
|
assert pdf.status_code == 200 and pdf.content.startswith(b"%PDF-")
|
||||||
|
assert 'filename="PLAN-MR001-' in pdf.headers["content-disposition"]
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
context = await PDFService(db)._context(await DCRRepository(db).get_full(uuid.UUID(plan_id)))
|
||||||
|
assert context["title"] == "DAILY CALL REPORT (PLAN)"
|
||||||
|
assert "PLANNED TIME" in context["grids"]["doctors"]["headers"]
|
||||||
|
assert context["grids"]["doctors"]["rows"][0]["cells"][3] == "23:00"
|
||||||
|
|
||||||
|
|
||||||
|
class TestPlanningAhead:
|
||||||
|
async def test_a_plan_may_be_made_up_to_two_days_ahead_but_a_done_report_never(self, client, auth, org):
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
from app.common.utils import local_today
|
||||||
|
|
||||||
|
day = lambda n: (local_today() + timedelta(days=n)).isoformat() # noqa: E731
|
||||||
|
made = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": day(2), "report_type": "PLAN"})
|
||||||
|
assert made.status_code == 201, made.text
|
||||||
|
too_far = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": day(3), "report_type": "PLAN"})
|
||||||
|
assert too_far.status_code == 422
|
||||||
|
done = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": day(1), "report_type": "ACTUAL"})
|
||||||
|
assert done.status_code == 422
|
||||||
@@ -7,16 +7,17 @@ from tests.e2e.test_full_approval_flow import _create_masters
|
|||||||
API = "/api/v1"
|
API = "/api/v1"
|
||||||
|
|
||||||
|
|
||||||
async def _draft(client, auth, org):
|
async def _draft(client, auth, org, approved_plan):
|
||||||
doctors, chemists = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
doctors, chemists = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
||||||
|
await approved_plan()
|
||||||
resp = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()})
|
resp = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()})
|
||||||
assert resp.status_code == 201, resp.text
|
assert resp.status_code == 201, resp.text
|
||||||
return resp.json()["id"], doctors, chemists
|
return resp.json()["id"], doctors, chemists
|
||||||
|
|
||||||
|
|
||||||
class TestFormFields:
|
class TestFormFields:
|
||||||
async def test_fields_round_trip_through_the_api(self, client, auth, org):
|
async def test_fields_round_trip_through_the_api(self, client, auth, org, approved_plan):
|
||||||
dcr_id, doctors, chemists = await _draft(client, auth, org)
|
dcr_id, doctors, chemists = await _draft(client, auth, org, approved_plan)
|
||||||
d = await client.post(
|
d = await client.post(
|
||||||
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
||||||
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET",
|
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET",
|
||||||
@@ -35,27 +36,48 @@ class TestFormFields:
|
|||||||
assert patched.status_code == 200, patched.text
|
assert patched.status_code == 200, patched.text
|
||||||
|
|
||||||
report = (await client.get(f"{API}/dcr/{dcr_id}", headers=auth["mr1"])).json()
|
report = (await client.get(f"{API}/dcr/{dcr_id}", headers=auth["mr1"])).json()
|
||||||
assert report["doctor_calls"][0]["product_promote"] == "Calcium" # trimmed
|
# A single name is still accepted, and comes back as a one-item list.
|
||||||
assert report["doctor_calls"][0]["product_sample"] == "Vit D"
|
assert report["doctor_calls"][0]["product_promote"] == ["Calcium"] # trimmed
|
||||||
|
assert report["doctor_calls"][0]["product_sample"] == ["Vit D"]
|
||||||
assert report["chemist_calls"][0]["pob"] == "12,500"
|
assert report["chemist_calls"][0]["pob"] == "12,500"
|
||||||
assert report["stockist_visit"] == "Ganesh Distributors"
|
assert report["stockist_visit"] == "Ganesh Distributors"
|
||||||
assert report["order_value"] == "45,000"
|
assert report["order_value"] == "45,000"
|
||||||
|
|
||||||
async def test_blank_values_are_stored_as_null_and_can_be_cleared(self, client, auth, org):
|
async def test_several_products_per_visit(self, client, auth, org, approved_plan):
|
||||||
dcr_id, _, _ = await _draft(client, auth, org)
|
dcr_id, doctors, _ = await _draft(client, auth, org, approved_plan)
|
||||||
|
d = await client.post(
|
||||||
|
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
||||||
|
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET",
|
||||||
|
"product_promote": ["Calcium", " Vit D ", "calcium", "", "Zinc"],
|
||||||
|
"product_sample": ["Iron", "Omega 3", "B12"]},
|
||||||
|
)
|
||||||
|
assert d.status_code == 201, d.text
|
||||||
|
call = d.json()["doctor_calls"][0]
|
||||||
|
assert call["product_promote"] == ["Calcium", "Vit D", "Zinc"] # trimmed, de-duplicated
|
||||||
|
assert call["product_sample"] == ["Iron", "Omega 3", "B12"]
|
||||||
|
|
||||||
|
too_many = await client.post(
|
||||||
|
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
||||||
|
json={"doctor_id": doctors[1]["id"], "visit_time": "09:40:00", "call_outcome": "MET",
|
||||||
|
"product_promote": [f"P{i}" for i in range(11)]},
|
||||||
|
)
|
||||||
|
assert too_many.status_code == 422
|
||||||
|
|
||||||
|
async def test_blank_values_are_stored_as_null_and_can_be_cleared(self, client, auth, org, approved_plan):
|
||||||
|
dcr_id, _, _ = await _draft(client, auth, org, approved_plan)
|
||||||
await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"stockist_visit": "X"})
|
await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"stockist_visit": "X"})
|
||||||
cleared = await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"stockist_visit": " "})
|
cleared = await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"stockist_visit": " "})
|
||||||
assert cleared.json()["stockist_visit"] is None
|
assert cleared.json()["stockist_visit"] is None
|
||||||
|
|
||||||
async def test_patching_one_field_leaves_the_others_alone(self, client, auth, org):
|
async def test_patching_one_field_leaves_the_others_alone(self, client, auth, org, approved_plan):
|
||||||
dcr_id, _, _ = await _draft(client, auth, org)
|
dcr_id, _, _ = await _draft(client, auth, org, approved_plan)
|
||||||
await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"mr_remarks": "Good day", "order_value": "10"})
|
await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"mr_remarks": "Good day", "order_value": "10"})
|
||||||
again = await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"stockist_visit": "S"})
|
again = await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"stockist_visit": "S"})
|
||||||
body = again.json()
|
body = again.json()
|
||||||
assert (body["mr_remarks"], body["order_value"], body["stockist_visit"]) == ("Good day", "10", "S")
|
assert (body["mr_remarks"], body["order_value"], body["stockist_visit"]) == ("Good day", "10", "S")
|
||||||
|
|
||||||
async def test_too_long_values_are_rejected(self, client, auth, org):
|
async def test_too_long_values_are_rejected(self, client, auth, org, approved_plan):
|
||||||
dcr_id, doctors, _ = await _draft(client, auth, org)
|
dcr_id, doctors, _ = await _draft(client, auth, org, approved_plan)
|
||||||
too_long = await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"stockist_visit": "x" * 201})
|
too_long = await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"stockist_visit": "x" * 201})
|
||||||
assert too_long.status_code == 422
|
assert too_long.status_code == 422
|
||||||
bad_call = await client.post(
|
bad_call = await client.post(
|
||||||
@@ -64,8 +86,8 @@ class TestFormFields:
|
|||||||
)
|
)
|
||||||
assert bad_call.status_code == 422
|
assert bad_call.status_code == 422
|
||||||
|
|
||||||
async def test_only_the_owner_can_edit_them_and_only_while_editable(self, client, auth, org):
|
async def test_only_the_owner_can_edit_them_and_only_while_editable(self, client, auth, org, approved_plan):
|
||||||
dcr_id, doctors, _ = await _draft(client, auth, org)
|
dcr_id, doctors, _ = await _draft(client, auth, org, approved_plan)
|
||||||
assert (await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr2"], json={"order_value": "1"})).status_code in (403, 404)
|
assert (await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr2"], json={"order_value": "1"})).status_code in (403, 404)
|
||||||
assert (await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["am1"], json={"order_value": "1"})).status_code == 403
|
assert (await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["am1"], json={"order_value": "1"})).status_code == 403
|
||||||
await client.post(
|
await client.post(
|
||||||
@@ -76,8 +98,8 @@ class TestFormFields:
|
|||||||
locked = await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"order_value": "1"})
|
locked = await client.patch(f"{API}/dcr/{dcr_id}", headers=auth["mr1"], json={"order_value": "1"})
|
||||||
assert locked.status_code == 409 # submitted reports are locked
|
assert locked.status_code == 409 # submitted reports are locked
|
||||||
|
|
||||||
async def test_approved_pdf_is_generated_with_the_new_layout(self, client, auth, org):
|
async def test_approved_pdf_is_generated_with_the_new_layout(self, client, auth, org, approved_plan):
|
||||||
dcr_id, doctors, chemists = await _draft(client, auth, org)
|
dcr_id, doctors, chemists = await _draft(client, auth, org, approved_plan)
|
||||||
await client.post(
|
await client.post(
|
||||||
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
||||||
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET", "product_promote": "Calcium"},
|
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET", "product_promote": "Calcium"},
|
||||||
@@ -91,8 +113,8 @@ class TestFormFields:
|
|||||||
class TestResponsesReflectTheChange:
|
class TestResponsesReflectTheChange:
|
||||||
"""Regression: the response to an add/remove used to list the visits as they were BEFORE it."""
|
"""Regression: the response to an add/remove used to list the visits as they were BEFORE it."""
|
||||||
|
|
||||||
async def test_adding_a_visit_returns_it_in_the_same_response(self, client, auth, org):
|
async def test_adding_a_visit_returns_it_in_the_same_response(self, client, auth, org, approved_plan):
|
||||||
dcr_id, doctors, chemists = await _draft(client, auth, org)
|
dcr_id, doctors, chemists = await _draft(client, auth, org, approved_plan)
|
||||||
added = await client.post(
|
added = await client.post(
|
||||||
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
||||||
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
|
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
|
||||||
@@ -105,8 +127,8 @@ class TestResponsesReflectTheChange:
|
|||||||
body = second.json()
|
body = second.json()
|
||||||
assert len(body["doctor_calls"]) == 1 and len(body["chemist_calls"]) == 1
|
assert len(body["doctor_calls"]) == 1 and len(body["chemist_calls"]) == 1
|
||||||
|
|
||||||
async def test_removing_a_visit_returns_the_report_without_it(self, client, auth, org):
|
async def test_removing_a_visit_returns_the_report_without_it(self, client, auth, org, approved_plan):
|
||||||
dcr_id, doctors, _ = await _draft(client, auth, org)
|
dcr_id, doctors, _ = await _draft(client, auth, org, approved_plan)
|
||||||
for i, doctor in enumerate(doctors):
|
for i, doctor in enumerate(doctors):
|
||||||
r = await client.post(
|
r = await client.post(
|
||||||
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
||||||
@@ -123,14 +145,14 @@ class TestResponsesReflectTheChange:
|
|||||||
|
|
||||||
|
|
||||||
class TestDownloadUsesTheCurrentLayout:
|
class TestDownloadUsesTheCurrentLayout:
|
||||||
async def test_a_report_approved_under_an_older_layout_still_downloads_in_the_new_one(self, client, auth, org, db):
|
async def test_a_report_approved_under_an_older_layout_still_downloads_in_the_new_one(self, client, auth, org, db, approved_plan):
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
|
|
||||||
from app.reports.models import DailyCallReport
|
from app.reports.models import DailyCallReport
|
||||||
|
|
||||||
dcr_id, doctors, _ = await _draft(client, auth, org)
|
dcr_id, doctors, _ = await _draft(client, auth, org, approved_plan)
|
||||||
await client.post(
|
await client.post(
|
||||||
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
||||||
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
|
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
|
||||||
@@ -146,14 +168,15 @@ class TestDownloadUsesTheCurrentLayout:
|
|||||||
assert pdf.status_code == 200
|
assert pdf.status_code == 200
|
||||||
assert b"OLD DESIGN" not in pdf.content and pdf.content.startswith(b"%PDF-") and len(pdf.content) > 5000
|
assert b"OLD DESIGN" not in pdf.content and pdf.content.startswith(b"%PDF-") and len(pdf.content) > 5000
|
||||||
# ...and still only for approved reports.
|
# ...and still only for approved reports.
|
||||||
draft_id, _, _ = await _draft_second(client, auth, org)
|
draft_id, _, _ = await _draft_second(client, auth, org, approved_plan)
|
||||||
assert (await client.get(f"{API}/dcr/{draft_id}/pdf", headers=auth["mr1"])).status_code == 422
|
assert (await client.get(f"{API}/dcr/{draft_id}/pdf", headers=auth["mr1"])).status_code == 422
|
||||||
|
|
||||||
|
|
||||||
async def _draft_second(client, auth, org):
|
async def _draft_second(client, auth, org, approved_plan):
|
||||||
"""A second, unapproved report (yesterday's) for the same MR."""
|
"""A second, unapproved report (yesterday's) for the same MR."""
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
|
||||||
|
await approved_plan(date.today() - timedelta(days=1))
|
||||||
resp = await client.post(
|
resp = await client.post(
|
||||||
f"{API}/dcr", headers=auth["mr1"], json={"report_date": (date.today() - timedelta(days=1)).isoformat()}
|
f"{API}/dcr", headers=auth["mr1"], json={"report_date": (date.today() - timedelta(days=1)).isoformat()}
|
||||||
)
|
)
|
||||||
@@ -162,14 +185,14 @@ async def _draft_second(client, auth, org):
|
|||||||
|
|
||||||
|
|
||||||
class TestApprovedPdfIsSigned:
|
class TestApprovedPdfIsSigned:
|
||||||
async def test_the_pdf_names_the_approving_area_manager_from_the_audit_trail(self, client, auth, org, db):
|
async def test_the_pdf_names_the_approving_area_manager_from_the_audit_trail(self, client, auth, org, db, approved_plan):
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
|
|
||||||
from app.pdf.service import PDFService
|
from app.pdf.service import PDFService
|
||||||
from app.reports.models import DailyCallReport
|
from app.reports.models import DailyCallReport
|
||||||
from app.reports.repository import DCRRepository
|
from app.reports.repository import DCRRepository
|
||||||
|
|
||||||
dcr_id, doctors, _ = await _draft(client, auth, org)
|
dcr_id, doctors, _ = await _draft(client, auth, org, approved_plan)
|
||||||
await client.post(
|
await client.post(
|
||||||
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
f"{API}/dcr/{dcr_id}/calls/doctor", headers=auth["mr1"],
|
||||||
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
|
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
|
||||||
@@ -184,10 +207,10 @@ class TestApprovedPdfIsSigned:
|
|||||||
assert context["approval"]["name"] == "Suresh Behera"
|
assert context["approval"]["name"] == "Suresh Behera"
|
||||||
assert len(context["approval"]["at"]) == 16 and context["mr_signed"] == "Ravi Das (MR001)"
|
assert len(context["approval"]["at"]) == 16 and context["mr_signed"] == "Ravi Das (MR001)"
|
||||||
|
|
||||||
async def test_a_report_that_is_not_approved_has_no_approval_signature(self, client, auth, org, db):
|
async def test_a_report_that_is_not_approved_has_no_approval_signature(self, client, auth, org, db, approved_plan):
|
||||||
from app.pdf.service import PDFService
|
from app.pdf.service import PDFService
|
||||||
from app.reports.repository import DCRRepository
|
from app.reports.repository import DCRRepository
|
||||||
|
|
||||||
dcr_id, _, _ = await _draft(client, auth, org)
|
dcr_id, _, _ = await _draft(client, auth, org, approved_plan)
|
||||||
report = await DCRRepository(db).get_full(dcr_id if not isinstance(dcr_id, str) else __import__("uuid").UUID(dcr_id))
|
report = await DCRRepository(db).get_full(dcr_id if not isinstance(dcr_id, str) else __import__("uuid").UUID(dcr_id))
|
||||||
assert (await PDFService(db)._context(report))["approval"] is None
|
assert (await PDFService(db)._context(report))["approval"] is None
|
||||||
|
|||||||
@@ -33,8 +33,9 @@ async def _audit_count(db, entity_id, action) -> int:
|
|||||||
|
|
||||||
|
|
||||||
class TestReports:
|
class TestReports:
|
||||||
async def _submitted(self, client, auth, org):
|
async def _submitted(self, client, auth, org, approved_plan):
|
||||||
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=1)
|
||||||
|
await approved_plan()
|
||||||
dcr = (await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()})).json()["id"]
|
dcr = (await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()})).json()["id"]
|
||||||
await client.post(
|
await client.post(
|
||||||
f"{API}/dcr/{dcr}/calls/doctor", headers=auth["mr1"],
|
f"{API}/dcr/{dcr}/calls/doctor", headers=auth["mr1"],
|
||||||
@@ -42,8 +43,8 @@ class TestReports:
|
|||||||
)
|
)
|
||||||
return dcr, doctors
|
return dcr, doctors
|
||||||
|
|
||||||
async def test_submitting_twice_is_one_submission(self, client, auth, org, db):
|
async def test_submitting_twice_is_one_submission(self, client, auth, org, db, approved_plan):
|
||||||
dcr, _ = await self._submitted(client, auth, org)
|
dcr, _ = await self._submitted(client, auth, org, approved_plan)
|
||||||
first = await client.post(f"{API}/dcr/{dcr}/submit", headers=auth["mr1"])
|
first = await client.post(f"{API}/dcr/{dcr}/submit", headers=auth["mr1"])
|
||||||
second = await client.post(f"{API}/dcr/{dcr}/submit", headers=auth["mr1"])
|
second = await client.post(f"{API}/dcr/{dcr}/submit", headers=auth["mr1"])
|
||||||
assert first.status_code == second.status_code == 200
|
assert first.status_code == second.status_code == 200
|
||||||
@@ -51,8 +52,8 @@ class TestReports:
|
|||||||
assert second.json()["submitted_at"] == first.json()["submitted_at"]
|
assert second.json()["submitted_at"] == first.json()["submitted_at"]
|
||||||
assert await _audit_count(db, dcr, "SUBMIT") == 1
|
assert await _audit_count(db, dcr, "SUBMIT") == 1
|
||||||
|
|
||||||
async def test_approving_twice_is_one_approval(self, client, auth, org, db):
|
async def test_approving_twice_is_one_approval(self, client, auth, org, db, approved_plan):
|
||||||
dcr, _ = await self._submitted(client, auth, org)
|
dcr, _ = await self._submitted(client, auth, org, approved_plan)
|
||||||
await client.post(f"{API}/dcr/{dcr}/submit", headers=auth["mr1"])
|
await client.post(f"{API}/dcr/{dcr}/submit", headers=auth["mr1"])
|
||||||
first = await client.post(f"{API}/dcr/{dcr}/approve", headers=auth["am1"], json={})
|
first = await client.post(f"{API}/dcr/{dcr}/approve", headers=auth["am1"], json={})
|
||||||
second = await client.post(f"{API}/dcr/{dcr}/approve", headers=auth["am1"], json={})
|
second = await client.post(f"{API}/dcr/{dcr}/approve", headers=auth["am1"], json={})
|
||||||
@@ -60,14 +61,14 @@ class TestReports:
|
|||||||
assert second.json()["approved_at"] == first.json()["approved_at"]
|
assert second.json()["approved_at"] == first.json()["approved_at"]
|
||||||
assert await _audit_count(db, dcr, "APPROVE") == 1
|
assert await _audit_count(db, dcr, "APPROVE") == 1
|
||||||
|
|
||||||
async def test_an_area_manager_of_another_hq_still_cannot_approve(self, client, auth, org):
|
async def test_an_area_manager_of_another_hq_still_cannot_approve(self, client, auth, org, approved_plan):
|
||||||
dcr, _ = await self._submitted(client, auth, org)
|
dcr, _ = await self._submitted(client, auth, org, approved_plan)
|
||||||
await client.post(f"{API}/dcr/{dcr}/submit", headers=auth["mr1"])
|
await client.post(f"{API}/dcr/{dcr}/submit", headers=auth["mr1"])
|
||||||
await client.post(f"{API}/dcr/{dcr}/approve", headers=auth["am1"], json={})
|
await client.post(f"{API}/dcr/{dcr}/approve", headers=auth["am1"], json={})
|
||||||
assert (await client.post(f"{API}/dcr/{dcr}/approve", headers=auth["am2"], json={})).status_code == 403
|
assert (await client.post(f"{API}/dcr/{dcr}/approve", headers=auth["am2"], json={})).status_code == 403
|
||||||
|
|
||||||
async def test_adding_the_same_visit_or_creating_the_same_report_twice_is_refused(self, client, auth, org):
|
async def test_adding_the_same_visit_or_creating_the_same_report_twice_is_refused(self, client, auth, org, approved_plan):
|
||||||
dcr, doctors = await self._submitted(client, auth, org)
|
dcr, doctors = await self._submitted(client, auth, org, approved_plan)
|
||||||
again = await client.post(
|
again = await client.post(
|
||||||
f"{API}/dcr/{dcr}/calls/doctor", headers=auth["mr1"],
|
f"{API}/dcr/{dcr}/calls/doctor", headers=auth["mr1"],
|
||||||
json={"doctor_id": doctors[0]["id"], "visit_time": "10:30:00", "call_outcome": "MET"},
|
json={"doctor_id": doctors[0]["id"], "visit_time": "10:30:00", "call_outcome": "MET"},
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ class TestFormApproval:
|
|||||||
async def test_every_approval_form_starts_as_draft_for_everyone(self, client, auth):
|
async def test_every_approval_form_starts_as_draft_for_everyone(self, client, auth):
|
||||||
# An MR sees all three forms as drafts; an Area Manager or admin has nothing to act on yet.
|
# An MR sees all three forms as drafts; an Area Manager or admin has nothing to act on yet.
|
||||||
forms = _by_table(await client.get(f"{API}/approvals", headers=auth["mr1"]))
|
forms = _by_table(await client.get(f"{API}/approvals", headers=auth["mr1"]))
|
||||||
assert set(forms) == {"tour_plan", "standard_tour_plan", "fare_chart"}
|
assert set(forms) == {"tour_plan", "standard_tour_plan", "fare_chart", "expense_statement"}
|
||||||
assert {f["status"] for f in forms.values()} == {"draft"}
|
assert {f["status"] for f in forms.values()} == {"draft"}
|
||||||
for who in ("am1", "admin"):
|
for who in ("am1", "admin"):
|
||||||
resp = await client.get(f"{API}/approvals", headers=auth[who])
|
resp = await client.get(f"{API}/approvals", headers=auth[who])
|
||||||
@@ -94,10 +94,9 @@ class TestFormApproval:
|
|||||||
state = _by_table(await client.get(f"{API}/approvals", headers=auth["mr1"]))["fare_chart"]
|
state = _by_table(await client.get(f"{API}/approvals", headers=auth["mr1"]))["fare_chart"]
|
||||||
assert state["status"] == "draft" and state["approved_by_name"] is None
|
assert state["status"] == "draft" and state["approved_by_name"] is None
|
||||||
# A pending (not yet approved) form is withdrawn too, so the AM never signs stale data.
|
# A pending (not yet approved) form is withdrawn too, so the AM never signs stale data.
|
||||||
# Deleting a row is admin-only — an MR can no longer delete their own rows.
|
# An MR may remove a row they entered by mistake; that too withdraws the request.
|
||||||
await client.post(f"{API}/fare_chart/approval/request", headers=auth["mr1"])
|
await client.post(f"{API}/fare_chart/approval/request", headers=auth["mr1"])
|
||||||
assert (await client.delete(f"{API}/fare_chart/rows/{row_id}", headers=auth["mr1"])).status_code == 403
|
assert (await client.delete(f"{API}/fare_chart/rows/{row_id}", headers=auth["mr1"])).status_code == 204
|
||||||
assert (await client.delete(f"{API}/fare_chart/rows/{row_id}", headers=auth["admin"])).status_code == 204
|
|
||||||
assert (await client.get(f"{API}/approvals", headers=auth["am1"])).json() == [] # withdrawn: nothing left for the AM
|
assert (await client.get(f"{API}/approvals", headers=auth["am1"])).json() == [] # withdrawn: nothing left for the AM
|
||||||
|
|
||||||
async def test_the_pdf_signature_comes_from_the_server_not_the_browser(self, client, auth, org, db, fare_chart):
|
async def test_the_pdf_signature_comes_from_the_server_not_the_browser(self, client, auth, org, db, fare_chart):
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
"""Company forms: listed in the company's order, and readable (never writable) by the GM."""
|
||||||
|
|
||||||
|
from tests.e2e.test_form_ownership import forms # noqa: F401 - creates the form tables
|
||||||
|
|
||||||
|
API = "/api/v1"
|
||||||
|
|
||||||
|
ORDER = [
|
||||||
|
"standard_tour_plan",
|
||||||
|
"tour_plan",
|
||||||
|
"fare_chart",
|
||||||
|
"sales_and_stock_statement",
|
||||||
|
"sales_projection",
|
||||||
|
"field_activity_report",
|
||||||
|
"expense_statement",
|
||||||
|
"area_covered",
|
||||||
|
"weekly_report",
|
||||||
|
"core_dr_call_conversion",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class TestFormsForTheGeneralManager:
|
||||||
|
async def test_forms_are_listed_in_the_company_order(self, client, auth, org):
|
||||||
|
for who in ("mr1", "gm", "admin"):
|
||||||
|
tables = (await client.get(f"{API}/csv-data/tables", headers=auth[who])).json()
|
||||||
|
assert [t["name"] for t in tables] == ORDER
|
||||||
|
|
||||||
|
async def test_gm_reads_every_mrs_rows_and_pdf(self, client, auth, org, forms): # noqa: F811
|
||||||
|
added = await client.post(
|
||||||
|
f"{API}/csv-data/tour_plan/rows", headers=auth["mr1"], json={"from_location": "Puri"}
|
||||||
|
)
|
||||||
|
assert added.status_code == 201, added.text
|
||||||
|
rows = (await client.get(f"{API}/csv-data/tour_plan/rows", headers=auth["gm"])).json()
|
||||||
|
assert [r["from_location"] for r in rows] == ["Puri"]
|
||||||
|
owners = (await client.get(f"{API}/csv-data/owners", headers=auth["gm"])).json()
|
||||||
|
assert {o["id"] for o in owners} == {str(org["mr1"].id), str(org["mr2"].id)}
|
||||||
|
mine = await client.get(
|
||||||
|
f"{API}/csv-data/tour_plan/rows?owner_id={org['mr1'].id}", headers=auth["gm"]
|
||||||
|
)
|
||||||
|
assert mine.status_code == 200 and len(mine.json()) == 1
|
||||||
|
pdf = await client.get(f"{API}/csv-data/tour_plan/pdf", headers=auth["gm"])
|
||||||
|
assert pdf.status_code == 200 and pdf.content.startswith(b"%PDF-")
|
||||||
|
|
||||||
|
async def test_gm_cannot_change_or_approve_a_form(self, client, auth, org, forms): # noqa: F811
|
||||||
|
row = (
|
||||||
|
await client.post(
|
||||||
|
f"{API}/csv-data/tour_plan/rows", headers=auth["mr1"], json={"to_location": "Puri"}
|
||||||
|
)
|
||||||
|
).json()
|
||||||
|
add = await client.post(
|
||||||
|
f"{API}/csv-data/tour_plan/rows?owner_id={org['mr1'].id}",
|
||||||
|
headers=auth["gm"],
|
||||||
|
json={"to_location": "Cuttack"},
|
||||||
|
)
|
||||||
|
assert add.status_code == 403
|
||||||
|
edit = await client.patch(
|
||||||
|
f"{API}/csv-data/tour_plan/rows/{row['id']}", headers=auth["gm"], json={"pob": "1"}
|
||||||
|
)
|
||||||
|
assert edit.status_code == 403
|
||||||
|
delete = await client.delete(
|
||||||
|
f"{API}/csv-data/tour_plan/rows/{row['id']}", headers=auth["gm"]
|
||||||
|
)
|
||||||
|
assert delete.status_code == 403
|
||||||
|
approve = await client.post(
|
||||||
|
f"{API}/csv-data/tour_plan/approval/approve?owner_id={org['mr1'].id}",
|
||||||
|
headers=auth["gm"],
|
||||||
|
)
|
||||||
|
assert approve.status_code == 403
|
||||||
@@ -151,3 +151,48 @@ class TestMonthlyDownload:
|
|||||||
async def test_a_form_without_a_month_rejects_the_filter(self, client, auth, forms):
|
async def test_a_form_without_a_month_rejects_the_filter(self, client, auth, forms):
|
||||||
resp = await client.get(f"{API}/fare_chart/pdf", headers=auth["mr1"], params={"month": "November"})
|
resp = await client.get(f"{API}/fare_chart/pdf", headers=auth["mr1"], params={"month": "November"})
|
||||||
assert resp.status_code == 422
|
assert resp.status_code == 422
|
||||||
|
|
||||||
|
|
||||||
|
class TestExpenseStatement:
|
||||||
|
async def test_the_total_is_worked_out_by_the_server(self, client, auth, db):
|
||||||
|
await _make_table(db, "expense_statement", owned=True)
|
||||||
|
made = await client.post(
|
||||||
|
f"{API}/expense_statement/rows", headers=auth["mr1"],
|
||||||
|
json={"report_date": "2026-10-01", "fare": "120.50", "da_hq": "100", "total": "1"},
|
||||||
|
)
|
||||||
|
assert made.status_code == 201, made.text
|
||||||
|
assert made.json()["total"] == "220.50" and made.json()["name"] == "Ravi Das"
|
||||||
|
row = made.json()["id"]
|
||||||
|
changed = await client.patch(f"{API}/expense_statement/rows/{row}", headers=auth["mr1"], json={"postage": "9.50", "total": "5"})
|
||||||
|
assert changed.status_code == 200 and changed.json()["total"] == "230.00"
|
||||||
|
bad = await client.patch(f"{API}/expense_statement/rows/{row}", headers=auth["mr1"], json={"fare": "abc"})
|
||||||
|
assert bad.status_code == 422
|
||||||
|
|
||||||
|
async def test_clearing_one_cell_of_a_row_that_has_other_values_is_allowed(self, client, auth, db):
|
||||||
|
await _make_table(db, "expense_statement", owned=True)
|
||||||
|
made = await client.post(f"{API}/expense_statement/rows", headers=auth["admin"], json={"from_location": "A", "fare": "10"}, params={"owner_id": str((await client.get(f"{API}/owners", headers=auth["admin"])).json()[0]["id"])})
|
||||||
|
assert made.status_code == 201, made.text
|
||||||
|
cleared = await client.patch(f"{API}/expense_statement/rows/{made.json()['id']}", headers=auth["admin"], json={"fare": ""})
|
||||||
|
assert cleared.status_code == 200, cleared.text
|
||||||
|
assert cleared.json()["fare"] == "" and cleared.json()["total"] is None
|
||||||
|
|
||||||
|
|
||||||
|
class TestRemovingAMistake:
|
||||||
|
async def test_an_mr_removes_their_own_row_and_the_rest_are_renumbered(self, client, auth, forms):
|
||||||
|
first = await _add(client, auth["mr1"], "A")
|
||||||
|
await _add(client, auth["mr1"], "B")
|
||||||
|
assert (await client.delete(f"{API}/fare_chart/rows/{first}", headers=auth["mr1"])).status_code == 204
|
||||||
|
mine = (await client.get(f"{API}/fare_chart/rows", headers=auth["mr1"])).json()
|
||||||
|
assert [(r["from_location"], r["serial_no"]) for r in mine] == [("B", "1")]
|
||||||
|
|
||||||
|
async def test_an_mr_removes_an_extra_copy_of_a_product_but_never_its_only_row(self, client, auth, db):
|
||||||
|
await _make_table(db, "sales_projection", owned=False)
|
||||||
|
made = await client.post(f"{API}/sales_projection/rows", headers=auth["admin"], json={"product_name": "INTEZOLE-PD", "pts": "106.92"})
|
||||||
|
assert made.status_code == 201, made.text
|
||||||
|
row = made.json()["id"]
|
||||||
|
extra = await client.post(f"{API}/sales_projection/rows", headers=auth["mr1"], json={"product_name": "INTEZOLE-PD", "month": "August"})
|
||||||
|
assert extra.status_code == 201, extra.text
|
||||||
|
assert (await client.delete(f"{API}/sales_projection/rows/{extra.json()['id']}", headers=auth["mr1"])).status_code == 204
|
||||||
|
assert (await client.delete(f"{API}/sales_projection/rows/{row}", headers=auth["mr1"])).status_code == 403
|
||||||
|
cleared = await client.patch(f"{API}/sales_projection/rows/{row}", headers=auth["mr1"], json={"closing_qty": "", "month": ""})
|
||||||
|
assert cleared.status_code == 200 and cleared.json()["product_name"] == "INTEZOLE-PD"
|
||||||
|
|||||||
@@ -137,18 +137,40 @@ class TestStep3And5Masters:
|
|||||||
resp = await client.get(f"{API}/doctors", headers=auth["mr2"])
|
resp = await client.get(f"{API}/doctors", headers=auth["mr2"])
|
||||||
assert resp.json() == []
|
assert resp.json() == []
|
||||||
|
|
||||||
async def test_mr_cannot_create_a_doctor(self, client, auth, org):
|
async def test_mr_creates_doctor_and_chemist_in_own_hq(self, client, auth, org):
|
||||||
"""A3/Q3 — not permitted in the MVP."""
|
"""The MR's new doctor and chemist are assigned to them, so they show up at once."""
|
||||||
|
hq1 = str(org["hq1"].id)
|
||||||
|
doctor = await client.post(
|
||||||
|
f"{API}/doctors",
|
||||||
|
headers=auth["mr1"],
|
||||||
|
json={"headquarters_id": hq1, "name": "Dr Selfmade", "clinic_address": "Nowhere"},
|
||||||
|
)
|
||||||
|
assert doctor.status_code == 201
|
||||||
|
chemist = await client.post(
|
||||||
|
f"{API}/chemists",
|
||||||
|
headers=auth["mr1"],
|
||||||
|
json={"headquarters_id": hq1, "name": "Selfmade Pharmacy", "shop_address": "Nowhere"},
|
||||||
|
)
|
||||||
|
assert chemist.status_code == 201
|
||||||
|
|
||||||
|
doctors = (await client.get(f"{API}/doctors", headers=auth["mr1"])).json()
|
||||||
|
assert doctor.json()["id"] in {d["id"] for d in doctors}
|
||||||
|
chemists = (await client.get(f"{API}/chemists", headers=auth["mr1"])).json()
|
||||||
|
assert chemist.json()["id"] in {c["id"] for c in chemists}
|
||||||
|
|
||||||
|
async def test_mr_cannot_create_outside_own_hq_or_a_product(self, client, auth, org):
|
||||||
resp = await client.post(
|
resp = await client.post(
|
||||||
f"{API}/doctors",
|
f"{API}/doctors",
|
||||||
headers=auth["mr1"],
|
headers=auth["mr1"],
|
||||||
json={
|
json={
|
||||||
"headquarters_id": str(org["hq1"].id),
|
"headquarters_id": str(org["hq2"].id),
|
||||||
"name": "Dr Selfmade",
|
"name": "Dr Elsewhere",
|
||||||
"clinic_address": "Nowhere",
|
"clinic_address": "Nowhere",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
assert resp.status_code == 403
|
assert resp.status_code == 403
|
||||||
|
resp = await client.post(f"{API}/products", headers=auth["mr1"], json={"name": "Pill"})
|
||||||
|
assert resp.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
class TestStep4Login:
|
class TestStep4Login:
|
||||||
@@ -193,9 +215,10 @@ class TestStep4Login:
|
|||||||
|
|
||||||
|
|
||||||
class TestFullApprovalFlow:
|
class TestFullApprovalFlow:
|
||||||
async def test_thirteen_step_flow(self, client, auth, org):
|
async def test_thirteen_step_flow(self, client, auth, org, approved_plan):
|
||||||
doctors, chemists = await _create_masters(client, auth, org)
|
doctors, chemists = await _create_masters(client, auth, org)
|
||||||
today = date.today().isoformat()
|
today = date.today().isoformat()
|
||||||
|
await approved_plan()
|
||||||
|
|
||||||
# --- Step 5: MR creates a DCR ---------------------------------
|
# --- Step 5: MR creates a DCR ---------------------------------
|
||||||
resp = await client.post(
|
resp = await client.post(
|
||||||
@@ -391,8 +414,9 @@ class TestFullApprovalFlow:
|
|||||||
|
|
||||||
|
|
||||||
class TestNegativeScope:
|
class TestNegativeScope:
|
||||||
async def _submitted_report(self, client, auth, org):
|
async def _submitted_report(self, client, auth, org, approved_plan):
|
||||||
doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
||||||
|
await approved_plan()
|
||||||
resp = await client.post(
|
resp = await client.post(
|
||||||
f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()}
|
f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()}
|
||||||
)
|
)
|
||||||
@@ -409,8 +433,8 @@ class TestNegativeScope:
|
|||||||
await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"])
|
await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"])
|
||||||
return dcr_id
|
return dcr_id
|
||||||
|
|
||||||
async def test_x1_second_mr_cannot_see_the_first_mrs_report(self, client, auth, org):
|
async def test_x1_second_mr_cannot_see_the_first_mrs_report(self, client, auth, org, approved_plan):
|
||||||
dcr_id = await self._submitted_report(client, auth, org)
|
dcr_id = await self._submitted_report(client, auth, org, approved_plan)
|
||||||
|
|
||||||
resp = await client.get(f"{API}/dcr/{dcr_id}", headers=auth["mr2"])
|
resp = await client.get(f"{API}/dcr/{dcr_id}", headers=auth["mr2"])
|
||||||
assert resp.status_code == 403, resp.text
|
assert resp.status_code == 403, resp.text
|
||||||
@@ -420,8 +444,8 @@ class TestNegativeScope:
|
|||||||
listing = await client.get(f"{API}/dcr", headers=auth["mr2"])
|
listing = await client.get(f"{API}/dcr", headers=auth["mr2"])
|
||||||
assert listing.json() == []
|
assert listing.json() == []
|
||||||
|
|
||||||
async def test_x2_area_manager_of_another_hq_cannot_see_it(self, client, auth, org):
|
async def test_x2_area_manager_of_another_hq_cannot_see_it(self, client, auth, org, approved_plan):
|
||||||
dcr_id = await self._submitted_report(client, auth, org)
|
dcr_id = await self._submitted_report(client, auth, org, approved_plan)
|
||||||
|
|
||||||
resp = await client.get(f"{API}/dcr/{dcr_id}", headers=auth["am2"])
|
resp = await client.get(f"{API}/dcr/{dcr_id}", headers=auth["am2"])
|
||||||
assert resp.status_code == 403, resp.text
|
assert resp.status_code == 403, resp.text
|
||||||
@@ -435,9 +459,9 @@ class TestNegativeScope:
|
|||||||
listing = await client.get(f"{API}/dcr?status=PENDING_AM", headers=auth["am2"])
|
listing = await client.get(f"{API}/dcr?status=PENDING_AM", headers=auth["am2"])
|
||||||
assert listing.json() == []
|
assert listing.json() == []
|
||||||
|
|
||||||
async def test_x3_admin_cannot_approve(self, client, auth, org):
|
async def test_x3_admin_cannot_approve(self, client, auth, org, approved_plan):
|
||||||
"""SEC-2 — the single most important governance rule in the design."""
|
"""SEC-2 — the single most important governance rule in the design."""
|
||||||
dcr_id = await self._submitted_report(client, auth, org)
|
dcr_id = await self._submitted_report(client, auth, org, approved_plan)
|
||||||
|
|
||||||
resp = await client.post(f"{API}/dcr/{dcr_id}/approve", headers=auth["admin"], json={})
|
resp = await client.post(f"{API}/dcr/{dcr_id}/approve", headers=auth["admin"], json={})
|
||||||
assert resp.status_code == 403, resp.text
|
assert resp.status_code == 403, resp.text
|
||||||
@@ -489,7 +513,8 @@ class TestValidationRules:
|
|||||||
assert resp.status_code == 422
|
assert resp.status_code == 422
|
||||||
assert "back-dating" in resp.json()["error"]["message"]
|
assert "back-dating" in resp.json()["error"]["message"]
|
||||||
|
|
||||||
async def test_v4_cannot_submit_without_a_doctor_call(self, client, auth, org):
|
async def test_v4_cannot_submit_without_a_doctor_call(self, client, auth, org, approved_plan):
|
||||||
|
await approved_plan()
|
||||||
resp = await client.post(
|
resp = await client.post(
|
||||||
f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()}
|
f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()}
|
||||||
)
|
)
|
||||||
@@ -499,8 +524,9 @@ class TestValidationRules:
|
|||||||
assert submit.status_code == 422
|
assert submit.status_code == 422
|
||||||
assert "at least one doctor call" in submit.json()["error"]["message"]
|
assert "at least one doctor call" in submit.json()["error"]["message"]
|
||||||
|
|
||||||
async def test_v6_unassigned_doctor_rejected(self, client, auth, org):
|
async def test_v6_unassigned_doctor_rejected(self, client, auth, org, approved_plan):
|
||||||
"""A doctor from another HQ, not assigned to this MR."""
|
"""A doctor from another HQ, not assigned to this MR."""
|
||||||
|
await approved_plan()
|
||||||
other = await client.post(
|
other = await client.post(
|
||||||
f"{API}/doctors",
|
f"{API}/doctors",
|
||||||
headers=auth["admin"],
|
headers=auth["admin"],
|
||||||
@@ -527,8 +553,9 @@ class TestValidationRules:
|
|||||||
assert call.status_code == 422
|
assert call.status_code == 422
|
||||||
assert "not assigned" in call.json()["error"]["message"]
|
assert "not assigned" in call.json()["error"]["message"]
|
||||||
|
|
||||||
async def test_v7_conversion_status_only_for_core_doctors(self, client, auth, org):
|
async def test_v7_conversion_status_only_for_core_doctors(self, client, auth, org, approved_plan):
|
||||||
doctors, _ = await _create_masters(client, auth, org, n_doctors=5, n_chemists=1)
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=5, n_chemists=1)
|
||||||
|
await approved_plan()
|
||||||
non_core = next(d for d in doctors if not d["is_core_doctor"])
|
non_core = next(d for d in doctors if not d["is_core_doctor"])
|
||||||
|
|
||||||
resp = await client.post(
|
resp = await client.post(
|
||||||
@@ -549,8 +576,9 @@ class TestValidationRules:
|
|||||||
assert call.status_code == 422
|
assert call.status_code == 422
|
||||||
assert "core doctor" in call.json()["error"]["message"]
|
assert "core doctor" in call.json()["error"]["message"]
|
||||||
|
|
||||||
async def test_cannot_edit_while_pending_with_the_manager(self, client, auth, org):
|
async def test_cannot_edit_while_pending_with_the_manager(self, client, auth, org, approved_plan):
|
||||||
doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
||||||
|
await approved_plan()
|
||||||
resp = await client.post(
|
resp = await client.post(
|
||||||
f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()}
|
f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()}
|
||||||
)
|
)
|
||||||
@@ -572,8 +600,9 @@ class TestValidationRules:
|
|||||||
assert edit.status_code == 409
|
assert edit.status_code == 409
|
||||||
assert edit.json()["error"]["code"] == "REPORT_LOCKED"
|
assert edit.json()["error"]["code"] == "REPORT_LOCKED"
|
||||||
|
|
||||||
async def test_pdf_unavailable_before_approval(self, client, auth, org):
|
async def test_pdf_unavailable_before_approval(self, client, auth, org, approved_plan):
|
||||||
doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
||||||
|
await approved_plan()
|
||||||
resp = await client.post(
|
resp = await client.post(
|
||||||
f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()}
|
f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()}
|
||||||
)
|
)
|
||||||
@@ -585,8 +614,9 @@ class TestValidationRules:
|
|||||||
|
|
||||||
|
|
||||||
class TestStatusCounts:
|
class TestStatusCounts:
|
||||||
async def test_counts_replace_the_dashboard(self, client, auth, org):
|
async def test_counts_replace_the_dashboard(self, client, auth, org, approved_plan):
|
||||||
doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
||||||
|
await approved_plan()
|
||||||
resp = await client.post(
|
resp = await client.post(
|
||||||
f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()}
|
f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()}
|
||||||
)
|
)
|
||||||
@@ -595,4 +625,4 @@ class TestStatusCounts:
|
|||||||
counts = await client.get(f"{API}/dcr/counts", headers=auth["mr1"])
|
counts = await client.get(f"{API}/dcr/counts", headers=auth["mr1"])
|
||||||
assert counts.status_code == 200
|
assert counts.status_code == 200
|
||||||
assert counts.json()["DRAFT"] == 1
|
assert counts.json()["DRAFT"] == 1
|
||||||
assert counts.json()["APPROVED"] == 0
|
assert counts.json()["APPROVED"] == 1 # the day plan the report follows
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
"""A doctor or chemist an MR adds waits for their Area Manager; a doctor visit records a gift."""
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
API = "/api/v1"
|
||||||
|
|
||||||
|
|
||||||
|
async def _add_doctor(client, auth, org, name="Dr New", who="mr1", hq="hq1"):
|
||||||
|
resp = await client.post(
|
||||||
|
f"{API}/doctors", headers=auth[who],
|
||||||
|
json={"headquarters_id": str(org[hq].id), "name": name, "clinic_address": "Clinic 1, Bhubaneswar"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 201, resp.text
|
||||||
|
return resp.json()
|
||||||
|
|
||||||
|
|
||||||
|
async def _names(client, headers, path="/doctors"):
|
||||||
|
return [d["name"] for d in (await client.get(f"{API}{path}", headers=headers)).json()]
|
||||||
|
|
||||||
|
|
||||||
|
class TestAnMrsDoctorWaitsForTheAreaManager:
|
||||||
|
async def test_it_is_pending_and_unlisted_until_approved(self, client, auth, org):
|
||||||
|
doctor = await _add_doctor(client, auth, org)
|
||||||
|
assert doctor["approval_status"] == "PENDING" and doctor["requested_by_name"] == "Ravi Das"
|
||||||
|
assert "Dr New" not in await _names(client, auth["mr1"])
|
||||||
|
assert "Dr New" not in await _names(client, auth["am1"])
|
||||||
|
assert await _names(client, auth["mr1"], "/doctors/requests") == ["Dr New"]
|
||||||
|
assert await _names(client, auth["am1"], "/doctors/requests") == ["Dr New"]
|
||||||
|
assert await _names(client, auth["am2"], "/doctors/requests") == [] # another headquarters
|
||||||
|
|
||||||
|
approved = await client.post(f"{API}/doctors/{doctor['id']}/approve", headers=auth["am1"])
|
||||||
|
assert approved.status_code == 200 and approved.json()["approval_status"] == "APPROVED"
|
||||||
|
assert "Dr New" in await _names(client, auth["mr1"]) # in the list, assigned to the MR who asked
|
||||||
|
assert await _names(client, auth["mr1"], "/doctors/requests") == []
|
||||||
|
|
||||||
|
async def test_only_the_mrs_own_area_manager_or_the_admin_decides(self, client, auth, org):
|
||||||
|
doctor = await _add_doctor(client, auth, org)
|
||||||
|
assert (await client.post(f"{API}/doctors/{doctor['id']}/approve", headers=auth["am2"])).status_code == 403
|
||||||
|
assert (await client.post(f"{API}/doctors/{doctor['id']}/approve", headers=auth["mr1"])).status_code == 403
|
||||||
|
assert (await client.post(f"{API}/doctors/{doctor['id']}/approve", headers=auth["gm"])).status_code == 403
|
||||||
|
assert (await client.post(f"{API}/doctors/{doctor['id']}/approve", headers=auth["admin"])).status_code == 200
|
||||||
|
|
||||||
|
async def test_a_rejection_tells_the_mr_why_and_adding_it_again_resends_it(self, client, auth, org):
|
||||||
|
doctor = await _add_doctor(client, auth, org)
|
||||||
|
rejected = await client.post(f"{API}/doctors/{doctor['id']}/reject", headers=auth["am1"], json={"reason": "Wrong clinic"})
|
||||||
|
assert rejected.status_code == 200
|
||||||
|
mine = (await client.get(f"{API}/doctors/requests", headers=auth["mr1"])).json()
|
||||||
|
assert [(d["approval_status"], d["rejection_reason"]) for d in mine] == [("REJECTED", "Wrong clinic")]
|
||||||
|
assert await _names(client, auth["am1"], "/doctors/requests") == []
|
||||||
|
|
||||||
|
again = await _add_doctor(client, auth, org)
|
||||||
|
assert again["id"] == doctor["id"] and again["approval_status"] == "PENDING" and again["rejection_reason"] is None
|
||||||
|
assert await _names(client, auth["am1"], "/doctors/requests") == ["Dr New"]
|
||||||
|
|
||||||
|
async def test_a_pending_doctor_cannot_be_visited(self, client, auth, org, approved_plan):
|
||||||
|
doctor = await _add_doctor(client, auth, org)
|
||||||
|
await approved_plan()
|
||||||
|
dcr = await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()})
|
||||||
|
assert dcr.status_code == 201, dcr.text
|
||||||
|
visit = await client.post(
|
||||||
|
f"{API}/dcr/{dcr.json()['id']}/calls/doctor", headers=auth["mr1"],
|
||||||
|
json={"doctor_id": doctor["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
|
||||||
|
)
|
||||||
|
assert visit.status_code == 422
|
||||||
|
|
||||||
|
async def test_the_admins_own_doctor_is_approved_at_once(self, client, auth, org):
|
||||||
|
doctor = await _add_doctor(client, auth, org, who="admin")
|
||||||
|
assert doctor["approval_status"] == "APPROVED" and doctor["requested_by_name"] is None
|
||||||
|
|
||||||
|
|
||||||
|
class TestAnMrsChemistWaitsToo:
|
||||||
|
async def test_it_is_pending_until_approved(self, client, auth, org):
|
||||||
|
resp = await client.post(
|
||||||
|
f"{API}/chemists", headers=auth["mr1"],
|
||||||
|
json={"headquarters_id": str(org["hq1"].id), "name": "New Pharmacy", "shop_address": "Shop 2, Bhubaneswar"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 201 and resp.json()["approval_status"] == "PENDING"
|
||||||
|
assert "New Pharmacy" not in await _names(client, auth["mr1"], "/chemists")
|
||||||
|
assert (await client.post(f"{API}/chemists/{resp.json()['id']}/approve", headers=auth["am1"])).status_code == 200
|
||||||
|
assert "New Pharmacy" in await _names(client, auth["mr1"], "/chemists")
|
||||||
|
|
||||||
|
|
||||||
|
class TestGift:
|
||||||
|
async def test_a_doctor_visit_records_the_gift_and_the_pdf_notes_it(self, client, auth, org, approved_plan):
|
||||||
|
doctor = await _add_doctor(client, auth, org, who="admin", name="Dr Gifted")
|
||||||
|
assert (await client.post(f"{API}/doctors/{doctor['id']}/assign", headers=auth["admin"], json={"mr_user_id": str(org["mr1"].id)})).status_code == 201
|
||||||
|
await approved_plan()
|
||||||
|
dcr = (await client.post(f"{API}/dcr", headers=auth["mr1"], json={"report_date": date.today().isoformat()})).json()
|
||||||
|
visit = await client.post(
|
||||||
|
f"{API}/dcr/{dcr['id']}/calls/doctor", headers=auth["mr1"],
|
||||||
|
json={"doctor_id": doctor["id"], "visit_time": "09:30:00", "call_outcome": "MET", "gift": "Diary"},
|
||||||
|
)
|
||||||
|
assert visit.status_code == 201, visit.text
|
||||||
|
calls = (await client.get(f"{API}/dcr/{dcr['id']}", headers=auth["mr1"])).json()["doctor_calls"]
|
||||||
|
assert [c["gift"] for c in calls] == ["Diary"]
|
||||||
|
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
from app.pdf.forms import _doctor_remarks
|
||||||
|
|
||||||
|
call = SimpleNamespace(call_outcome="MET", gift="Diary", remarks="Interested")
|
||||||
|
assert _doctor_remarks(call) == "Gift: Diary. Interested"
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
"""An Area Manager's own Daily Call Report (Self): no plan, no approval, final on submit."""
|
||||||
|
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from tests.e2e.test_full_approval_flow import _create_masters
|
||||||
|
|
||||||
|
API = "/api/v1"
|
||||||
|
TODAY = date.today().isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
async def _self_report(client, auth, **extra):
|
||||||
|
return await client.post(
|
||||||
|
f"{API}/dcr",
|
||||||
|
headers=auth["am1"],
|
||||||
|
json={"report_date": TODAY, "report_type": "SELF", **extra},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestSelfReport:
|
||||||
|
async def test_am_files_and_submits_without_a_plan(self, client, auth, org):
|
||||||
|
doctors, chemists = await _create_masters(client, auth, org, n_doctors=2, n_chemists=1)
|
||||||
|
created = await _self_report(client, auth)
|
||||||
|
assert created.status_code == 201, created.text
|
||||||
|
report = created.json()
|
||||||
|
assert report["report_type"] == "SELF"
|
||||||
|
assert report["headquarters_id"] == str(org["hq1"].id) # the one HQ am1 manages
|
||||||
|
dcr_id = report["id"]
|
||||||
|
|
||||||
|
# Any doctor of the headquarters, though it is assigned to an MR, not to the AM.
|
||||||
|
visit = await client.post(
|
||||||
|
f"{API}/dcr/{dcr_id}/calls/doctor",
|
||||||
|
headers=auth["am1"],
|
||||||
|
json={
|
||||||
|
"doctor_id": doctors[0]["id"],
|
||||||
|
"visit_time": "09:30:00",
|
||||||
|
"call_outcome": "MET",
|
||||||
|
"product_promote": ["Calcium", "Zinc"],
|
||||||
|
"product_sample": ["Iron"],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert visit.status_code == 201, visit.text
|
||||||
|
chem = await client.post(
|
||||||
|
f"{API}/dcr/{dcr_id}/calls/chemist",
|
||||||
|
headers=auth["am1"],
|
||||||
|
json={"chemist_id": chemists[0]["id"], "visit_time": "10:00:00"},
|
||||||
|
)
|
||||||
|
assert chem.status_code == 201, chem.text
|
||||||
|
|
||||||
|
submitted = await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["am1"])
|
||||||
|
assert submitted.status_code == 200, submitted.text
|
||||||
|
assert submitted.json()["status"] == "APPROVED" # final: nobody approves it
|
||||||
|
assert submitted.json()["is_locked"] is True
|
||||||
|
|
||||||
|
locked = await client.patch(
|
||||||
|
f"{API}/dcr/{dcr_id}", headers=auth["am1"], json={"mr_remarks": "x"}
|
||||||
|
)
|
||||||
|
assert locked.status_code == 409
|
||||||
|
pdf = await client.get(f"{API}/dcr/{dcr_id}/pdf", headers=auth["am1"])
|
||||||
|
assert pdf.status_code == 200 and pdf.content.startswith(b"%PDF-")
|
||||||
|
|
||||||
|
async def test_self_list_is_own_and_kept_out_of_the_mr_lists(self, client, auth, org):
|
||||||
|
dcr_id = (await _self_report(client, auth)).json()["id"]
|
||||||
|
own = (await client.get(f"{API}/dcr?type=SELF", headers=auth["am1"])).json()
|
||||||
|
assert [r["id"] for r in own] == [dcr_id]
|
||||||
|
assert (await client.get(f"{API}/dcr?type=SELF", headers=auth["am2"])).json() == []
|
||||||
|
everything = (await client.get(f"{API}/dcr", headers=auth["am1"])).json()
|
||||||
|
assert dcr_id not in {r["id"] for r in everything}
|
||||||
|
counts = (await client.get(f"{API}/dcr/counts", headers=auth["am1"])).json()
|
||||||
|
assert counts["DRAFT"] == 0
|
||||||
|
|
||||||
|
async def test_one_self_report_per_date(self, client, auth, org):
|
||||||
|
assert (await _self_report(client, auth)).status_code == 201
|
||||||
|
assert (await _self_report(client, auth)).status_code == 409
|
||||||
|
|
||||||
|
async def test_needs_a_headquarters_the_am_manages(self, client, auth, org):
|
||||||
|
resp = await _self_report(client, auth, headquarters_id=str(org["hq2"].id))
|
||||||
|
assert resp.status_code == 403
|
||||||
|
|
||||||
|
async def test_only_an_am_files_one_and_an_am_files_no_plan(self, client, auth, org):
|
||||||
|
mr = await client.post(
|
||||||
|
f"{API}/dcr", headers=auth["mr1"], json={"report_date": TODAY, "report_type": "SELF"}
|
||||||
|
)
|
||||||
|
assert mr.status_code == 403
|
||||||
|
plan = await client.post(
|
||||||
|
f"{API}/dcr", headers=auth["am1"], json={"report_date": TODAY, "report_type": "PLAN"}
|
||||||
|
)
|
||||||
|
assert plan.status_code == 403
|
||||||
|
|
||||||
|
async def test_doctor_from_another_headquarters_is_refused(self, client, auth, org):
|
||||||
|
other = await client.post(
|
||||||
|
f"{API}/doctors",
|
||||||
|
headers=auth["admin"],
|
||||||
|
json={
|
||||||
|
"headquarters_id": str(org["hq2"].id),
|
||||||
|
"name": "Dr Far",
|
||||||
|
"clinic_address": "Sambalpur",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
dcr_id = (await _self_report(client, auth)).json()["id"]
|
||||||
|
resp = await client.post(
|
||||||
|
f"{API}/dcr/{dcr_id}/calls/doctor",
|
||||||
|
headers=auth["am1"],
|
||||||
|
json={"doctor_id": other.json()["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
|
||||||
|
)
|
||||||
|
assert resp.status_code == 422
|
||||||
|
|
||||||
|
async def test_nobody_else_can_touch_it(self, client, auth, org):
|
||||||
|
dcr_id = (await _self_report(client, auth)).json()["id"]
|
||||||
|
assert (
|
||||||
|
await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["mr1"])
|
||||||
|
).status_code == 403
|
||||||
|
approve = await client.post(f"{API}/dcr/{dcr_id}/approve", headers=auth["am1"], json={})
|
||||||
|
assert approve.status_code == 409 # a draft cannot be approved; submitting finalises it
|
||||||
|
|
||||||
|
|
||||||
|
class TestGeneralManagerOversight:
|
||||||
|
async def test_gm_sees_every_self_report_read_only(self, client, auth, org):
|
||||||
|
doctors, _ = await _create_masters(client, auth, org, n_doctors=1, n_chemists=0)
|
||||||
|
dcr_id = (await _self_report(client, auth)).json()["id"]
|
||||||
|
await client.post(
|
||||||
|
f"{API}/dcr/{dcr_id}/calls/doctor",
|
||||||
|
headers=auth["am1"],
|
||||||
|
json={"doctor_id": doctors[0]["id"], "visit_time": "09:30:00", "call_outcome": "MET"},
|
||||||
|
)
|
||||||
|
await client.post(f"{API}/dcr/{dcr_id}/submit", headers=auth["am1"])
|
||||||
|
|
||||||
|
listed = (await client.get(f"{API}/dcr?type=SELF", headers=auth["gm"])).json()
|
||||||
|
assert [r["id"] for r in listed] == [dcr_id]
|
||||||
|
assert listed[0]["mr_name"] == org["am1"].full_name
|
||||||
|
assert (await client.get(f"{API}/dcr/{dcr_id}", headers=auth["gm"])).status_code == 200
|
||||||
|
pdf = await client.get(f"{API}/dcr/{dcr_id}/pdf", headers=auth["gm"])
|
||||||
|
assert pdf.status_code == 200
|
||||||
|
|
||||||
|
edit = await client.patch(
|
||||||
|
f"{API}/dcr/{dcr_id}", headers=auth["gm"], json={"mr_remarks": "x"}
|
||||||
|
)
|
||||||
|
assert edit.status_code == 403
|
||||||
|
own = await client.post(
|
||||||
|
f"{API}/dcr", headers=auth["gm"], json={"report_date": TODAY, "report_type": "SELF"}
|
||||||
|
)
|
||||||
|
assert own.status_code == 403
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
"""An Administrator can change another user's role; the old role's assignments end."""
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
|
from app.doctors.models import DoctorAssignment
|
||||||
|
from tests.conftest import DEFAULT_PASSWORD
|
||||||
|
|
||||||
|
API = "/api/v1"
|
||||||
|
|
||||||
|
|
||||||
|
async def _patch(client, auth, user, body, as_="admin"):
|
||||||
|
return await client.patch(f"{API}/users/{user.id}", headers=auth[as_], json=body)
|
||||||
|
|
||||||
|
|
||||||
|
class TestAdminChangesRole:
|
||||||
|
async def test_mr_becomes_am_and_loses_hq_and_doctors(self, client, auth, org, db):
|
||||||
|
doctor = await client.post(
|
||||||
|
f"{API}/doctors",
|
||||||
|
headers=auth["mr1"],
|
||||||
|
json={"headquarters_id": str(org["hq1"].id), "name": "Dr A", "clinic_address": "Puri"},
|
||||||
|
)
|
||||||
|
assert doctor.status_code == 201
|
||||||
|
|
||||||
|
resp = await _patch(client, auth, org["mr1"], {"role": "AM"})
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
assert resp.json()["role"] == "AM"
|
||||||
|
assert resp.json()["headquarters_id"] is None
|
||||||
|
|
||||||
|
# The doctor stays in the headquarters but is no longer assigned to anyone.
|
||||||
|
active = await db.execute(
|
||||||
|
select(DoctorAssignment).where(
|
||||||
|
DoctorAssignment.doctor_id == uuid.UUID(doctor.json()["id"]),
|
||||||
|
DoctorAssignment.effective_to.is_(None),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assert active.scalars().first() is None
|
||||||
|
|
||||||
|
async def test_am_becomes_mr_and_releases_headquarters(self, client, auth, org):
|
||||||
|
resp = await _patch(
|
||||||
|
client, auth, org["am1"], {"role": "MR", "headquarters_id": str(org["hq2"].id)}
|
||||||
|
)
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
assert resp.json()["headquarters_id"] == str(org["hq2"].id)
|
||||||
|
|
||||||
|
mappings = await client.get(f"{API}/headquarters/area-managers", headers=auth["admin"])
|
||||||
|
assert str(org["am1"].id) not in {m["area_manager_user_id"] for m in mappings.json()}
|
||||||
|
|
||||||
|
async def test_gm_becomes_am(self, client, auth, org):
|
||||||
|
resp = await _patch(client, auth, org["gm"], {"role": "AM"})
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
assert resp.json()["role"] == "AM"
|
||||||
|
|
||||||
|
async def test_role_change_signs_the_user_out(self, client, auth, org):
|
||||||
|
login = await client.post(
|
||||||
|
f"{API}/auth/login",
|
||||||
|
json={"email": org["gm"].email, "password": DEFAULT_PASSWORD},
|
||||||
|
)
|
||||||
|
await _patch(client, auth, org["gm"], {"role": "AM"})
|
||||||
|
again = await client.post(
|
||||||
|
f"{API}/auth/refresh", json={"refresh_token": login.json()["refresh_token"]}
|
||||||
|
)
|
||||||
|
assert again.status_code == 401
|
||||||
|
|
||||||
|
async def test_becoming_mr_needs_a_headquarters(self, client, auth, org):
|
||||||
|
resp = await _patch(client, auth, org["gm"], {"role": "MR"})
|
||||||
|
assert resp.status_code == 422
|
||||||
|
|
||||||
|
async def test_admin_cannot_change_own_role(self, client, auth, org):
|
||||||
|
resp = await _patch(client, auth, org["admin"], {"role": "GM"})
|
||||||
|
assert resp.status_code == 422
|
||||||
|
|
||||||
|
async def test_only_admin_can_change_a_role(self, client, auth, org):
|
||||||
|
resp = await _patch(client, auth, org["mr1"], {"role": "AM"}, as_="gm")
|
||||||
|
assert resp.status_code == 403
|
||||||
@@ -11,6 +11,7 @@ from zoneinfo import ZoneInfo
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
from app.common.enums import ReportType
|
||||||
from app.common.exceptions import ValidationError
|
from app.common.exceptions import ValidationError
|
||||||
from app.reports import service as svc
|
from app.reports import service as svc
|
||||||
|
|
||||||
@@ -36,7 +37,7 @@ def _service() -> svc.DCRService:
|
|||||||
|
|
||||||
|
|
||||||
def _report(day: date) -> SimpleNamespace:
|
def _report(day: date) -> SimpleNamespace:
|
||||||
return SimpleNamespace(report_date=day)
|
return SimpleNamespace(report_date=day, report_type=ReportType.ACTUAL)
|
||||||
|
|
||||||
|
|
||||||
class TestVisitTime:
|
class TestVisitTime:
|
||||||
@@ -57,12 +58,19 @@ class TestVisitTime:
|
|||||||
class TestReportDate:
|
class TestReportDate:
|
||||||
def test_today_is_todays_ist_date_just_after_midnight(self, at):
|
def test_today_is_todays_ist_date_just_after_midnight(self, at):
|
||||||
at(2026, 9, 21, 1, 0) # still 20 Sep in UTC
|
at(2026, 9, 21, 1, 0) # still 20 Sep in UTC
|
||||||
_service()._validate_report_date(date(2026, 9, 21))
|
_service()._validate_report_date(date(2026, 9, 21), ReportType.ACTUAL)
|
||||||
|
|
||||||
def test_tomorrow_is_rejected(self, at):
|
def test_tomorrow_is_rejected_for_a_done_or_self_report(self, at):
|
||||||
at(2026, 9, 21, 1, 0)
|
at(2026, 9, 21, 1, 0)
|
||||||
|
for report_type in (ReportType.ACTUAL, ReportType.SELF):
|
||||||
with pytest.raises(ValidationError):
|
with pytest.raises(ValidationError):
|
||||||
_service()._validate_report_date(date(2026, 9, 22))
|
_service()._validate_report_date(date(2026, 9, 22), report_type)
|
||||||
|
|
||||||
|
def test_a_plan_may_be_made_up_to_two_days_ahead(self, at):
|
||||||
|
at(2026, 9, 21, 1, 0)
|
||||||
|
_service()._validate_report_date(date(2026, 9, 23), ReportType.PLAN)
|
||||||
|
with pytest.raises(ValidationError):
|
||||||
|
_service()._validate_report_date(date(2026, 9, 24), ReportType.PLAN)
|
||||||
|
|
||||||
|
|
||||||
def test_local_helpers_use_the_configured_timezone():
|
def test_local_helpers_use_the_configured_timezone():
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ async def test_am_can_list_only_approval_csv_tables_and_download_approval_pdf(cl
|
|||||||
resp = await client.get(f"{API}/csv-data/tables", headers=auth["am1"])
|
resp = await client.get(f"{API}/csv-data/tables", headers=auth["am1"])
|
||||||
assert resp.status_code == 200, resp.text
|
assert resp.status_code == 200, resp.text
|
||||||
table_names = {item["name"] for item in resp.json()}
|
table_names = {item["name"] for item in resp.json()}
|
||||||
assert table_names == {"standard_tour_plan", "tour_plan", "fare_chart"}
|
assert table_names == {"standard_tour_plan", "tour_plan", "fare_chart", "expense_statement"}
|
||||||
assert "daily_call_report_csv" not in table_names
|
assert "daily_call_report_csv" not in table_names
|
||||||
|
|
||||||
pdf = await client.get(f"{API}/csv-data/fare_chart/pdf", headers=auth["am1"])
|
pdf = await client.get(f"{API}/csv-data/fare_chart/pdf", headers=auth["am1"])
|
||||||
|
|||||||
@@ -45,8 +45,8 @@ def test_identity_is_gathered_from_all_rows_not_just_the_first():
|
|||||||
PRINTED_HEADERS = {
|
PRINTED_HEADERS = {
|
||||||
"tour_plan": ["Sl.No.", "Date", "From", "To", "POB", "Stockiest Visit"],
|
"tour_plan": ["Sl.No.", "Date", "From", "To", "POB", "Stockiest Visit"],
|
||||||
"standard_tour_plan": ["Sl.No.", "PLACE"],
|
"standard_tour_plan": ["Sl.No.", "PLACE"],
|
||||||
"fare_chart": ["Sl.No.", "Date", "From", "To", "Kilometers (KM)"],
|
"fare_chart": ["Sl.No.", "Date", "From", "To", "Kilometers (KM)\n(One Way)"],
|
||||||
"area_covered": ["SALE STATUS", "AREA TO COVER", "SALE OBJECTIVE", "STATUS"],
|
"area_covered": ["AREA TO COVER", "SALE OBJECTIVE", "STATUS"],
|
||||||
"core_dr_call_conversion": ["DOCTOR NAME", "DATE OF VISIT", "PRODUCT TARGETED", "STATUS"],
|
"core_dr_call_conversion": ["DOCTOR NAME", "DATE OF VISIT", "PRODUCT TARGETED", "STATUS"],
|
||||||
"field_activity_report": [
|
"field_activity_report": [
|
||||||
"DATE",
|
"DATE",
|
||||||
@@ -57,21 +57,19 @@ PRINTED_HEADERS = {
|
|||||||
"sales_and_stock_statement": [
|
"sales_and_stock_statement": [
|
||||||
"Sl.No.",
|
"Sl.No.",
|
||||||
"Name of the Product",
|
"Name of the Product",
|
||||||
|
"Value in PTS",
|
||||||
"Opening",
|
"Opening",
|
||||||
"Receipt",
|
"Receipt",
|
||||||
"Sale",
|
"Sale",
|
||||||
"Closing",
|
"Closing",
|
||||||
"Value in PTS",
|
|
||||||
],
|
],
|
||||||
"sales_projection": [
|
"sales_projection": [
|
||||||
"SL. No.",
|
"SL. No.",
|
||||||
"NAME OF THE PRODUCT",
|
"NAME OF THE PRODUCT",
|
||||||
"PTS",
|
"PTS",
|
||||||
"SEC. QTY",
|
"QUANTITY",
|
||||||
"VALUE",
|
"VALUE",
|
||||||
"CLOSING",
|
"QUANTITY",
|
||||||
"SEC. VALUE",
|
|
||||||
"SALES",
|
|
||||||
"VALUE",
|
"VALUE",
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
@@ -120,10 +118,10 @@ def test_blank_lines_carry_on_numbering_and_tour_plan_numbers_have_a_dot():
|
|||||||
def test_product_lists_print_in_their_own_columns():
|
def test_product_lists_print_in_their_own_columns():
|
||||||
rows = _rows("sales_projection", 2)
|
rows = _rows("sales_projection", 2)
|
||||||
rows[0].update(product_name="INTEZOLE-PD", pts="106.92")
|
rows[0].update(product_name="INTEZOLE-PD", pts="106.92")
|
||||||
rows[1].update(product_name="INTEZOLE-RD", pts="93.59", secondary_qty="4")
|
rows[1].update(product_name="INTEZOLE-RD", pts="93.59", closing_qty="4", projection_value="250")
|
||||||
cells = [r["cells"] for r in _ctx("sales_projection", rows)["grids"]["main"]["rows"][:2]]
|
cells = [r["cells"] for r in _ctx("sales_projection", rows)["grids"]["main"]["rows"][:2]]
|
||||||
assert cells[0][:3] == ["1", "INTEZOLE-PD", "106.92"]
|
assert cells[0][:3] == ["1", "INTEZOLE-PD", "106.92"]
|
||||||
assert cells[1][:4] == ["2", "INTEZOLE-RD", "93.59", "4"]
|
assert cells[1] == ["2", "INTEZOLE-RD", "93.59", "4", "", "", "250"]
|
||||||
|
|
||||||
|
|
||||||
def test_printing_every_month_together_renumbers_instead_of_repeating():
|
def test_printing_every_month_together_renumbers_instead_of_repeating():
|
||||||
@@ -140,11 +138,11 @@ def test_printing_every_month_together_renumbers_instead_of_repeating():
|
|||||||
assert [r["cells"][0] for r in body[:2]] == ["1", "1"]
|
assert [r["cells"][0] for r in body[:2]] == ["1", "1"]
|
||||||
|
|
||||||
|
|
||||||
def test_sales_projection_sales_column_names_the_actual_month():
|
def test_sales_projection_groups_closing_and_projection_under_their_own_headings():
|
||||||
rows = _rows("sales_projection", 2, month="September")
|
from app.pdf.service import _env
|
||||||
assert _ctx("sales_projection", rows)["grids"]["main"]["headers"][7] == "SEP. SALES"
|
|
||||||
# No month on any row (e.g. a blank template): a generic label, never a hardcoded month.
|
html = _env.get_template("forms/sales_projection.html").render(**_ctx("sales_projection", _rows("sales_projection", 1)))
|
||||||
assert _ctx("sales_projection", _rows("sales_projection", 2))["grids"]["main"]["headers"][7] == "SALES"
|
assert '<th colspan="2">CLOSING</th>' in html and '<th colspan="2">PROJECTION</th>' in html
|
||||||
|
|
||||||
|
|
||||||
def test_no_form_prints_dashboard_extras():
|
def test_no_form_prints_dashboard_extras():
|
||||||
@@ -224,3 +222,19 @@ def test_plain_text_fallback_keeps_the_form_content_readable():
|
|||||||
text = _html_to_text(_env.get_template("forms/fare_chart.html").render(**ctx))
|
text = _html_to_text(_env.get_template("forms/fare_chart.html").render(**ctx))
|
||||||
assert "Puri" in text and "APPROVAL SIGNATURE: Meera" in text and "<" not in text
|
assert "Puri" in text and "APPROVAL SIGNATURE: Meera" in text and "<" not in text
|
||||||
assert _minimal_pdf(text).startswith(b"%PDF")
|
assert _minimal_pdf(text).startswith(b"%PDF")
|
||||||
|
|
||||||
|
|
||||||
|
def test_expense_statement_splits_rupees_and_paise_and_totals_every_column():
|
||||||
|
rows = _rows("expense_statement", 2, from_location="BBSR")
|
||||||
|
rows[0].update(report_date="2026-10-03", fare="120.5", da_ex="150", other_expense="20")
|
||||||
|
rows[1].update(report_date="2026-10-01", da_hq="100", postage="15.75", total="999") # a stale total is ignored
|
||||||
|
ctx = _ctx("expense_statement", rows, approval_status="approved", am_name="Anita Das")
|
||||||
|
body = ctx["grids"]["main"]["rows"]
|
||||||
|
assert len(body) == 27
|
||||||
|
assert body[0]["cells"][4:9] == ["120", "50", "", "150", ""]
|
||||||
|
assert body[0]["cells"][13:15] == ["290", "50"]
|
||||||
|
assert body[1]["cells"][13:15] == ["115", "75"]
|
||||||
|
assert ctx["sums"]["total_rs"] == "406" and ctx["sums"]["total_p"] == "25"
|
||||||
|
assert ctx["sums"]["claimed"] == "406.25"
|
||||||
|
assert (ctx["period_from"], ctx["period_to"]) == ("01/10/2026", "03/10/2026")
|
||||||
|
assert ctx["approval"]["value"] == "Anita Das"
|
||||||
|
|||||||
+19
-6
@@ -10,6 +10,7 @@ import { NotFoundPage } from "./pages/NotFoundPage";
|
|||||||
import { ProductsPage } from "./pages/ProductsPage";
|
import { ProductsPage } from "./pages/ProductsPage";
|
||||||
import { ProfilePage } from "./pages/ProfilePage";
|
import { ProfilePage } from "./pages/ProfilePage";
|
||||||
import { AdminPage } from "./pages/admin/AdminPage";
|
import { AdminPage } from "./pages/admin/AdminPage";
|
||||||
|
import { UserDetailPage } from "./pages/admin/UserDetailPage";
|
||||||
import { UsersPage } from "./pages/admin/UsersPage";
|
import { UsersPage } from "./pages/admin/UsersPage";
|
||||||
import { FormsPage } from "./pages/forms/FormsPage";
|
import { FormsPage } from "./pages/forms/FormsPage";
|
||||||
import { NewReportPage } from "./pages/reports/NewReportPage";
|
import { NewReportPage } from "./pages/reports/NewReportPage";
|
||||||
@@ -20,16 +21,28 @@ import type { Role } from "./types";
|
|||||||
/** Which roles may open which screens; anything else renders "not found". */
|
/** Which roles may open which screens; anything else renders "not found". */
|
||||||
const ROUTES: { pattern: string; roles?: Role[]; render: (params: Record<string, string>) => JSX.Element }[] = [
|
const ROUTES: { pattern: string; roles?: Role[]; render: (params: Record<string, string>) => JSX.Element }[] = [
|
||||||
{ pattern: "/", render: () => <DashboardPage /> },
|
{ pattern: "/", render: () => <DashboardPage /> },
|
||||||
{ pattern: "/reports", roles: ["MR", "AM", "GM"], render: () => <ReportsPage /> },
|
// Daily Call Report (Plan) and (Done) each have their own list, new-report form and report pages.
|
||||||
{ pattern: "/reports/new", roles: ["MR"], render: () => <NewReportPage /> },
|
{ pattern: "/reports", roles: ["MR", "SFE", "AM", "GM"], render: () => <ReportsPage type="PLAN" key="PLAN" /> },
|
||||||
{ pattern: "/reports/:id", roles: ["MR", "AM", "GM"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
|
{ pattern: "/reports/plan", roles: ["MR", "SFE", "AM", "GM"], render: () => <ReportsPage type="PLAN" key="PLAN" /> },
|
||||||
|
{ pattern: "/reports/done", roles: ["MR", "SFE", "AM", "GM"], render: () => <ReportsPage type="ACTUAL" key="ACTUAL" /> },
|
||||||
|
{ pattern: "/reports/plan/new", roles: ["MR", "SFE"], render: () => <NewReportPage type="PLAN" key="PLAN" /> },
|
||||||
|
{ pattern: "/reports/done/new", roles: ["MR", "SFE"], render: () => <NewReportPage type="ACTUAL" key="ACTUAL" /> },
|
||||||
|
{ pattern: "/reports/plan/:id", roles: ["MR", "SFE", "AM", "GM"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
|
||||||
|
{ pattern: "/reports/done/:id", roles: ["MR", "SFE", "AM", "GM"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
|
||||||
|
{ pattern: "/reports/self", roles: ["AM", "GM"], render: () => <ReportsPage type="SELF" key="SELF" /> },
|
||||||
|
{ pattern: "/reports/self/new", roles: ["AM"], render: () => <NewReportPage type="SELF" key="SELF" /> },
|
||||||
|
{ pattern: "/reports/self/:id", roles: ["AM", "GM"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
|
||||||
|
// Links from before the split.
|
||||||
|
{ pattern: "/reports/new", roles: ["MR", "SFE"], render: () => <NewReportPage type="PLAN" key="PLAN" /> },
|
||||||
|
{ pattern: "/reports/:id", roles: ["MR", "SFE", "AM", "GM"], render: (p) => <ReportDetailPage id={p.id!} key={p.id} /> },
|
||||||
{ pattern: "/directory", render: () => <DirectoryPage /> },
|
{ pattern: "/directory", render: () => <DirectoryPage /> },
|
||||||
{ pattern: "/products", render: () => <ProductsPage /> },
|
{ pattern: "/products", render: () => <ProductsPage /> },
|
||||||
{ pattern: "/forms", roles: ["MR", "AM", "ADMIN"], render: () => <FormsPage /> },
|
{ pattern: "/forms", roles: ["MR", "SFE", "AM", "GM", "ADMIN"], render: () => <FormsPage /> },
|
||||||
{ pattern: "/forms/:table", roles: ["MR", "AM", "ADMIN"], render: (p) => <FormsPage table={p.table} /> },
|
{ pattern: "/forms/:table", roles: ["MR", "SFE", "AM", "GM", "ADMIN"], render: (p) => <FormsPage table={p.table} /> },
|
||||||
{ pattern: "/profile", render: () => <ProfilePage /> },
|
{ pattern: "/profile", render: () => <ProfilePage /> },
|
||||||
{ pattern: "/admin", roles: ["ADMIN"], render: () => <AdminPage /> },
|
{ pattern: "/admin", roles: ["ADMIN", "MR", "SFE"], render: () => <AdminPage /> },
|
||||||
{ pattern: "/users", roles: ["ADMIN", "GM"], render: () => <UsersPage /> },
|
{ pattern: "/users", roles: ["ADMIN", "GM"], render: () => <UsersPage /> },
|
||||||
|
{ pattern: "/users/:id", roles: ["ADMIN", "GM"], render: (p) => <UserDetailPage id={p.id!} key={p.id} /> },
|
||||||
];
|
];
|
||||||
|
|
||||||
function Routes({ role }: { role: Role }) {
|
function Routes({ role }: { role: Role }) {
|
||||||
|
|||||||
+14
-3
@@ -1,6 +1,6 @@
|
|||||||
import type {
|
import type {
|
||||||
Approval, AreaManagerMapping, Chemist, CsvRow, CsvTable, Dcr, DcrListItem, Doctor, FormOwner, Headquarters,
|
Approval, AreaManagerMapping, Chemist, CsvRow, CsvTable, Dcr, DcrListItem, Doctor, FormOwner, Headquarters,
|
||||||
FormApproval, Product, Profile, StatusCounts, StockInventory, User,
|
FormApproval, Product, Profile, UserOverview, ReportType, StatusCounts, StockInventory, User,
|
||||||
} from "../types";
|
} from "../types";
|
||||||
import { API_BASE, auth, download, json, request } from "./client";
|
import { API_BASE, auth, download, json, request } from "./client";
|
||||||
|
|
||||||
@@ -24,14 +24,19 @@ export const api = {
|
|||||||
profile: () => request<Profile>("/users/me/profile"),
|
profile: () => request<Profile>("/users/me/profile"),
|
||||||
|
|
||||||
// daily call reports
|
// daily call reports
|
||||||
reports: () => request<DcrListItem[]>("/dcr?limit=200"),
|
/** `type` limits the list to Daily Call Report (Plan) or (Done); omitted, both. */
|
||||||
counts: () => request<StatusCounts>("/dcr/counts"),
|
/** `headquartersId` narrows a manager's list to one of their headquarters. */
|
||||||
|
reports: (type?: ReportType, headquartersId?: string) => request<DcrListItem[]>(`/dcr${query({ limit: "200", type, headquarters_id: headquartersId })}`),
|
||||||
|
counts: (headquartersId?: string) => request<StatusCounts>(`/dcr/counts${query({ headquarters_id: headquartersId })}`),
|
||||||
report: (id: string) => request<Dcr>(`/dcr/${id}`),
|
report: (id: string) => request<Dcr>(`/dcr/${id}`),
|
||||||
createReport: (payload: Payload) => request<Dcr>("/dcr", json("POST", payload)),
|
createReport: (payload: Payload) => request<Dcr>("/dcr", json("POST", payload)),
|
||||||
updateReport: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}`, json("PATCH", payload)),
|
updateReport: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}`, json("PATCH", payload)),
|
||||||
addDoctorCall: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}/calls/doctor`, json("POST", payload)),
|
addDoctorCall: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}/calls/doctor`, json("POST", payload)),
|
||||||
addChemistCall: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}/calls/chemist`, json("POST", payload)),
|
addChemistCall: (id: string, payload: Payload) => request<Dcr>(`/dcr/${id}/calls/chemist`, json("POST", payload)),
|
||||||
deleteCall: (id: string, callId: string) => request<Dcr>(`/dcr/${id}/calls/${callId}`, json("DELETE")),
|
deleteCall: (id: string, callId: string) => request<Dcr>(`/dcr/${id}/calls/${callId}`, json("DELETE")),
|
||||||
|
/** End-of-day report: why a planned doctor/chemist (`target` holds doctor_id or chemist_id) was not visited. */
|
||||||
|
setMissedReason: (id: string, target: Payload, reason: string) => request<Dcr>(`/dcr/${id}/missed`, json("PUT", { ...target, reason })),
|
||||||
|
clearMissedReason: (id: string, missedId: string) => request<Dcr>(`/dcr/${id}/missed/${missedId}`, json("DELETE")),
|
||||||
submit: (id: string) => request<Dcr>(`/dcr/${id}/submit`, json("POST")),
|
submit: (id: string) => request<Dcr>(`/dcr/${id}/submit`, json("POST")),
|
||||||
returnReport: (id: string, reason: string) => request<Dcr>(`/dcr/${id}/return`, json("POST", { reason })),
|
returnReport: (id: string, reason: string) => request<Dcr>(`/dcr/${id}/return`, json("POST", { reason })),
|
||||||
approve: (id: string, comment: string) => request<Dcr>(`/dcr/${id}/approve`, json("POST", { comment: comment || null })),
|
approve: (id: string, comment: string) => request<Dcr>(`/dcr/${id}/approve`, json("POST", { comment: comment || null })),
|
||||||
@@ -41,8 +46,14 @@ export const api = {
|
|||||||
// masters and organisation
|
// masters and organisation
|
||||||
doctors: () => request<Doctor[]>("/doctors"),
|
doctors: () => request<Doctor[]>("/doctors"),
|
||||||
chemists: () => request<Chemist[]>("/chemists"),
|
chemists: () => request<Chemist[]>("/chemists"),
|
||||||
|
/** Doctors / chemists added by an MR that wait for (or were refused by) the Area Manager. */
|
||||||
|
doctorRequests: () => request<Doctor[]>("/doctors/requests"),
|
||||||
|
chemistRequests: () => request<Chemist[]>("/chemists/requests"),
|
||||||
|
reviewMaster: (kind: "doctor" | "chemist", id: string, approve: boolean, reason?: string) =>
|
||||||
|
request<Doctor | Chemist>(`/${kind}s/${id}/${approve ? "approve" : "reject"}`, json("POST", approve ? undefined : { reason })),
|
||||||
headquarters: () => request<Headquarters[]>("/headquarters"),
|
headquarters: () => request<Headquarters[]>("/headquarters"),
|
||||||
users: () => request<User[]>("/users"),
|
users: () => request<User[]>("/users"),
|
||||||
|
userOverview: (id: string) => request<UserOverview>(`/users/${id}/overview`),
|
||||||
areaManagerMappings: () => request<AreaManagerMapping[]>("/headquarters/area-managers"),
|
areaManagerMappings: () => request<AreaManagerMapping[]>("/headquarters/area-managers"),
|
||||||
setAreaManagerHeadquarters: (areaManagerId: string, headquarters_ids: string[]) =>
|
setAreaManagerHeadquarters: (areaManagerId: string, headquarters_ids: string[]) =>
|
||||||
request<AreaManagerMapping[]>(`/headquarters/area-managers/${areaManagerId}`, json("PUT", { headquarters_ids })),
|
request<AreaManagerMapping[]>(`/headquarters/area-managers/${areaManagerId}`, json("PUT", { headquarters_ids })),
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { Headquarters } from "../../types";
|
import type { Headquarters } from "../../types";
|
||||||
|
|
||||||
/** Pick any number of headquarters. `owners` shows who manages each one today. */
|
/** Pick any number of headquarters. `owners` shows who else manages each one today (a headquarters may have several). */
|
||||||
export function HeadquartersChecklist({ headquarters, selected, onChange, owners = {}, disabled = false }: {
|
export function HeadquartersChecklist({ headquarters, selected, onChange, owners = {}, disabled = false }: {
|
||||||
headquarters: Headquarters[];
|
headquarters: Headquarters[];
|
||||||
selected: ReadonlySet<string>;
|
selected: ReadonlySet<string>;
|
||||||
@@ -21,7 +21,7 @@ export function HeadquartersChecklist({ headquarters, selected, onChange, owners
|
|||||||
<input type="checkbox" checked={selected.has(h.id)} disabled={disabled} onChange={() => toggle(h.id)} />
|
<input type="checkbox" checked={selected.has(h.id)} disabled={disabled} onChange={() => toggle(h.id)} />
|
||||||
<span className="hq-check-text">
|
<span className="hq-check-text">
|
||||||
<strong>{h.code}</strong> · {h.name}
|
<strong>{h.code}</strong> · {h.name}
|
||||||
{owners[h.id] && <small>Managed by {owners[h.id]}</small>}
|
{owners[h.id] && <small>Area Manager: {owners[h.id]}</small>}
|
||||||
</span>
|
</span>
|
||||||
</label>
|
</label>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { Badge } from "../ui/Badge";
|
||||||
|
import { Button } from "../ui/Button";
|
||||||
|
import { Card, CardBody, CardHeader } from "../ui/Card";
|
||||||
|
import { DataTable, type Column } from "../ui/DataTable";
|
||||||
|
import { Field, Textarea } from "../ui/Field";
|
||||||
|
import { Modal } from "../ui/Modal";
|
||||||
|
import { ErrorState } from "../ui/States";
|
||||||
|
import { useToast } from "../ui/Toast";
|
||||||
|
import { LIVE, useAsync } from "../../hooks/useAsync";
|
||||||
|
import { api } from "../../api";
|
||||||
|
import { errorMessage, formatDate } from "../../lib/format";
|
||||||
|
import { useUser } from "../../lib/session";
|
||||||
|
import type { Chemist, Doctor } from "../../types";
|
||||||
|
|
||||||
|
type Request = { kind: "doctor" | "chemist"; item: Doctor | Chemist };
|
||||||
|
|
||||||
|
const address = (r: Request) => (r.kind === "doctor" ? (r.item as Doctor).clinic_address : (r.item as Chemist).shop_address);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Doctors and chemists an MR added that wait for the Area Manager.
|
||||||
|
* `mine`: the MR's own requests, with any rejection and its reason.
|
||||||
|
* `review`: what waits for this Area Manager (or the admin) to approve or reject; the GM only looks.
|
||||||
|
* Shows nothing when there is nothing to show.
|
||||||
|
*/
|
||||||
|
export function MasterRequests({ mode, onReviewed }: { mode: "mine" | "review"; onReviewed?: () => void }) {
|
||||||
|
const user = useUser();
|
||||||
|
const toast = useToast();
|
||||||
|
const canAct = mode === "review" && (user.role === "AM" || user.role === "ADMIN");
|
||||||
|
const data = useAsync(async () => {
|
||||||
|
const [doctors, chemists] = await Promise.all([api.doctorRequests(), api.chemistRequests()]);
|
||||||
|
return [...doctors.map((item) => ({ kind: "doctor" as const, item })), ...chemists.map((item) => ({ kind: "chemist" as const, item }))]
|
||||||
|
.sort((a, b) => b.item.created_at.localeCompare(a.item.created_at));
|
||||||
|
}, [], { poll: LIVE });
|
||||||
|
const [acting, setActing] = useState<string | null>(null);
|
||||||
|
const [rejecting, setRejecting] = useState<Request | null>(null);
|
||||||
|
const [reason, setReason] = useState("");
|
||||||
|
const [reasonError, setReasonError] = useState<string | null>(null);
|
||||||
|
const rows = data.data ?? [];
|
||||||
|
|
||||||
|
async function decide(r: Request, approve: boolean, why?: string) {
|
||||||
|
setActing(r.item.id);
|
||||||
|
try {
|
||||||
|
await api.reviewMaster(r.kind, r.item.id, approve, why);
|
||||||
|
toast.success(approve ? `${r.item.name} approved and added to the list` : `${r.item.name} rejected`);
|
||||||
|
setRejecting(null);
|
||||||
|
await data.reload();
|
||||||
|
onReviewed?.();
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(errorMessage(e, approve ? "Could not approve" : "Could not reject"));
|
||||||
|
} finally {
|
||||||
|
setActing(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.error) return <Card><ErrorState message={data.error} onRetry={() => void data.reload()} /></Card>;
|
||||||
|
if (rows.length === 0) return null;
|
||||||
|
|
||||||
|
const columns: Column<Request>[] = [
|
||||||
|
{ key: "kind", header: "Type", render: (r) => <Badge tone="brand">{r.kind === "doctor" ? "Doctor" : "Chemist"}</Badge>, nowrap: true },
|
||||||
|
{ key: "name", header: "Name", render: (r) => <strong>{r.item.name}</strong> },
|
||||||
|
{ key: "address", header: "Address", render: address },
|
||||||
|
...(mode === "review" ? [{ key: "by", header: "Added by", render: (r: Request) => r.item.requested_by_name ?? "—", nowrap: true }] : []),
|
||||||
|
{ key: "on", header: "Added on", render: (r) => formatDate(r.item.created_at), nowrap: true },
|
||||||
|
mode === "mine"
|
||||||
|
? {
|
||||||
|
key: "status", header: "Status",
|
||||||
|
render: (r) => r.item.approval_status === "REJECTED"
|
||||||
|
? <span><Badge tone="danger" dot>Rejected</Badge>{r.item.rejection_reason && <span className="muted"> — {r.item.rejection_reason}</span>}</span>
|
||||||
|
: <Badge tone="warning" dot>Waiting for Area Manager</Badge>,
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
key: "_actions", header: "", align: "right", nowrap: true,
|
||||||
|
render: (r) => canAct ? (
|
||||||
|
<span className="row-actions">
|
||||||
|
<Button size="sm" variant="primary" icon="check" loading={acting === r.item.id} onClick={() => void decide(r, true)}>Approve</Button>
|
||||||
|
<Button size="sm" variant="ghost" disabled={acting === r.item.id} onClick={() => { setRejecting(r); setReason(""); setReasonError(null); }}>Reject</Button>
|
||||||
|
</span>
|
||||||
|
) : <Badge tone="warning" dot>Waiting for Area Manager</Badge>,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const pending = rows.filter((r) => r.item.approval_status === "PENDING").length;
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Card>
|
||||||
|
<CardHeader
|
||||||
|
title={mode === "mine" ? "Your requests" : "Waiting for approval"}
|
||||||
|
description={mode === "mine"
|
||||||
|
? "Doctors and chemists you added. Each joins your list once your Area Manager approves it. To re-send a rejected one, add it again with the corrected details."
|
||||||
|
: `${pending} new doctor${pending === 1 ? "" : "s"} or chemist${pending === 1 ? "" : "s"} added by MRs. Once approved, each joins the list and is assigned to the MR who added it.`}
|
||||||
|
/>
|
||||||
|
<CardBody flush>
|
||||||
|
<DataTable columns={columns} rows={rows} rowKey={(r) => `${r.kind}-${r.item.id}`} loading={data.loading} minWidth={720} />
|
||||||
|
</CardBody>
|
||||||
|
</Card>
|
||||||
|
<Modal
|
||||||
|
open={!!rejecting}
|
||||||
|
title={`Reject ${rejecting?.item.name ?? ""}?`}
|
||||||
|
description="The MR sees your reason and can add it again with corrected details."
|
||||||
|
onClose={() => setRejecting(null)}
|
||||||
|
footer={<><Button onClick={() => setRejecting(null)}>Cancel</Button><Button variant="danger" loading={!!rejecting && acting === rejecting.item.id} onClick={() => {
|
||||||
|
const why = reason.trim();
|
||||||
|
if (why.length < 3) { setReasonError("Give a reason (at least 3 characters)"); return; }
|
||||||
|
if (rejecting) void decide(rejecting, false, why);
|
||||||
|
}}>Reject</Button></>}
|
||||||
|
>
|
||||||
|
<Field label="Reason" required error={reasonError ?? undefined} hint={`${reason.length}/500`}>
|
||||||
|
<Textarea value={reason} maxLength={500} rows={3} onChange={(e) => { setReason(e.target.value); setReasonError(null); }} placeholder="e.g. Wrong clinic address, or this doctor is already in the list" />
|
||||||
|
</Field>
|
||||||
|
</Modal>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
import { Icon } from "../ui/Icon";
|
import { Icon } from "../ui/Icon";
|
||||||
|
import { LIVE, useAsync } from "../../hooks/useAsync";
|
||||||
|
import { api } from "../../api";
|
||||||
import { Link } from "../../lib/router";
|
import { Link } from "../../lib/router";
|
||||||
import { navigationFor } from "../../lib/navigation";
|
import { navigationFor } from "../../lib/navigation";
|
||||||
import type { Role } from "../../types";
|
import type { Role } from "../../types";
|
||||||
@@ -9,6 +11,12 @@ export function Sidebar({ role, path, collapsed, mobileOpen, onToggleCollapsed,
|
|||||||
role: Role; path: string; collapsed: boolean; mobileOpen: boolean;
|
role: Role; path: string; collapsed: boolean; mobileOpen: boolean;
|
||||||
onToggleCollapsed: () => void; onNavigate: () => void;
|
onToggleCollapsed: () => void; onNavigate: () => void;
|
||||||
}) {
|
}) {
|
||||||
|
// An Area Manager is told how many new doctors / chemists wait for their approval.
|
||||||
|
const waiting = useAsync(
|
||||||
|
async () => (role === "AM" ? (await Promise.all([api.doctorRequests(), api.chemistRequests()])).reduce((n, list) => n + list.length, 0) : 0),
|
||||||
|
[role], { poll: LIVE },
|
||||||
|
);
|
||||||
|
const flags: Record<string, number> = { "/directory": waiting.data ?? 0 };
|
||||||
return (
|
return (
|
||||||
<aside className={`sidebar${collapsed ? " collapsed" : ""}${mobileOpen ? " open" : ""}`} aria-label="Primary">
|
<aside className={`sidebar${collapsed ? " collapsed" : ""}${mobileOpen ? " open" : ""}`} aria-label="Primary">
|
||||||
<Link to="/" className="sidebar-brand" onClick={onNavigate} aria-label="Celtic Life Science — home">
|
<Link to="/" className="sidebar-brand" onClick={onNavigate} aria-label="Celtic Life Science — home">
|
||||||
@@ -29,6 +37,7 @@ export function Sidebar({ role, path, collapsed, mobileOpen, onToggleCollapsed,
|
|||||||
>
|
>
|
||||||
<Icon name={item.icon} />
|
<Icon name={item.icon} />
|
||||||
<span>{item.label}</span>
|
<span>{item.label}</span>
|
||||||
|
{!collapsed && (flags[item.to] ?? 0) > 0 && <span className="nav-flag" title="Waiting for your approval">{flags[item.to]}</span>}
|
||||||
</Link>
|
</Link>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,16 +1,20 @@
|
|||||||
import { type FormEvent, useState } from "react";
|
import { type FormEvent, useEffect, useRef, useState } from "react";
|
||||||
import { Alert } from "../ui/Alert";
|
import { Alert } from "../ui/Alert";
|
||||||
import { Button } from "../ui/Button";
|
import { Button } from "../ui/Button";
|
||||||
import { Field, Input, Select, Textarea } from "../ui/Field";
|
import { Field, Input, Select, Textarea } from "../ui/Field";
|
||||||
import { useToast } from "../ui/Toast";
|
import { useToast } from "../ui/Toast";
|
||||||
|
import { ProductPicker } from "./ProductPicker";
|
||||||
import { api } from "../../api";
|
import { api } from "../../api";
|
||||||
import { useAsync } from "../../hooks/useAsync";
|
import { useAsync } from "../../hooks/useAsync";
|
||||||
import { errorMessage, nowHHMM, todayISO } from "../../lib/format";
|
import { errorMessage, nowHHMM, todayISO } from "../../lib/format";
|
||||||
import { amount, maxLength, required, useValidation } from "../../lib/validation";
|
import { amount, maxLength, required, useValidation } from "../../lib/validation";
|
||||||
import type { Chemist, Dcr, Doctor } from "../../types";
|
import type { Chemist, Dcr, Doctor } from "../../types";
|
||||||
|
|
||||||
export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
|
/** Pre-selects a doctor/chemist, e.g. "Record visit" on a planned line. A new `key` re-applies it. */
|
||||||
dcr: Dcr; doctors: Doctor[]; chemists: Chemist[]; onChange: (dcr: Dcr) => void;
|
export interface VisitPreset { kind: "doctor" | "chemist"; targetId: string; key: number }
|
||||||
|
|
||||||
|
export function AddVisitForm({ dcr, doctors, chemists, onChange, preset }: {
|
||||||
|
dcr: Dcr; doctors: Doctor[]; chemists: Chemist[]; onChange: (dcr: Dcr) => void; preset?: VisitPreset | null;
|
||||||
}) {
|
}) {
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
const products = useAsync(api.stockInventory, []);
|
const products = useAsync(api.stockInventory, []);
|
||||||
@@ -20,27 +24,43 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
|
|||||||
const [time, setTime] = useState(nowHHMM);
|
const [time, setTime] = useState(nowHHMM);
|
||||||
const [outcome, setOutcome] = useState("MET");
|
const [outcome, setOutcome] = useState("MET");
|
||||||
const [conversion, setConversion] = useState("NOT_STARTED");
|
const [conversion, setConversion] = useState("NOT_STARTED");
|
||||||
const [promote, setPromote] = useState("");
|
const [promote, setPromote] = useState<string[]>([]);
|
||||||
const [sample, setSample] = useState("");
|
const [sample, setSample] = useState<string[]>([]);
|
||||||
const [pob, setPob] = useState("");
|
const [pob, setPob] = useState("");
|
||||||
|
const [gift, setGift] = useState("");
|
||||||
const [remarks, setRemarks] = useState("");
|
const [remarks, setRemarks] = useState("");
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
|
const formRef = useRef<HTMLFormElement>(null);
|
||||||
|
// A day plan records who and when only; outcomes, products and POB come at the end of the day.
|
||||||
|
const isPlan = dcr.report_type === "PLAN";
|
||||||
|
// An Area Manager's own report lists the headquarters' doctors and chemists, not assigned ones.
|
||||||
|
const isSelf = dcr.report_type === "SELF";
|
||||||
|
const productNames = (products.data ?? []).map((p) => p.product_name);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!preset) return;
|
||||||
|
setKind(preset.kind);
|
||||||
|
setTargetId(preset.targetId);
|
||||||
|
setTime(nowHHMM());
|
||||||
|
v.clear();
|
||||||
|
formRef.current?.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||||
|
}, [preset?.key]);
|
||||||
|
|
||||||
const selectedDoctor = kind === "doctor" ? doctors.find((d) => d.id === targetId) : undefined;
|
const selectedDoctor = kind === "doctor" ? doctors.find((d) => d.id === targetId) : undefined;
|
||||||
const options = kind === "doctor" ? doctors : chemists;
|
const options = kind === "doctor" ? doctors : chemists;
|
||||||
// Visit times are local; today's report cannot hold a visit later than now.
|
// Visit times are local; today's report cannot hold a visit later than now.
|
||||||
const isToday = dcr.report_date === todayISO();
|
const isToday = !isPlan && dcr.report_date === todayISO();
|
||||||
|
const timeLabel = isPlan ? "Planned time" : "Visit time";
|
||||||
const label = kind === "doctor" ? "Doctor" : "Chemist";
|
const label = kind === "doctor" ? "Doctor" : "Chemist";
|
||||||
|
|
||||||
const v = useValidation({
|
const v = useValidation({
|
||||||
target: [required(label)],
|
target: [required(label)],
|
||||||
time: [required("Visit time"), (t) => (isToday && t > nowHHMM() ? "A visit today cannot be later than the current time" : null)],
|
time: [required(timeLabel), (t) => (isToday && t > nowHHMM() ? "A visit today cannot be later than the current time" : null)],
|
||||||
promote: [maxLength(200, "Product promoted")],
|
|
||||||
sample: [maxLength(200, "Product sample")],
|
|
||||||
pob: [maxLength(100, "POB"), amount("POB")],
|
pob: [maxLength(100, "POB"), amount("POB")],
|
||||||
|
gift: [maxLength(200, "Gift")],
|
||||||
remarks: [maxLength(2000, "Remarks")],
|
remarks: [maxLength(2000, "Remarks")],
|
||||||
});
|
});
|
||||||
const values = () => ({ target: targetId, time, promote, sample, pob, remarks });
|
const values = () => ({ target: targetId, time, pob, gift, remarks });
|
||||||
const on = (name: string, set: (value: string) => void) => (e: { target: { value: string } }) => { set(e.target.value); v.retouch(name, e.target.value); };
|
const on = (name: string, set: (value: string) => void) => (e: { target: { value: string } }) => { set(e.target.value); v.retouch(name, e.target.value); };
|
||||||
const blur = (name: string) => (e: { target: { value: string } }) => v.touch(name, e.target.value);
|
const blur = (name: string) => (e: { target: { value: string } }) => v.touch(name, e.target.value);
|
||||||
|
|
||||||
@@ -50,16 +70,20 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
|
|||||||
setBusy(true);
|
setBusy(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const updated = kind === "doctor"
|
const updated = isPlan
|
||||||
|
? kind === "doctor"
|
||||||
|
? await api.addDoctorCall(dcr.id, { doctor_id: targetId, visit_time: time, remarks: remarks.trim() || null })
|
||||||
|
: await api.addChemistCall(dcr.id, { chemist_id: targetId, visit_time: time, remarks: remarks.trim() || null })
|
||||||
|
: kind === "doctor"
|
||||||
? await api.addDoctorCall(dcr.id, {
|
? await api.addDoctorCall(dcr.id, {
|
||||||
doctor_id: targetId, visit_time: time, call_outcome: outcome,
|
doctor_id: targetId, visit_time: time, call_outcome: outcome,
|
||||||
conversion_status: selectedDoctor?.is_core_doctor ? conversion : null,
|
conversion_status: selectedDoctor?.is_core_doctor ? conversion : null,
|
||||||
product_promote: promote.trim() || null, product_sample: sample.trim() || null, remarks: remarks.trim() || null,
|
product_promote: promote, product_sample: sample, gift: gift.trim() || null, remarks: remarks.trim() || null,
|
||||||
})
|
})
|
||||||
: await api.addChemistCall(dcr.id, { chemist_id: targetId, visit_time: time, pob: pob.trim() || null, remarks: remarks.trim() || null });
|
: await api.addChemistCall(dcr.id, { chemist_id: targetId, visit_time: time, pob: pob.trim() || null, remarks: remarks.trim() || null });
|
||||||
onChange(updated);
|
onChange(updated);
|
||||||
toast.success(`${label} visit added`);
|
toast.success(isPlan ? `${label} added to the plan` : `${label} visit added`);
|
||||||
setTargetId(""); setPromote(""); setSample(""); setPob(""); setRemarks("");
|
setTargetId(""); setPromote([]); setSample([]); setPob(""); setGift(""); setRemarks("");
|
||||||
v.clear();
|
v.clear();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(errorMessage(err, "Could not add the visit")); // shown right here, where the MR is looking
|
setError(errorMessage(err, "Could not add the visit")); // shown right here, where the MR is looking
|
||||||
@@ -69,7 +93,7 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form className="form-grid" onSubmit={submit} noValidate>
|
<form ref={formRef} className="form-grid" onSubmit={submit} noValidate>
|
||||||
<Alert>{error}</Alert>
|
<Alert>{error}</Alert>
|
||||||
<Field label="Visit type">
|
<Field label="Visit type">
|
||||||
<Select value={kind} onChange={(e) => { setKind(e.target.value as "doctor" | "chemist"); setTargetId(""); v.clear(); }}>
|
<Select value={kind} onChange={(e) => { setKind(e.target.value as "doctor" | "chemist"); setTargetId(""); v.clear(); }}>
|
||||||
@@ -77,18 +101,18 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
|
|||||||
<option value="chemist">Chemist</option>
|
<option value="chemist">Chemist</option>
|
||||||
</Select>
|
</Select>
|
||||||
</Field>
|
</Field>
|
||||||
<Field label={label} required error={v.errors.target} hint={options.length === 0 ? `No ${kind}s are assigned to you yet — ask your administrator to assign some.` : undefined}>
|
<Field label={label} required error={v.errors.target} hint={options.length === 0 ? (isSelf ? `This headquarters has no ${kind}s yet.` : `No ${kind}s are assigned to you yet — ask your administrator to assign some.`) : undefined}>
|
||||||
<Select value={targetId} onChange={on("target", setTargetId)} onBlur={blur("target")} disabled={options.length === 0}>
|
<Select value={targetId} onChange={on("target", setTargetId)} onBlur={blur("target")} disabled={options.length === 0}>
|
||||||
<option value="">Choose an assigned {kind}</option>
|
<option value="">{isSelf ? `Choose a ${kind}` : `Choose an assigned ${kind}`}</option>
|
||||||
{options.map((o) => (
|
{options.map((o) => (
|
||||||
<option key={o.id} value={o.id}>{o.name}{"is_core_doctor" in o && o.is_core_doctor ? " (core)" : ""}</option>
|
<option key={o.id} value={o.id}>{o.name}{"is_core_doctor" in o && o.is_core_doctor ? " (core)" : ""}</option>
|
||||||
))}
|
))}
|
||||||
</Select>
|
</Select>
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="Visit time" required error={v.errors.time}>
|
<Field label={timeLabel} required error={v.errors.time}>
|
||||||
<Input type="time" value={time} max={isToday ? nowHHMM() : undefined} onChange={on("time", setTime)} onBlur={blur("time")} />
|
<Input type="time" value={time} max={isToday ? nowHHMM() : undefined} onChange={on("time", setTime)} onBlur={blur("time")} />
|
||||||
</Field>
|
</Field>
|
||||||
{kind === "doctor" && (
|
{!isPlan && kind === "doctor" && (
|
||||||
<Field label="Outcome">
|
<Field label="Outcome">
|
||||||
<Select value={outcome} onChange={(e) => setOutcome(e.target.value)}>
|
<Select value={outcome} onChange={(e) => setOutcome(e.target.value)}>
|
||||||
<option value="MET">Met</option>
|
<option value="MET">Met</option>
|
||||||
@@ -97,7 +121,7 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
|
|||||||
</Select>
|
</Select>
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
{selectedDoctor?.is_core_doctor && (
|
{!isPlan && selectedDoctor?.is_core_doctor && (
|
||||||
<Field label="Core doctor status">
|
<Field label="Core doctor status">
|
||||||
<Select value={conversion} onChange={(e) => setConversion(e.target.value)}>
|
<Select value={conversion} onChange={(e) => setConversion(e.target.value)}>
|
||||||
<option value="NOT_STARTED">Not started</option>
|
<option value="NOT_STARTED">Not started</option>
|
||||||
@@ -107,28 +131,28 @@ export function AddVisitForm({ dcr, doctors, chemists, onChange }: {
|
|||||||
</Select>
|
</Select>
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
{kind === "doctor" ? (
|
{isPlan ? null : kind === "doctor" ? (
|
||||||
<>
|
<>
|
||||||
<Field label="Product promoted" error={v.errors.promote}>
|
<Field label="Products promoted" hint={`${promote.length} chosen`}>
|
||||||
<Input list="product-suggestions" value={promote} onChange={on("promote", setPromote)} onBlur={blur("promote")} placeholder="Pick or type a product" />
|
<ProductPicker value={promote} onChange={setPromote} suggestions={productNames} listId="promote-suggestions" placeholder="Pick or type a product" />
|
||||||
</Field>
|
</Field>
|
||||||
<Field label="Product sample" error={v.errors.sample}>
|
<Field label="Product samples" hint={`${sample.length} chosen`}>
|
||||||
<Input list="product-suggestions" value={sample} onChange={on("sample", setSample)} onBlur={blur("sample")} placeholder="Sample given, if any" />
|
<ProductPicker value={sample} onChange={setSample} suggestions={productNames} listId="sample-suggestions" placeholder="Samples given, if any" />
|
||||||
|
</Field>
|
||||||
|
<Field label="Gift" error={v.errors.gift} hint="Optional — any gift given to the doctor on this visit">
|
||||||
|
<Input value={gift} onChange={on("gift", setGift)} onBlur={blur("gift")} placeholder="e.g. Diary, pen" />
|
||||||
</Field>
|
</Field>
|
||||||
<datalist id="product-suggestions">
|
|
||||||
{(products.data ?? []).map((p) => <option key={p.id} value={p.product_name} />)}
|
|
||||||
</datalist>
|
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<Field label="POB (order booked)" error={v.errors.pob} hint="Amount, e.g. 12500 or 12,500.50">
|
<Field label="POB (order booked)" error={v.errors.pob} hint="Amount, e.g. 12500 or 12,500.50">
|
||||||
<Input inputMode="decimal" value={pob} onChange={on("pob", setPob)} onBlur={blur("pob")} placeholder="0" />
|
<Input inputMode="decimal" value={pob} onChange={on("pob", setPob)} onBlur={blur("pob")} placeholder="0" />
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
<Field label="Remarks" span error={v.errors.remarks} hint={`${remarks.length}/2000`}>
|
<Field label={isPlan ? "Purpose / note" : "Remarks"} span error={v.errors.remarks} hint={`${remarks.length}/2000`}>
|
||||||
<Textarea value={remarks} onChange={on("remarks", setRemarks)} onBlur={blur("remarks")} rows={2} />
|
<Textarea value={remarks} onChange={on("remarks", setRemarks)} onBlur={blur("remarks")} rows={2} placeholder={isPlan ? "Optional, e.g. follow up on samples" : undefined} />
|
||||||
</Field>
|
</Field>
|
||||||
<div className="form-actions">
|
<div className="form-actions">
|
||||||
<Button type="submit" variant="primary" icon="plus" loading={busy}>Add {kind} visit</Button>
|
<Button type="submit" variant="primary" icon="plus" loading={busy}>{isPlan ? `Add ${kind} to plan` : `Add ${kind} visit`}</Button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { Badge } from "../ui/Badge";
|
||||||
|
import { Button } from "../ui/Button";
|
||||||
|
import { Field, Textarea } from "../ui/Field";
|
||||||
|
import { EmptyState } from "../ui/States";
|
||||||
|
import type { Dcr, PlannedVisit } from "../../types";
|
||||||
|
|
||||||
|
const STATUS: Record<PlannedVisit["status"], { label: string; tone: "success" | "warning" | "danger" }> = {
|
||||||
|
VISITED: { label: "Visited", tone: "success" },
|
||||||
|
MISSED: { label: "Missed", tone: "warning" },
|
||||||
|
PENDING: { label: "Not recorded", tone: "danger" },
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The approved day plan, line by line, on the end-of-day report. Every line must end up
|
||||||
|
* visited (a visit recorded below) or missed (with a short note) before the report can be submitted.
|
||||||
|
*/
|
||||||
|
export function PlannedVisitList({ dcr, editable, onRecord, onSaveReason, onClearReason }: {
|
||||||
|
dcr: Dcr;
|
||||||
|
editable: boolean;
|
||||||
|
onRecord: (line: PlannedVisit) => void;
|
||||||
|
onSaveReason: (line: PlannedVisit, reason: string) => Promise<boolean>;
|
||||||
|
onClearReason: (line: PlannedVisit) => void;
|
||||||
|
}) {
|
||||||
|
const [editing, setEditing] = useState<string | null>(null);
|
||||||
|
const [reason, setReason] = useState("");
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
if (dcr.planned_visits.length === 0) {
|
||||||
|
return <EmptyState icon="file" title="Nothing was planned" description="The approved Daily Call Report (Plan) has no visits on it." />;
|
||||||
|
}
|
||||||
|
|
||||||
|
const startEdit = (line: PlannedVisit) => { setEditing(line.target_id); setReason(line.missed_reason ?? ""); setError(null); };
|
||||||
|
const save = async (line: PlannedVisit) => {
|
||||||
|
if (reason.trim().length < 3) { setError("Say briefly why the visit was missed (3+ characters)."); return; }
|
||||||
|
if (reason.trim().length > 500) { setError("Keep the note to 500 characters or fewer."); return; }
|
||||||
|
setSaving(true);
|
||||||
|
if (await onSaveReason(line, reason.trim())) setEditing(null);
|
||||||
|
setSaving(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ul className="visit-list">
|
||||||
|
{dcr.planned_visits.map((line) => {
|
||||||
|
const status = STATUS[line.status];
|
||||||
|
const isEditing = editable && editing === line.target_id;
|
||||||
|
return (
|
||||||
|
<li key={line.target_id} style={isEditing ? { flexWrap: "wrap" } : undefined}>
|
||||||
|
<span className="visit-time">{line.planned_time.slice(0, 5)}</span>
|
||||||
|
<div className="visit-main">
|
||||||
|
<p>
|
||||||
|
<strong>{line.name}</strong> <Badge tone={line.kind === "DOCTOR" ? "brand" : "neutral"}>{line.kind === "DOCTOR" ? "Doctor" : "Chemist"}</Badge>
|
||||||
|
{line.is_core_doctor && <> <Badge tone="warning">Core</Badge></>} <Badge tone={status.tone} dot>{status.label}</Badge>
|
||||||
|
</p>
|
||||||
|
{line.status === "MISSED" && !isEditing && <p className="visit-detail">Why missed: {line.missed_reason}</p>}
|
||||||
|
</div>
|
||||||
|
{editable && !isEditing && line.status === "PENDING" && (
|
||||||
|
<span className="row-actions">
|
||||||
|
<Button size="sm" icon="check" onClick={() => onRecord(line)}>Record visit</Button>
|
||||||
|
<Button size="sm" variant="ghost" icon="edit" onClick={() => startEdit(line)}>Missed</Button>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{editable && !isEditing && line.status === "MISSED" && (
|
||||||
|
<span className="row-actions">
|
||||||
|
<Button size="sm" variant="ghost" icon="edit" onClick={() => startEdit(line)}>Edit note</Button>
|
||||||
|
<Button size="sm" variant="ghost" icon="x" onClick={() => onClearReason(line)} aria-label={`Clear the missed note for ${line.name}`}>Clear</Button>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{isEditing && (
|
||||||
|
<div style={{ flexBasis: "100%" }}>
|
||||||
|
<Field label={`Why was ${line.name} not visited?`} required error={error ?? undefined} hint={`${reason.length}/500`}>
|
||||||
|
<Textarea value={reason} onChange={(e) => { setReason(e.target.value); setError(null); }} rows={2} maxLength={500} placeholder="e.g. Doctor on leave, clinic closed, rescheduled to tomorrow" autoFocus />
|
||||||
|
</Field>
|
||||||
|
<div className="button-row">
|
||||||
|
<Button size="sm" onClick={() => setEditing(null)}>Cancel</Button>
|
||||||
|
<Button size="sm" variant="primary" icon="check" loading={saving} onClick={() => void save(line)}>Save note</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { type ChangeEvent, type KeyboardEvent, useState } from "react";
|
||||||
|
import { Button } from "../ui/Button";
|
||||||
|
import { Icon } from "../ui/Icon";
|
||||||
|
import { Input } from "../ui/Field";
|
||||||
|
|
||||||
|
/** Matches the server's limit per visit. */
|
||||||
|
export const MAX_PRODUCTS = 10;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Several products for one visit. Picking a suggestion adds it at once; a name typed by hand is
|
||||||
|
* added with Enter, the Add button, or on leaving the box (so it is never silently dropped).
|
||||||
|
* Chosen products show as chips that can be removed.
|
||||||
|
*/
|
||||||
|
export function ProductPicker({ value, onChange, suggestions, listId, placeholder }: {
|
||||||
|
value: string[]; onChange: (next: string[]) => void; suggestions: string[]; listId: string; placeholder: string;
|
||||||
|
}) {
|
||||||
|
const [draft, setDraft] = useState("");
|
||||||
|
const full = value.length >= MAX_PRODUCTS;
|
||||||
|
const chosen = new Set(value.map((v) => v.toLowerCase()));
|
||||||
|
|
||||||
|
const add = (name: string) => {
|
||||||
|
const clean = name.trim();
|
||||||
|
if (clean && !full && !chosen.has(clean.toLowerCase())) onChange([...value, clean]);
|
||||||
|
setDraft("");
|
||||||
|
};
|
||||||
|
const typed = (e: ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const next = e.target.value;
|
||||||
|
// A datalist pick is not a keystroke. Typing "Zinc" on the way to "Zinc Plus" must not add "Zinc".
|
||||||
|
const native = e.nativeEvent as Event & { inputType?: string };
|
||||||
|
const picked = native.inputType === undefined || native.inputType === "insertReplacementText";
|
||||||
|
if (picked && suggestions.includes(next)) add(next);
|
||||||
|
else setDraft(next);
|
||||||
|
};
|
||||||
|
const onKey = (e: KeyboardEvent<HTMLInputElement>) => {
|
||||||
|
if (e.key === "Enter") { e.preventDefault(); add(draft); }
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="product-picker">
|
||||||
|
<span className="input-row">
|
||||||
|
<Input list={listId} value={draft} onChange={typed} onKeyDown={onKey} onBlur={() => add(draft)} disabled={full}
|
||||||
|
placeholder={full ? `Up to ${MAX_PRODUCTS} products` : placeholder} />
|
||||||
|
<Button size="sm" icon="plus" onClick={() => add(draft)} disabled={full || !draft.trim()}>Add</Button>
|
||||||
|
</span>
|
||||||
|
<datalist id={listId}>
|
||||||
|
{suggestions.filter((s) => !chosen.has(s.toLowerCase())).map((s) => <option key={s} value={s} />)}
|
||||||
|
</datalist>
|
||||||
|
{value.length > 0 && (
|
||||||
|
<div className="chips">
|
||||||
|
{value.map((name) => (
|
||||||
|
<span key={name} className="badge badge-brand chip">
|
||||||
|
{name}
|
||||||
|
<button type="button" className="chip-remove" aria-label={`Remove ${name}`} onClick={() => onChange(value.filter((v) => v !== name))}>
|
||||||
|
<Icon name="x" size={12} />
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,26 +1,29 @@
|
|||||||
|
import { Badge } from "../ui/Badge";
|
||||||
import { DataTable, type Column } from "../ui/DataTable";
|
import { DataTable, type Column } from "../ui/DataTable";
|
||||||
import { EmptyState } from "../ui/States";
|
import { EmptyState } from "../ui/States";
|
||||||
import { StatusBadge } from "./StatusBadge";
|
import { StatusBadge } from "./StatusBadge";
|
||||||
import { formatDate } from "../../lib/format";
|
import { formatDate, REPORT_TYPE_SHORT } from "../../lib/format";
|
||||||
|
import { reportPath } from "../../lib/navigation";
|
||||||
import { navigate } from "../../lib/router";
|
import { navigate } from "../../lib/router";
|
||||||
import type { DcrListItem } from "../../types";
|
import type { DcrListItem } from "../../types";
|
||||||
|
|
||||||
const COLUMNS: Column<DcrListItem>[] = [
|
const columns = (ownerHeader: string): Column<DcrListItem>[] => [
|
||||||
{ key: "date", header: "Report date", render: (r) => <strong>{formatDate(r.report_date)}</strong>, nowrap: true },
|
{ key: "date", header: "Report date", render: (r) => <strong>{formatDate(r.report_date)}</strong>, nowrap: true },
|
||||||
{ key: "mr", header: "Medical Representative", render: (r) => r.mr_name },
|
{ key: "type", header: "Report", render: (r) => <Badge tone={r.report_type === "ACTUAL" ? "brand" : "neutral"}>{REPORT_TYPE_SHORT[r.report_type]}</Badge>, nowrap: true },
|
||||||
|
{ key: "mr", header: ownerHeader, render: (r) => r.mr_name },
|
||||||
{ key: "hq", header: "Headquarters", render: (r) => r.headquarters_name },
|
{ key: "hq", header: "Headquarters", render: (r) => r.headquarters_name },
|
||||||
{ key: "calls", header: "Visits", render: (r) => `${r.doctor_call_count} doctors · ${r.chemist_call_count} chemists`, nowrap: true },
|
{ key: "calls", header: "Visits", render: (r) => `${r.doctor_call_count} doctors · ${r.chemist_call_count} chemists${r.report_type === "PLAN" ? " planned" : ""}`, nowrap: true },
|
||||||
{ key: "status", header: "Status", render: (r) => <StatusBadge status={r.status} /> },
|
{ key: "status", header: "Status", render: (r) => <StatusBadge status={r.status} type={r.report_type} /> },
|
||||||
];
|
];
|
||||||
|
|
||||||
export function ReportTable({ rows, loading, emptyText = "No reports yet" }: { rows: DcrListItem[]; loading?: boolean; emptyText?: string }) {
|
export function ReportTable({ rows, loading, emptyText = "No reports yet", ownerHeader = "Medical Representative" }: { rows: DcrListItem[]; loading?: boolean; emptyText?: string; ownerHeader?: string }) {
|
||||||
return (
|
return (
|
||||||
<DataTable
|
<DataTable
|
||||||
columns={COLUMNS}
|
columns={columns(ownerHeader)}
|
||||||
rows={rows}
|
rows={rows}
|
||||||
loading={loading}
|
loading={loading}
|
||||||
rowKey={(r) => r.id}
|
rowKey={(r) => r.id}
|
||||||
onRowClick={(r) => navigate(`/reports/${r.id}`)}
|
onRowClick={(r) => navigate(reportPath(r))}
|
||||||
minWidth={720}
|
minWidth={720}
|
||||||
empty={<EmptyState icon="file" title={emptyText} />}
|
empty={<EmptyState icon="file" title={emptyText} />}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Badge, type Tone } from "../ui/Badge";
|
import { Badge, type Tone } from "../ui/Badge";
|
||||||
import { STATUS_LABEL } from "../../lib/format";
|
import { statusLabel } from "../../lib/format";
|
||||||
import type { DcrStatus } from "../../types";
|
import type { DcrStatus, ReportType } from "../../types";
|
||||||
|
|
||||||
const TONE: Record<DcrStatus, Tone> = {
|
const TONE: Record<DcrStatus, Tone> = {
|
||||||
DRAFT: "neutral",
|
DRAFT: "neutral",
|
||||||
@@ -9,6 +9,6 @@ const TONE: Record<DcrStatus, Tone> = {
|
|||||||
APPROVED: "success",
|
APPROVED: "success",
|
||||||
};
|
};
|
||||||
|
|
||||||
export function StatusBadge({ status }: { status: DcrStatus }) {
|
export function StatusBadge({ status, type }: { status: DcrStatus; type?: ReportType }) {
|
||||||
return <Badge tone={TONE[status]} dot>{STATUS_LABEL[status]}</Badge>;
|
return <Badge tone={TONE[status]} dot>{statusLabel(status, type)}</Badge>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ export function VisitList({ dcr, editable, onRemove }: { dcr: Dcr; editable: boo
|
|||||||
const visits: Visit[] = [
|
const visits: Visit[] = [
|
||||||
...dcr.doctor_calls.map((c) => ({
|
...dcr.doctor_calls.map((c) => ({
|
||||||
id: c.id, kind: "Doctor" as const, name: c.doctor_name, time: c.visit_time, core: c.is_core_doctor,
|
id: c.id, kind: "Doctor" as const, name: c.doctor_name, time: c.visit_time, core: c.is_core_doctor,
|
||||||
detail: [humanize(c.call_outcome.toLowerCase()), c.conversion_status && humanize(c.conversion_status.toLowerCase()), c.product_promote && `Promote: ${c.product_promote}`, c.product_sample && `Sample: ${c.product_sample}`, c.remarks].filter(Boolean).join(" · "),
|
detail: [c.call_outcome && humanize(c.call_outcome.toLowerCase()), c.conversion_status && humanize(c.conversion_status.toLowerCase()), c.product_promote.length > 0 && `Promote: ${c.product_promote.join(", ")}`, c.product_sample.length > 0 && `Sample: ${c.product_sample.join(", ")}`, c.gift && `Gift: ${c.gift}`, c.remarks].filter(Boolean).join(" · "),
|
||||||
})),
|
})),
|
||||||
...dcr.chemist_calls.map((c) => ({
|
...dcr.chemist_calls.map((c) => ({
|
||||||
id: c.id, kind: "Chemist" as const, name: c.chemist_name, time: c.visit_time, core: false, detail: [c.pob && `POB: ${c.pob}`, c.remarks].filter(Boolean).join(" · "),
|
id: c.id, kind: "Chemist" as const, name: c.chemist_name, time: c.visit_time, core: false, detail: [c.pob && `POB: ${c.pob}`, c.remarks].filter(Boolean).join(" · "),
|
||||||
@@ -18,7 +18,14 @@ export function VisitList({ dcr, editable, onRemove }: { dcr: Dcr; editable: boo
|
|||||||
].sort((a, b) => a.time.localeCompare(b.time));
|
].sort((a, b) => a.time.localeCompare(b.time));
|
||||||
|
|
||||||
if (visits.length === 0) {
|
if (visits.length === 0) {
|
||||||
return <EmptyState icon="stethoscope" title="No visits recorded" description={editable ? "Add doctor and chemist visits above." : undefined} />;
|
const plan = dcr.report_type === "PLAN";
|
||||||
|
return (
|
||||||
|
<EmptyState
|
||||||
|
icon="stethoscope"
|
||||||
|
title={plan ? "No visits planned" : "No visits recorded"}
|
||||||
|
description={editable ? (plan ? "Add the doctors and chemists you plan to visit above." : "Add doctor and chemist visits above.") : undefined}
|
||||||
|
/>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<ul className="visit-list">
|
<ul className="visit-list">
|
||||||
|
|||||||
@@ -1,15 +1,18 @@
|
|||||||
import { Icon } from "../ui/Icon";
|
import { Icon } from "../ui/Icon";
|
||||||
import type { DcrStatus } from "../../types";
|
import type { DcrStatus, ReportType } from "../../types";
|
||||||
|
|
||||||
const STEPS = ["Draft", "Area Manager", "Approved"] as const;
|
const STEPS = ["Draft", "Area Manager", "Approved"];
|
||||||
const INDEX: Record<DcrStatus, number> = { DRAFT: 0, RETURNED: 0, PENDING_AM: 1, APPROVED: 2 };
|
const INDEX: Record<DcrStatus, number> = { DRAFT: 0, RETURNED: 0, PENDING_AM: 1, APPROVED: 2 };
|
||||||
|
/** An Area Manager's own report goes straight from draft to final. */
|
||||||
|
const SELF_STEPS = ["Draft", "Submitted"];
|
||||||
|
|
||||||
/** Where a report is in DRAFT → AM → APPROVED. A returned report sits back at step one. */
|
/** Where a report is in DRAFT → AM → APPROVED. A returned report sits back at step one. */
|
||||||
export function WorkflowTracker({ status }: { status: DcrStatus }) {
|
export function WorkflowTracker({ status, type }: { status: DcrStatus; type?: ReportType }) {
|
||||||
const current = INDEX[status];
|
const steps = type === "SELF" ? SELF_STEPS : STEPS;
|
||||||
|
const current = Math.min(INDEX[status], steps.length - 1);
|
||||||
return (
|
return (
|
||||||
<ol className="steps" aria-label="Approval progress">
|
<ol className="steps" aria-label="Approval progress">
|
||||||
{STEPS.map((label, i) => {
|
{steps.map((label, i) => {
|
||||||
const state = status === "APPROVED" || i < current ? "done" : i === current ? (status === "RETURNED" ? "returned" : "current") : "todo";
|
const state = status === "APPROVED" || i < current ? "done" : i === current ? (status === "RETURNED" ? "returned" : "current") : "todo";
|
||||||
return (
|
return (
|
||||||
<li key={label} className={`step step-${state}`} aria-current={state === "current" ? "step" : undefined}>
|
<li key={label} className={`step step-${state}`} aria-current={state === "current" ? "step" : undefined}>
|
||||||
|
|||||||
@@ -11,9 +11,11 @@ export interface Column<T> {
|
|||||||
sticky?: boolean;
|
sticky?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function DataTable<T>({ columns, rows, rowKey, loading = false, empty, onRowClick, minWidth }: {
|
export function DataTable<T>({ columns, rows, rowKey, loading = false, empty, onRowClick, minWidth, footer }: {
|
||||||
columns: Column<T>[]; rows: T[]; rowKey: (row: T) => string; loading?: boolean;
|
columns: Column<T>[]; rows: T[]; rowKey: (row: T) => string; loading?: boolean;
|
||||||
empty?: ReactNode; onRowClick?: (row: T) => void; minWidth?: number;
|
empty?: ReactNode; onRowClick?: (row: T) => void; minWidth?: number;
|
||||||
|
/** A summary row pinned under the data (e.g. totals), keyed by column key. */
|
||||||
|
footer?: Record<string, ReactNode>;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<div className="table-scroll">
|
<div className="table-scroll">
|
||||||
@@ -44,6 +46,15 @@ export function DataTable<T>({ columns, rows, rowKey, loading = false, empty, on
|
|||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
|
{footer && !loading && rows.length > 0 && (
|
||||||
|
<tfoot>
|
||||||
|
<tr>
|
||||||
|
{columns.map((c) => (
|
||||||
|
<td key={c.key} style={{ textAlign: c.align }} className={[c.nowrap && "nowrap", c.sticky && "col-sticky"].filter(Boolean).join(" ") || undefined}>{footer[c.key]}</td>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
</tfoot>
|
||||||
|
)}
|
||||||
</table>
|
</table>
|
||||||
{!loading && rows.length === 0 && empty}
|
{!loading && rows.length === 0 && empty}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
+25
-6
@@ -1,4 +1,4 @@
|
|||||||
import type { DcrStatus, Role } from "../types";
|
import type { DcrStatus, ReportType, Role } from "../types";
|
||||||
|
|
||||||
export const STATUS_LABEL: Record<DcrStatus, string> = {
|
export const STATUS_LABEL: Record<DcrStatus, string> = {
|
||||||
DRAFT: "Draft",
|
DRAFT: "Draft",
|
||||||
@@ -7,16 +7,28 @@ export const STATUS_LABEL: Record<DcrStatus, string> = {
|
|||||||
APPROVED: "Approved",
|
APPROVED: "Approved",
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const REPORT_TYPE_LABEL: Record<ReportType, string> = { PLAN: "Daily Call Report (Plan)", ACTUAL: "Daily Call Report (Done)", SELF: "Daily Call Report (Self)" };
|
||||||
|
/** Short form for badges and tight spaces. */
|
||||||
|
export const REPORT_TYPE_SHORT: Record<ReportType, string> = { PLAN: "Plan", ACTUAL: "Done", SELF: "Self" };
|
||||||
|
/** An Area Manager's own report has no approval: once submitted it is final. */
|
||||||
|
export const statusLabel = (status: DcrStatus, type?: ReportType) => (type === "SELF" && status === "APPROVED" ? "Submitted" : STATUS_LABEL[status]);
|
||||||
|
|
||||||
|
/** The roles that do field work and file reports: an SFE does an MR's work. */
|
||||||
|
export const isField = (role: string): boolean => role === "MR" || role === "SFE";
|
||||||
|
|
||||||
export const ROLE_LABEL: Record<Role, string> = {
|
export const ROLE_LABEL: Record<Role, string> = {
|
||||||
MR: "Medical Representative",
|
MR: "Medical Representative",
|
||||||
|
SFE: "Senior Field Executive",
|
||||||
AM: "Area Manager",
|
AM: "Area Manager",
|
||||||
GM: "General Manager",
|
GM: "General Manager",
|
||||||
ADMIN: "Administrator",
|
ADMIN: "Administrator",
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Today's date in the user's own timezone (toISOString would give the UTC date). */
|
/** Today's date in the user's own timezone (toISOString would give the UTC date). */
|
||||||
export const todayISO = () => {
|
/** Today's local date as YYYY-MM-DD, or `days` from today. */
|
||||||
|
export const todayISO = (days = 0) => {
|
||||||
const d = new Date();
|
const d = new Date();
|
||||||
|
d.setDate(d.getDate() + days);
|
||||||
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -52,10 +64,17 @@ export const humanize = (key: string) =>
|
|||||||
.map((word) => (ACRONYMS.has(word) ? word.toUpperCase() : word.charAt(0).toUpperCase() + word.slice(1)))
|
.map((word) => (ACRONYMS.has(word) ? word.toUpperCase() : word.charAt(0).toUpperCase() + word.slice(1)))
|
||||||
.join(" ");
|
.join(" ");
|
||||||
|
|
||||||
/** Column labels that read wrong once spelled out from their key. The stored column is still
|
/** Column labels that read wrong once spelled out from their key; the stored column keeps its name. */
|
||||||
* "aug_sales" (the printed form's own field, matching the database and the PDF) — this is only
|
const COLUMN_LABEL_OVERRIDES: Record<string, string> = {
|
||||||
* what the app displays, since "Aug Sales" is misleading once the row can be any month. */
|
kilometers_km: "Kilometers KM (One Way)",
|
||||||
const COLUMN_LABEL_OVERRIDES: Record<string, string> = { aug_sales: "Month Sales" };
|
fare: "Fare (Rs)",
|
||||||
|
da_hq: "Daily allowance – H.Q. (Rs)",
|
||||||
|
da_ex: "Daily allowance – EX (Rs)",
|
||||||
|
da_out: "Daily allowance – OUT (Rs)",
|
||||||
|
postage: "Postage (Rs)",
|
||||||
|
other_expense: "Other expense (Rs)",
|
||||||
|
total: "Total (Rs)",
|
||||||
|
};
|
||||||
export const columnLabel = (key: string) => COLUMN_LABEL_OVERRIDES[key] ?? humanize(key);
|
export const columnLabel = (key: string) => COLUMN_LABEL_OVERRIDES[key] ?? humanize(key);
|
||||||
|
|
||||||
export const errorMessage = (error: unknown, fallback = "Something went wrong") =>
|
export const errorMessage = (error: unknown, fallback = "Something went wrong") =>
|
||||||
|
|||||||
@@ -1,11 +1,26 @@
|
|||||||
|
import { isField } from "./format";
|
||||||
import type { AreaManagerMapping, Headquarters, User } from "../types";
|
import type { AreaManagerMapping, Headquarters, User } from "../types";
|
||||||
|
|
||||||
/** Headquarters a person works in: an MR has one, an AM has any number, GM and Admin cover all. */
|
/** Headquarters a person works in: an MR has one, an AM has any number, GM and Admin cover all. */
|
||||||
export function headquartersOf(user: User, hqs: Headquarters[], mappings: AreaManagerMapping[]): { all: boolean; items: Headquarters[] } {
|
export function headquartersOf(user: User, hqs: Headquarters[], mappings: AreaManagerMapping[]): { all: boolean; items: Headquarters[] } {
|
||||||
if (user.role === "GM" || user.role === "ADMIN") return { all: true, items: [] };
|
if (user.role === "GM" || user.role === "ADMIN") return { all: true, items: [] };
|
||||||
const ids = user.role === "MR"
|
const ids = isField(user.role)
|
||||||
? (user.headquarters_id ? [user.headquarters_id] : [])
|
? [...(user.headquarters_id ? [user.headquarters_id] : []), ...(user.extra_headquarter_ids ?? [])]
|
||||||
: mappings.filter((m) => m.area_manager_user_id === user.id).map((m) => m.headquarters_id);
|
: mappings.filter((m) => m.area_manager_user_id === user.id).map((m) => m.headquarters_id);
|
||||||
const wanted = new Set(ids);
|
const wanted = new Set(ids);
|
||||||
return { all: false, items: hqs.filter((h) => wanted.has(h.id)) };
|
return { all: false, items: hqs.filter((h) => wanted.has(h.id)) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Area Managers of each headquarters, by name ("Asha Rao, Ravi Das"). A headquarters may
|
||||||
|
* have several. `except` leaves one Area Manager out, e.g. the one whose headquarters are being edited.
|
||||||
|
*/
|
||||||
|
export function areaManagersOf(mappings: AreaManagerMapping[], users: User[], except?: string): Record<string, string> {
|
||||||
|
const name = new Map(users.map((u) => [u.id, u.full_name]));
|
||||||
|
const byHq = new Map<string, string[]>();
|
||||||
|
for (const m of mappings) {
|
||||||
|
if (m.area_manager_user_id === except) continue;
|
||||||
|
byHq.set(m.headquarters_id, [...(byHq.get(m.headquarters_id) ?? []), name.get(m.area_manager_user_id) ?? "an Area Manager"]);
|
||||||
|
}
|
||||||
|
return Object.fromEntries([...byHq].map(([hq, names]) => [hq, names.sort().join(", ")]));
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { IconName } from "../components/ui/Icon";
|
import type { IconName } from "../components/ui/Icon";
|
||||||
import type { Role } from "../types";
|
import type { ReportType, Role } from "../types";
|
||||||
|
|
||||||
export interface NavItem {
|
export interface NavItem {
|
||||||
to: string;
|
to: string;
|
||||||
@@ -13,13 +13,20 @@ export interface NavSection {
|
|||||||
items: NavItem[];
|
items: NavItem[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Each report type has its own list, so the sidebar highlights the right one on a report's page. */
|
||||||
|
const REPORTS_PATH: Record<ReportType, string> = { PLAN: "/reports/plan", ACTUAL: "/reports/done", SELF: "/reports/self" };
|
||||||
|
export const reportsPath = (type: ReportType) => REPORTS_PATH[type];
|
||||||
|
export const reportPath = (report: { id: string; report_type: ReportType }) => `${reportsPath(report.report_type)}/${report.id}`;
|
||||||
|
|
||||||
/** Sidebar structure. `roles` limits an item to those roles; omitted means everyone. */
|
/** Sidebar structure. `roles` limits an item to those roles; omitted means everyone. */
|
||||||
export const NAVIGATION: NavSection[] = [
|
export const NAVIGATION: NavSection[] = [
|
||||||
{
|
{
|
||||||
title: "Workspace",
|
title: "Workspace",
|
||||||
items: [
|
items: [
|
||||||
{ to: "/", label: "Dashboard", icon: "dashboard" },
|
{ to: "/", label: "Dashboard", icon: "dashboard" },
|
||||||
{ to: "/reports", label: "Daily Call Reports", icon: "file", roles: ["MR", "AM", "GM"] },
|
{ to: "/reports/plan", label: "Daily Call Report (Plan)", icon: "file", roles: ["MR", "SFE", "AM", "GM"] },
|
||||||
|
{ to: "/reports/done", label: "Daily Call Report (Done)", icon: "checkCircle", roles: ["MR", "SFE", "AM", "GM"] },
|
||||||
|
{ to: "/reports/self", label: "Daily Call Report (Self)", icon: "file", roles: ["AM", "GM"] },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -27,13 +34,13 @@ export const NAVIGATION: NavSection[] = [
|
|||||||
items: [
|
items: [
|
||||||
{ to: "/directory", label: "Doctors & Chemists", icon: "stethoscope" },
|
{ to: "/directory", label: "Doctors & Chemists", icon: "stethoscope" },
|
||||||
{ to: "/products", label: "Products", icon: "box" },
|
{ to: "/products", label: "Products", icon: "box" },
|
||||||
{ to: "/forms", label: "Company forms", icon: "table", roles: ["MR", "AM", "ADMIN"] },
|
{ to: "/forms", label: "Company forms", icon: "table", roles: ["MR", "SFE", "AM", "GM", "ADMIN"] },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: "Administration",
|
title: "Administration",
|
||||||
items: [
|
items: [
|
||||||
{ to: "/admin", label: "Setup", icon: "settings", roles: ["ADMIN"] },
|
{ to: "/admin", label: "Setup", icon: "settings", roles: ["ADMIN", "MR", "SFE"] },
|
||||||
{ to: "/users", label: "Users", icon: "users", roles: ["ADMIN", "GM"] },
|
{ to: "/users", label: "Users", icon: "users", roles: ["ADMIN", "GM"] },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -49,9 +56,9 @@ export function navigationFor(role: Role): NavSection[] {
|
|||||||
/** Title shown in the top bar for the current path. */
|
/** Title shown in the top bar for the current path. */
|
||||||
export function titleFor(path: string): string {
|
export function titleFor(path: string): string {
|
||||||
if (path === "/") return "Dashboard";
|
if (path === "/") return "Dashboard";
|
||||||
if (path === "/reports/new") return "New report";
|
if (path.startsWith("/reports/done")) return "Daily Call Report (Done)";
|
||||||
if (path.startsWith("/reports/")) return "Report";
|
if (path.startsWith("/reports/self")) return "Daily Call Report (Self)";
|
||||||
if (path.startsWith("/reports")) return "Daily Call Reports";
|
if (path.startsWith("/reports")) return "Daily Call Report (Plan)";
|
||||||
if (path.startsWith("/forms")) return "Company forms";
|
if (path.startsWith("/forms")) return "Company forms";
|
||||||
if (path.startsWith("/directory")) return "Doctors & Chemists";
|
if (path.startsWith("/directory")) return "Doctors & Chemists";
|
||||||
if (path.startsWith("/products")) return "Products";
|
if (path.startsWith("/products")) return "Products";
|
||||||
|
|||||||
+118
-19
@@ -3,6 +3,7 @@ import { Badge } from "../components/ui/Badge";
|
|||||||
import { Button } from "../components/ui/Button";
|
import { Button } from "../components/ui/Button";
|
||||||
import { Card, CardBody, CardHeader } from "../components/ui/Card";
|
import { Card, CardBody, CardHeader } from "../components/ui/Card";
|
||||||
import { DataTable, type Column } from "../components/ui/DataTable";
|
import { DataTable, type Column } from "../components/ui/DataTable";
|
||||||
|
import { Select } from "../components/ui/Field";
|
||||||
import { EmptyState, ErrorState } from "../components/ui/States";
|
import { EmptyState, ErrorState } from "../components/ui/States";
|
||||||
import { PageHeader } from "../components/ui/PageHeader";
|
import { PageHeader } from "../components/ui/PageHeader";
|
||||||
import { Stat } from "../components/ui/Misc";
|
import { Stat } from "../components/ui/Misc";
|
||||||
@@ -11,7 +12,7 @@ import { LIVE, useAsync } from "../hooks/useAsync";
|
|||||||
import { api } from "../api";
|
import { api } from "../api";
|
||||||
import { Link, navigate } from "../lib/router";
|
import { Link, navigate } from "../lib/router";
|
||||||
import { useUser } from "../lib/session";
|
import { useUser } from "../lib/session";
|
||||||
import { ROLE_LABEL } from "../lib/format";
|
import { ROLE_LABEL, isField } from "../lib/format";
|
||||||
import { headquartersOf } from "../lib/headquarters";
|
import { headquartersOf } from "../lib/headquarters";
|
||||||
import type { DcrListItem, Headquarters, Role, User } from "../types";
|
import type { DcrListItem, Headquarters, Role, User } from "../types";
|
||||||
|
|
||||||
@@ -26,12 +27,29 @@ export function DashboardPage() {
|
|||||||
return <ReportDashboard role={user.role} name={user.full_name.split(" ")[0]!} />;
|
return <ReportDashboard role={user.role} name={user.full_name.split(" ")[0]!} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Narrows the dashboard to one headquarters. It lists only the headquarters the server lets
|
||||||
|
* this user see; "" means all of them.
|
||||||
|
*/
|
||||||
|
function HeadquartersFilter({ value, onChange }: { value: string; onChange: (id: string) => void }) {
|
||||||
|
const hqs = useAsync(api.headquarters, [], { poll: LIVE });
|
||||||
|
return (
|
||||||
|
<Select className="hq-filter" value={value} onChange={(e) => onChange(e.target.value)} aria-label="Filter by headquarters" disabled={!hqs.data}>
|
||||||
|
<option value="">All headquarters</option>
|
||||||
|
{(hqs.data ?? []).map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}
|
||||||
|
</Select>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function ReportDashboard({ role, name }: { role: Exclude<Role, "ADMIN">; name: string }) {
|
function ReportDashboard({ role, name }: { role: Exclude<Role, "ADMIN">; name: string }) {
|
||||||
const counts = useAsync(api.counts, [], { poll: LIVE });
|
// The General Manager looks across every headquarters, so they can narrow it to one.
|
||||||
const reports = useAsync(api.reports, [], { poll: LIVE });
|
const [hq, setHq] = useState("");
|
||||||
const isMR = role === "MR";
|
const hqId = role === "GM" ? hq || undefined : undefined;
|
||||||
|
const counts = useAsync(() => api.counts(hqId), [hqId], { poll: LIVE });
|
||||||
|
const reports = useAsync(() => api.reports(undefined, hqId), [hqId], { poll: LIVE });
|
||||||
|
const isMR = isField(role);
|
||||||
// A General Manager has no approval step — they get a read-only overview.
|
// A General Manager has no approval step — they get a read-only overview.
|
||||||
const config = role === "GM" ? null : WAITING[role];
|
const config = role === "GM" ? null : WAITING[isField(role) ? "MR" : (role as "AM")];
|
||||||
const all = reports.data ?? [];
|
const all = reports.data ?? [];
|
||||||
const waiting = config ? all.filter((r) => config.statuses.includes(r.status)) : [];
|
const waiting = config ? all.filter((r) => config.statuses.includes(r.status)) : [];
|
||||||
|
|
||||||
@@ -41,10 +59,20 @@ function ReportDashboard({ role, name }: { role: Exclude<Role, "ADMIN">; name: s
|
|||||||
title={isMR ? `Good to see you, ${name}` : role === "GM" ? "Reports overview" : "Your review queue"}
|
title={isMR ? `Good to see you, ${name}` : role === "GM" ? "Reports overview" : "Your review queue"}
|
||||||
description={isMR ? "Track drafts, submissions and anything sent back for correction." : role === "GM" ? "A read-only view of every report across all headquarters." : "Reports from your scope awaiting your decision."}
|
description={isMR ? "Track drafts, submissions and anything sent back for correction." : role === "GM" ? "A read-only view of every report across all headquarters." : "Reports from your scope awaiting your decision."}
|
||||||
actions={isMR
|
actions={isMR
|
||||||
? <Button variant="primary" icon="plus" onClick={() => navigate("/reports/new")}>New report</Button>
|
? <>
|
||||||
: <Button icon="file" onClick={() => navigate("/reports")}>View all reports</Button>}
|
<Button icon="plus" onClick={() => navigate("/reports/done/new")}>New report (Done)</Button>
|
||||||
|
<Button variant="primary" icon="plus" onClick={() => navigate("/reports/plan/new")}>Plan my day</Button>
|
||||||
|
</>
|
||||||
|
: <>
|
||||||
|
{role === "GM" && <HeadquartersFilter value={hq} onChange={setHq} />}
|
||||||
|
<Button icon="file" onClick={() => navigate("/reports/plan")}>View all reports</Button>
|
||||||
|
</>}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{role === "SFE" && <MyHeadquarters />}
|
||||||
|
|
||||||
|
{role === "GM" && <OrganisationOverview canManage={false} hqId={hqId} />}
|
||||||
|
|
||||||
<div className="stats">
|
<div className="stats">
|
||||||
<Stat label="Draft" value={counts.data?.DRAFT ?? "–"} />
|
<Stat label="Draft" value={counts.data?.DRAFT ?? "–"} />
|
||||||
<Stat label="With Area Manager" value={counts.data?.PENDING_AM ?? "–"} tone="warning" />
|
<Stat label="With Area Manager" value={counts.data?.PENDING_AM ?? "–"} tone="warning" />
|
||||||
@@ -66,28 +94,94 @@ function ReportDashboard({ role, name }: { role: Exclude<Role, "ADMIN">; name: s
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader title="Recent reports" description="The latest activity within your permitted scope." actions={<Link to="/reports" className="text-link">See all →</Link>} />
|
<CardHeader title={role === "GM" ? "Recent MR reports" : "Recent reports"} description="The latest activity within your permitted scope." actions={<Link to="/reports" className="text-link">See all →</Link>} />
|
||||||
<CardBody flush>
|
<CardBody flush>
|
||||||
{reports.error ? null : <ReportTable rows={all.slice(0, 5)} loading={reports.loading} />}
|
{reports.error ? null : <ReportTable rows={all.slice(0, 5)} loading={reports.loading} />}
|
||||||
</CardBody>
|
</CardBody>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
{role === "GM" && <AreaManagerReports hqId={hqId} />}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** For a Senior Field Executive: every headquarters (district) they cover, the main one first. */
|
||||||
|
function MyHeadquarters() {
|
||||||
|
const user = useUser();
|
||||||
|
const hqs = useAsync(api.headquarters, [], { poll: LIVE });
|
||||||
|
const mine = (hqs.data ?? []).filter((h) => h.id === user.headquarters_id || (user.extra_headquarter_ids ?? []).includes(h.id))
|
||||||
|
.sort((a, b) => Number(b.id === user.headquarters_id) - Number(a.id === user.headquarters_id));
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader title="Your headquarters" description={hqs.data ? `You cover ${mine.length} headquarters. Reports go to the Area Manager of ${mine.find((h) => h.id === user.headquarters_id)?.name ?? "your main headquarters"}.` : "Loading…"} />
|
||||||
|
<CardBody>
|
||||||
|
<div className="chip-row">
|
||||||
|
{mine.map((h) => <Badge key={h.id} tone={h.id === user.headquarters_id ? "brand" : "neutral"}>{h.code} · {h.name}{h.id === user.headquarters_id ? " (main)" : ""}</Badge>)}
|
||||||
|
</div>
|
||||||
|
</CardBody>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** For a General Manager: what the Area Managers did themselves (their Daily Call Report (Self)). */
|
||||||
|
function AreaManagerReports({ hqId }: { hqId?: string }) {
|
||||||
|
const reports = useAsync(() => api.reports("SELF", hqId), [hqId], { poll: LIVE });
|
||||||
|
const all = reports.data ?? [];
|
||||||
|
const submitted = all.filter((r) => r.status === "APPROVED").length;
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader
|
||||||
|
title="Area Managers' own reports"
|
||||||
|
description={reports.data ? `${submitted} submitted · ${all.length - submitted} in draft. Their Daily Call Report (Self), across every headquarters.` : "Their Daily Call Report (Self), across every headquarters."}
|
||||||
|
actions={<Link to="/reports/self" className="text-link">See all →</Link>}
|
||||||
|
/>
|
||||||
|
<CardBody flush>
|
||||||
|
{reports.error
|
||||||
|
? <ErrorState message={reports.error} onRetry={() => void reports.reload()} />
|
||||||
|
: !reports.loading && all.length === 0
|
||||||
|
? <EmptyState icon="file" title="No Area Manager reports yet" />
|
||||||
|
: <ReportTable rows={all.slice(0, 5)} loading={reports.loading} ownerHeader="Area Manager" />}
|
||||||
|
</CardBody>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
type AdminView = "hq" | "mr" | "am" | "gm" | "users";
|
type AdminView = "hq" | "mr" | "am" | "gm" | "users";
|
||||||
|
|
||||||
const statusBadge = (active: boolean) => <Badge tone={active ? "success" : "neutral"} dot>{active ? "Active" : "Inactive"}</Badge>;
|
const statusBadge = (active: boolean) => <Badge tone={active ? "success" : "neutral"} dot>{active ? "Active" : "Inactive"}</Badge>;
|
||||||
|
|
||||||
function AdminDashboard() {
|
function AdminDashboard() {
|
||||||
|
const [hq, setHq] = useState("");
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageHeader title="Administration" description="Set up the organisation, people and master data." actions={<><HeadquartersFilter value={hq} onChange={setHq} /><Button variant="primary" icon="settings" onClick={() => navigate("/admin")}>Open setup</Button></>} />
|
||||||
|
<OrganisationOverview canManage hqId={hq || undefined} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Headquarters and people across the whole company, with a details table per tile.
|
||||||
|
* The admin manages them; a General Manager (`canManage` false) only looks — every
|
||||||
|
* headquarters, every MR, AM and GM — and is sent to the People page, never to Setup.
|
||||||
|
*/
|
||||||
|
function OrganisationOverview({ canManage, hqId }: { canManage: boolean; hqId?: string }) {
|
||||||
const users = useAsync(api.users, [], { poll: LIVE });
|
const users = useAsync(api.users, [], { poll: LIVE });
|
||||||
const hqs = useAsync(api.headquarters, [], { poll: LIVE });
|
const hqs = useAsync(api.headquarters, [], { poll: LIVE });
|
||||||
const mappings = useAsync(api.areaManagerMappings, [], { poll: LIVE });
|
const mappings = useAsync(api.areaManagerMappings, [], { poll: LIVE });
|
||||||
const [view, setView] = useState<AdminView | null>(null);
|
const [view, setView] = useState<AdminView | null>(null);
|
||||||
const panel = useRef<HTMLDivElement>(null);
|
const panel = useRef<HTMLDivElement>(null);
|
||||||
const list = users.data ?? [];
|
const list = users.data ?? [];
|
||||||
const activeUsers = useMemo(() => list.filter((u) => u.is_active), [list]);
|
// With one headquarters chosen: that headquarters, its MRs, the Area Managers who manage it,
|
||||||
const byRole = (role: Role) => activeUsers.filter((u) => u.role === role);
|
// and the General Managers and admins (who cover every headquarters).
|
||||||
|
const shownHqs = useMemo(() => (hqs.data ?? []).filter((h) => !hqId || h.id === hqId), [hqs.data, hqId]);
|
||||||
|
const worksIn = (u: User) => {
|
||||||
|
if (!hqId) return true;
|
||||||
|
const place = headquartersOf(u, hqs.data ?? [], mappings.data ?? []);
|
||||||
|
return place.all || place.items.some((h) => h.id === hqId);
|
||||||
|
};
|
||||||
|
const activeUsers = useMemo(() => list.filter((u) => u.is_active && worksIn(u)), [list, hqId, hqs.data, mappings.data]);
|
||||||
|
const byRole = (role: Role) => activeUsers.filter((u) => (role === "MR" ? isField(u.role) : u.role === role));
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (view) panel.current?.scrollIntoView({ behavior: "smooth", block: "nearest" });
|
if (view) panel.current?.scrollIntoView({ behavior: "smooth", block: "nearest" });
|
||||||
@@ -115,26 +209,30 @@ function AdminDashboard() {
|
|||||||
{ key: "status", header: "Status", render: (u) => statusBadge(u.is_active), nowrap: true },
|
{ key: "status", header: "Status", render: (u) => statusBadge(u.is_active), nowrap: true },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// Setup is the admin's; a GM may open the People page but not Setup.
|
||||||
|
const manageLink = (to: string) => (canManage || to !== "/admin" ? to : null);
|
||||||
|
const setupHint = (text: string) => (canManage ? text : undefined);
|
||||||
|
|
||||||
const detail: Record<AdminView, { title: string; description: string; manage: string; error: string | null; loading: boolean; table: ReactNode }> = {
|
const detail: Record<AdminView, { title: string; description: string; manage: string; error: string | null; loading: boolean; table: ReactNode }> = {
|
||||||
hq: {
|
hq: {
|
||||||
title: "Headquarters", description: "Every headquarters set up for the company.", manage: "/admin",
|
title: "Headquarters", description: "Every headquarters set up for the company.", manage: "/admin",
|
||||||
error: hqs.error, loading: hqs.loading,
|
error: hqs.error, loading: hqs.loading,
|
||||||
table: <DataTable columns={hqColumns} rows={hqs.data ?? []} rowKey={(h) => h.id} loading={hqs.loading} minWidth={560} empty={<EmptyState icon="settings" title="No headquarters yet" description="Create one under Setup → Organisation." />} />,
|
table: <DataTable columns={hqColumns} rows={shownHqs} rowKey={(h) => h.id} loading={hqs.loading} minWidth={560} empty={<EmptyState icon="settings" title="No headquarters yet" description={setupHint("Create one under Setup → Organisation.")} />} />,
|
||||||
},
|
},
|
||||||
mr: {
|
mr: {
|
||||||
title: "Medical Representatives", description: "Active MRs and the headquarters they work in.", manage: "/users",
|
title: "Medical Representatives", description: "Active MRs and the headquarters they work in.", manage: "/users",
|
||||||
error: users.error, loading: users.loading,
|
error: users.error, loading: users.loading,
|
||||||
table: <DataTable columns={userColumns(false, true)} rows={byRole("MR")} rowKey={(u) => u.id} loading={users.loading} minWidth={640} empty={<EmptyState icon="users" title="No active MRs" description="Add one under Setup → People." />} />,
|
table: <DataTable columns={userColumns(false, true)} rows={byRole("MR")} rowKey={(u) => u.id} loading={users.loading} minWidth={640} empty={<EmptyState icon="users" title="No active MRs" description={setupHint("Add one under Setup → People.")} />} />,
|
||||||
},
|
},
|
||||||
am: {
|
am: {
|
||||||
title: "Area Managers", description: "Active Area Managers and every headquarters each one manages.", manage: "/users",
|
title: "Area Managers", description: "Active Area Managers and every headquarters each one manages.", manage: "/users",
|
||||||
error: users.error, loading: users.loading,
|
error: users.error, loading: users.loading,
|
||||||
table: <DataTable columns={userColumns(false, true)} rows={byRole("AM")} rowKey={(u) => u.id} loading={users.loading} minWidth={560} empty={<EmptyState icon="users" title="No active Area Managers" description="Add one under Setup → People." />} />,
|
table: <DataTable columns={userColumns(false, true)} rows={byRole("AM")} rowKey={(u) => u.id} loading={users.loading} minWidth={560} empty={<EmptyState icon="users" title="No active Area Managers" description={setupHint("Add one under Setup → People.")} />} />,
|
||||||
},
|
},
|
||||||
gm: {
|
gm: {
|
||||||
title: "General Managers", description: "Active General Managers. They have a read-only view across every headquarters.", manage: "/users",
|
title: "General Managers", description: "Active General Managers. They have a read-only view across every headquarters.", manage: "/users",
|
||||||
error: users.error, loading: users.loading,
|
error: users.error, loading: users.loading,
|
||||||
table: <DataTable columns={userColumns(false, true)} rows={byRole("GM")} rowKey={(u) => u.id} loading={users.loading} minWidth={560} empty={<EmptyState icon="users" title="No active General Managers" description="Add one under Setup → People." />} />,
|
table: <DataTable columns={userColumns(false, true)} rows={byRole("GM")} rowKey={(u) => u.id} loading={users.loading} minWidth={560} empty={<EmptyState icon="users" title="No active General Managers" description={setupHint("Add one under Setup → People.")} />} />,
|
||||||
},
|
},
|
||||||
users: {
|
users: {
|
||||||
title: "Active users", description: "Everyone who can currently sign in.", manage: "/users",
|
title: "Active users", description: "Everyone who can currently sign in.", manage: "/users",
|
||||||
@@ -143,12 +241,12 @@ function AdminDashboard() {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
const current = view ? detail[view] : null;
|
const current = view ? detail[view] : null;
|
||||||
|
const currentManage = current ? manageLink(current.manage) : null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<PageHeader title="Administration" description="Set up the organisation, people and master data." actions={<Button variant="primary" icon="settings" onClick={() => navigate("/admin")}>Open setup</Button>} />
|
|
||||||
<div className="stats stats-5">
|
<div className="stats stats-5">
|
||||||
<Stat label="Headquarters" value={hqs.data?.length ?? "–"} hint="View details" onClick={() => pick("hq")} selected={view === "hq"} />
|
<Stat label="Headquarters" value={hqs.data ? shownHqs.length : "–"} hint="View details" onClick={() => pick("hq")} selected={view === "hq"} />
|
||||||
<Stat label="Medical Representatives" value={users.data ? byRole("MR").length : "–"} hint="View details" onClick={() => pick("mr")} selected={view === "mr"} />
|
<Stat label="Medical Representatives" value={users.data ? byRole("MR").length : "–"} hint="View details" onClick={() => pick("mr")} selected={view === "mr"} />
|
||||||
<Stat label="Area Managers" value={users.data ? byRole("AM").length : "–"} hint="View details" onClick={() => pick("am")} selected={view === "am"} />
|
<Stat label="Area Managers" value={users.data ? byRole("AM").length : "–"} hint="View details" onClick={() => pick("am")} selected={view === "am"} />
|
||||||
<Stat label="General Managers" value={users.data ? byRole("GM").length : "–"} hint="View details" onClick={() => pick("gm")} selected={view === "gm"} />
|
<Stat label="General Managers" value={users.data ? byRole("GM").length : "–"} hint="View details" onClick={() => pick("gm")} selected={view === "gm"} />
|
||||||
@@ -160,7 +258,7 @@ function AdminDashboard() {
|
|||||||
<CardHeader
|
<CardHeader
|
||||||
title={current.title}
|
title={current.title}
|
||||||
description={current.description}
|
description={current.description}
|
||||||
actions={<><Link to={current.manage} className="text-link">Manage →</Link><Button size="sm" variant="ghost" onClick={() => setView(null)}>Close</Button></>}
|
actions={<>{currentManage && <Link to={currentManage} className="text-link">{canManage ? "Manage →" : "Open →"}</Link>}<Button size="sm" variant="ghost" onClick={() => setView(null)}>Close</Button></>}
|
||||||
/>
|
/>
|
||||||
<CardBody flush>
|
<CardBody flush>
|
||||||
{current.error ? <ErrorState message={current.error} onRetry={() => { void users.reload(); void hqs.reload(); }} /> : current.table}
|
{current.error ? <ErrorState message={current.error} onRetry={() => { void users.reload(); void hqs.reload(); }} /> : current.table}
|
||||||
@@ -168,7 +266,8 @@ function AdminDashboard() {
|
|||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<Card>
|
{/* Setup steps are the admin's to follow; the GM's dashboard leaves them out. */}
|
||||||
|
{canManage && <Card>
|
||||||
<CardHeader title="Recommended order" description="Create organisation data in this order." />
|
<CardHeader title="Recommended order" description="Create organisation data in this order." />
|
||||||
<CardBody>
|
<CardBody>
|
||||||
<ol className="checklist">
|
<ol className="checklist">
|
||||||
@@ -179,7 +278,7 @@ function AdminDashboard() {
|
|||||||
<li>Assign doctors and chemists to Medical Representatives</li>
|
<li>Assign doctors and chemists to Medical Representatives</li>
|
||||||
</ol>
|
</ol>
|
||||||
</CardBody>
|
</CardBody>
|
||||||
</Card>
|
</Card>}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,16 +4,17 @@ import { Badge } from "../components/ui/Badge";
|
|||||||
import { Button } from "../components/ui/Button";
|
import { Button } from "../components/ui/Button";
|
||||||
import { Card } from "../components/ui/Card";
|
import { Card } from "../components/ui/Card";
|
||||||
import { DataTable, type Column } from "../components/ui/DataTable";
|
import { DataTable, type Column } from "../components/ui/DataTable";
|
||||||
import { Checkbox, Field, Input } from "../components/ui/Field";
|
import { Checkbox, Field, Input, Select } from "../components/ui/Field";
|
||||||
import { Modal } from "../components/ui/Modal";
|
import { Modal } from "../components/ui/Modal";
|
||||||
import { SearchInput } from "../components/ui/Misc";
|
import { SearchInput } from "../components/ui/Misc";
|
||||||
import { PageHeader } from "../components/ui/PageHeader";
|
import { PageHeader } from "../components/ui/PageHeader";
|
||||||
import { EmptyState, ErrorState } from "../components/ui/States";
|
import { EmptyState, ErrorState } from "../components/ui/States";
|
||||||
import { Tabs } from "../components/ui/Tabs";
|
import { Tabs } from "../components/ui/Tabs";
|
||||||
import { useToast } from "../components/ui/Toast";
|
import { useToast } from "../components/ui/Toast";
|
||||||
|
import { MasterRequests } from "../components/admin/MasterRequests";
|
||||||
import { LIVE, useAsync } from "../hooks/useAsync";
|
import { LIVE, useAsync } from "../hooks/useAsync";
|
||||||
import { api } from "../api";
|
import { api } from "../api";
|
||||||
import { errorMessage } from "../lib/format";
|
import { errorMessage, isField } from "../lib/format";
|
||||||
import { useUser } from "../lib/session";
|
import { useUser } from "../lib/session";
|
||||||
import { maxLength, minLength, required, useValidation } from "../lib/validation";
|
import { maxLength, minLength, required, useValidation } from "../lib/validation";
|
||||||
import type { Chemist, Doctor } from "../types";
|
import type { Chemist, Doctor } from "../types";
|
||||||
@@ -46,9 +47,13 @@ export function DirectoryPage() {
|
|||||||
const [tab, setTab] = useState<"doctors" | "chemists">("doctors");
|
const [tab, setTab] = useState<"doctors" | "chemists">("doctors");
|
||||||
const [query, setQuery] = useState("");
|
const [query, setQuery] = useState("");
|
||||||
const q = query.trim().toLowerCase();
|
const q = query.trim().toLowerCase();
|
||||||
|
// Headquarters filter: the list holds only the headquarters this user may see (every one for
|
||||||
|
// the admin and GM, an Area Manager's own), so it offers exactly those. "" = all of them.
|
||||||
|
const [hqFilter, setHqFilter] = useState("");
|
||||||
|
const inHq = (id: string) => !hqFilter || id === hqFilter;
|
||||||
|
|
||||||
const doctorRows = useMemo(() => (doctors.data ?? []).filter((d) => !q || `${d.name} ${d.speciality} ${d.clinic_address} ${hqLabel.get(d.headquarters_id) ?? ""}`.toLowerCase().includes(q)), [doctors.data, hqLabel, q]);
|
const doctorRows = useMemo(() => (doctors.data ?? []).filter((d) => inHq(d.headquarters_id) && (!q || `${d.name} ${d.speciality} ${d.clinic_address} ${hqLabel.get(d.headquarters_id) ?? ""}`.toLowerCase().includes(q))), [doctors.data, hqLabel, q, hqFilter]);
|
||||||
const chemistRows = useMemo(() => (chemists.data ?? []).filter((c) => !q || `${c.name} ${c.shop_address} ${hqLabel.get(c.headquarters_id) ?? ""}`.toLowerCase().includes(q)), [chemists.data, hqLabel, q]);
|
const chemistRows = useMemo(() => (chemists.data ?? []).filter((c) => inHq(c.headquarters_id) && (!q || `${c.name} ${c.shop_address} ${hqLabel.get(c.headquarters_id) ?? ""}`.toLowerCase().includes(q))), [chemists.data, hqLabel, q, hqFilter]);
|
||||||
const active = tab === "doctors" ? doctors : chemists;
|
const active = tab === "doctors" ? doctors : chemists;
|
||||||
async function toggleActive(target: Editing) {
|
async function toggleActive(target: Editing) {
|
||||||
const next = !target.item.is_active;
|
const next = !target.item.is_active;
|
||||||
@@ -88,16 +93,23 @@ export function DirectoryPage() {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<PageHeader title="Doctors & Chemists" description="Masters available within your permitted territory." />
|
<PageHeader title="Doctors & Chemists" description="Masters available within your permitted territory." />
|
||||||
|
{!isField(user.role) && <MasterRequests mode="review" onReviewed={() => { void doctors.reload(); void chemists.reload(); }} />}
|
||||||
<Card>
|
<Card>
|
||||||
<div className="toolbar">
|
<div className="toolbar">
|
||||||
<Tabs
|
<Tabs
|
||||||
label="Directory"
|
label="Directory"
|
||||||
value={tab}
|
value={tab}
|
||||||
onChange={setTab}
|
onChange={setTab}
|
||||||
items={[{ key: "doctors", label: "Doctors", count: doctors.data?.length }, { key: "chemists", label: "Chemists", count: chemists.data?.length }]}
|
items={[{ key: "doctors", label: "Doctors", count: doctors.data ? doctorRows.length : undefined }, { key: "chemists", label: "Chemists", count: chemists.data ? chemistRows.length : undefined }]}
|
||||||
/>
|
/>
|
||||||
|
<div className="toolbar-group">
|
||||||
|
<Select className="hq-filter" value={hqFilter} onChange={(e) => setHqFilter(e.target.value)} aria-label="Filter by headquarters" disabled={!hqs.data}>
|
||||||
|
<option value="">All headquarters</option>
|
||||||
|
{(hqs.data ?? []).map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}
|
||||||
|
</Select>
|
||||||
<SearchInput value={query} onChange={setQuery} placeholder={`Search ${tab}`} />
|
<SearchInput value={query} onChange={setQuery} placeholder={`Search ${tab}`} />
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
{active.error ? <ErrorState message={active.error} onRetry={() => void active.reload()} /> : tab === "doctors" ? (
|
{active.error ? <ErrorState message={active.error} onRetry={() => void active.reload()} /> : tab === "doctors" ? (
|
||||||
<DataTable columns={doctorColumns} rows={doctorRows} rowKey={(d) => d.id} loading={doctors.loading} minWidth={820} empty={<EmptyState icon="stethoscope" title="No doctors found" />} />
|
<DataTable columns={doctorColumns} rows={doctorRows} rowKey={(d) => d.id} loading={doctors.loading} minWidth={820} empty={<EmptyState icon="stethoscope" title="No doctors found" />} />
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -9,11 +9,14 @@ import { useToast } from "../../components/ui/Toast";
|
|||||||
import { LIVE, useAsync } from "../../hooks/useAsync";
|
import { LIVE, useAsync } from "../../hooks/useAsync";
|
||||||
import { api } from "../../api";
|
import { api } from "../../api";
|
||||||
import { HeadquartersChecklist } from "../../components/admin/HeadquartersChecklist";
|
import { HeadquartersChecklist } from "../../components/admin/HeadquartersChecklist";
|
||||||
|
import { areaManagersOf } from "../../lib/headquarters";
|
||||||
|
import { MasterRequests } from "../../components/admin/MasterRequests";
|
||||||
import { DataTable, type Column } from "../../components/ui/DataTable";
|
import { DataTable, type Column } from "../../components/ui/DataTable";
|
||||||
import { Badge } from "../../components/ui/Badge";
|
import { Badge } from "../../components/ui/Badge";
|
||||||
import type { AreaManagerMapping, Headquarters, User } from "../../types";
|
import type { AreaManagerMapping, Headquarters, User } from "../../types";
|
||||||
import { errorMessage } from "../../lib/format";
|
import { errorMessage, todayISO, isField } from "../../lib/format";
|
||||||
import { code as codeRule, email as emailRule, focusFirstError, maxLength, minLength, password as passwordRule, phone as phoneRule, required, validateValues, type Errors, type Rule } from "../../lib/validation";
|
import { useUser } from "../../lib/session";
|
||||||
|
import { code as codeRule, email as emailRule, focusFirstError, isoDate, maxLength, notAfter, minLength, password as passwordRule, phone as phoneRule, required, validateValues, type Errors, type Rule } from "../../lib/validation";
|
||||||
|
|
||||||
/** Turns a form's FormData into plain strings for the validators. */
|
/** Turns a form's FormData into plain strings for the validators. */
|
||||||
const valuesOf = (f: FormData): Record<string, string> => Object.fromEntries([...f.entries()].map(([k, v]) => [k, typeof v === "string" ? v : ""]));
|
const valuesOf = (f: FormData): Record<string, string> => Object.fromEntries([...f.entries()].map(([k, v]) => [k, typeof v === "string" ? v : ""]));
|
||||||
@@ -24,8 +27,8 @@ const valuesOf = (f: FormData): Record<string, string> => Object.fromEntries([..
|
|||||||
* that depend on other fields. Errors show under the matching <Field name="…"> as you leave a
|
* that depend on other fields. Errors show under the matching <Field name="…"> as you leave a
|
||||||
* field, and all of them on submit.
|
* field, and all of them on submit.
|
||||||
*/
|
*/
|
||||||
function AdminForm({ title, description, submitLabel, onSubmit, rules, children }: {
|
function AdminForm({ title, description, submitLabel, onSubmit, rules, successMessage, children }: {
|
||||||
title: string; description?: string; submitLabel: string;
|
title: string; description?: string; submitLabel: string; successMessage?: string;
|
||||||
onSubmit: (data: FormData) => Promise<unknown>; children: ReactNode;
|
onSubmit: (data: FormData) => Promise<unknown>; children: ReactNode;
|
||||||
rules?: Record<string, Rule[]> | ((values: Record<string, string>) => Record<string, Rule[]>);
|
rules?: Record<string, Rule[]> | ((values: Record<string, string>) => Record<string, Rule[]>);
|
||||||
}) {
|
}) {
|
||||||
@@ -64,7 +67,7 @@ function AdminForm({ title, description, submitLabel, onSubmit, rules, children
|
|||||||
await onSubmit(new FormData(form));
|
await onSubmit(new FormData(form));
|
||||||
form.reset();
|
form.reset();
|
||||||
setErrors({});
|
setErrors({});
|
||||||
toast.success(`${title} — saved`);
|
toast.success(successMessage ?? `${title} — saved`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(errorMessage(err, "Could not save"));
|
setError(errorMessage(err, "Could not save"));
|
||||||
} finally {
|
} finally {
|
||||||
@@ -96,17 +99,88 @@ const optional = (f: FormData, key: string) => text(f, key) || null;
|
|||||||
|
|
||||||
type Section = "organisation" | "people" | "masters" | "assignments";
|
type Section = "organisation" | "people" | "masters" | "assignments";
|
||||||
|
|
||||||
|
/** Setup for the signed-in role: an MR gets only the doctor and chemist forms. */
|
||||||
export function AdminPage() {
|
export function AdminPage() {
|
||||||
|
return isField(useUser().role) ? <MasterDataSetup /> : <FullSetup />;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Refresh = (task: Promise<unknown>) => Promise<unknown>;
|
||||||
|
|
||||||
|
/** With a single headquarters in scope (an MR's own), it is preselected. */
|
||||||
|
function HeadquartersSelect({ hqs }: { hqs: Headquarters[] }) {
|
||||||
|
return (
|
||||||
|
<Field label="Headquarters" name="headquarters_id" required>
|
||||||
|
<Select name="headquarters_id" defaultValue={hqs.length === 1 ? hqs[0].id : ""} key={hqs.map((h) => h.id).join()}>
|
||||||
|
<option value="">Choose headquarters</option>
|
||||||
|
{hqs.map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What an MR sees after adding a doctor or chemist: it is not in their list yet. */
|
||||||
|
const sentForApproval = (role: string, what: string) => isField(role) ? `${what} sent to your Area Manager for approval` : undefined;
|
||||||
|
|
||||||
|
function DoctorForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: Refresh }) {
|
||||||
|
const role = useUser().role;
|
||||||
|
return (
|
||||||
|
<AdminForm title="Create doctor" submitLabel={isField(role) ? "Send for approval" : "Create doctor"} successMessage={sentForApproval(role, "Doctor")}
|
||||||
|
rules={{ headquarters_id: [required("Headquarters")], name: nameRule("Name"), address: addressRule("Clinic address"), speciality: [maxLength(100, "Speciality")], phone: [phoneRule], date_of_birth: [isoDate("Date of birth"), notAfter(todayISO(), "Date of birth")] }}
|
||||||
|
onSubmit={(f) => refresh(api.createDoctor({ headquarters_id: text(f, "headquarters_id"), name: text(f, "name"), clinic_address: text(f, "address"), speciality: optional(f, "speciality"), qualification: null, contact_number: optional(f, "phone"), date_of_birth: optional(f, "date_of_birth"), is_core_doctor: f.get("core") === "on" }))}>
|
||||||
|
<HeadquartersSelect hqs={hqs} />
|
||||||
|
<Field label="Name" name="name" required><Input name="name" /></Field>
|
||||||
|
<Field label="Clinic address" name="address" required span><Input name="address" /></Field>
|
||||||
|
<Field label="Speciality" name="speciality"><Input name="speciality" /></Field>
|
||||||
|
<Field label="Phone" name="phone"><Input name="phone" inputMode="tel" /></Field>
|
||||||
|
<Field label="Date of birth" name="date_of_birth"><Input type="date" name="date_of_birth" max={todayISO()} /></Field>
|
||||||
|
<Checkbox name="core" label="Core doctor" />
|
||||||
|
</AdminForm>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChemistForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: Refresh }) {
|
||||||
|
const role = useUser().role;
|
||||||
|
return (
|
||||||
|
<AdminForm title="Create chemist" submitLabel={isField(role) ? "Send for approval" : "Create chemist"} successMessage={sentForApproval(role, "Chemist")}
|
||||||
|
rules={{ headquarters_id: [required("Headquarters")], name: nameRule("Name"), address: addressRule("Shop address"), phone: [phoneRule] }}
|
||||||
|
onSubmit={(f) => refresh(api.createChemist({ headquarters_id: text(f, "headquarters_id"), name: text(f, "name"), shop_address: text(f, "address"), contact_number: optional(f, "phone") }))}>
|
||||||
|
<HeadquartersSelect hqs={hqs} />
|
||||||
|
<Field label="Name" name="name" required><Input name="name" /></Field>
|
||||||
|
<Field label="Shop address" name="address" required span><Input name="address" /></Field>
|
||||||
|
<Field label="Phone" name="phone"><Input name="phone" inputMode="tel" /></Field>
|
||||||
|
</AdminForm>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An MR adds doctors and chemists to their own headquarters; each is assigned to them. */
|
||||||
|
function MasterDataSetup() {
|
||||||
|
const hqs = useAsync(() => api.headquarters(), []);
|
||||||
|
// A new request shows in "Your requests" straight away, not only on the next poll.
|
||||||
|
const [sent, setSent] = useState(0);
|
||||||
|
const refresh: Refresh = async (task) => { const result = await task; setSent((n) => n + 1); return result; };
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageHeader title="Setup" description="Add a doctor or chemist in your headquarters. Your Area Manager approves it, and then it joins your Doctors & Chemists list." />
|
||||||
|
<Alert tone="danger">{hqs.error}</Alert>
|
||||||
|
<div className="grid-2">
|
||||||
|
<DoctorForm hqs={hqs.data ?? []} refresh={refresh} />
|
||||||
|
<ChemistForm hqs={hqs.data ?? []} refresh={refresh} />
|
||||||
|
</div>
|
||||||
|
<MasterRequests key={sent} mode="mine" />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function FullSetup() {
|
||||||
const [section, setSection] = useState<Section>("organisation");
|
const [section, setSection] = useState<Section>("organisation");
|
||||||
const data = useAsync(async () => {
|
const data = useAsync(async () => {
|
||||||
const [hqs, users, doctors, chemists, mappings] = await Promise.all([api.headquarters(), api.users(), api.doctors(), api.chemists(), api.areaManagerMappings()]);
|
const [hqs, users, doctors, chemists, mappings] = await Promise.all([api.headquarters(), api.users(), api.doctors(), api.chemists(), api.areaManagerMappings()]);
|
||||||
return { hqs, users, doctors, chemists, mappings };
|
return { hqs, users, doctors, chemists, mappings };
|
||||||
}, [], { poll: LIVE });
|
}, [], { poll: LIVE });
|
||||||
const { hqs = [], users = [], doctors = [], chemists = [], mappings = [] } = data.data ?? {};
|
const { hqs = [], users = [], doctors = [], chemists = [], mappings = [] } = data.data ?? {};
|
||||||
const mrs = users.filter((u) => u.role === "MR");
|
const mrs = users.filter((u) => isField(u.role));
|
||||||
const ams = users.filter((u) => u.role === "AM");
|
const ams = users.filter((u) => u.role === "AM");
|
||||||
const refresh = async <T,>(task: Promise<T>) => { const result = await task; await data.reload(); return result; };
|
const refresh = async <T,>(task: Promise<T>) => { const result = await task; await data.reload(); return result; };
|
||||||
const hqOptions = hqs.map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -143,24 +217,8 @@ export function AdminPage() {
|
|||||||
|
|
||||||
{section === "masters" && (
|
{section === "masters" && (
|
||||||
<div className="grid-2">
|
<div className="grid-2">
|
||||||
<AdminForm title="Create doctor" submitLabel="Create doctor"
|
<DoctorForm hqs={hqs} refresh={refresh} />
|
||||||
rules={{ headquarters_id: [required("Headquarters")], name: nameRule("Name"), address: addressRule("Clinic address"), speciality: [maxLength(100, "Speciality")], phone: [phoneRule] }}
|
<ChemistForm hqs={hqs} refresh={refresh} />
|
||||||
onSubmit={(f) => refresh(api.createDoctor({ headquarters_id: text(f, "headquarters_id"), name: text(f, "name"), clinic_address: text(f, "address"), speciality: optional(f, "speciality"), qualification: null, contact_number: optional(f, "phone"), is_core_doctor: f.get("core") === "on" }))}>
|
|
||||||
<Field label="Headquarters" name="headquarters_id" required><Select name="headquarters_id"><option value="">Choose headquarters</option>{hqOptions}</Select></Field>
|
|
||||||
<Field label="Name" name="name" required><Input name="name" /></Field>
|
|
||||||
<Field label="Clinic address" name="address" required span><Input name="address" /></Field>
|
|
||||||
<Field label="Speciality" name="speciality"><Input name="speciality" /></Field>
|
|
||||||
<Field label="Phone" name="phone"><Input name="phone" inputMode="tel" /></Field>
|
|
||||||
<Checkbox name="core" label="Core doctor" />
|
|
||||||
</AdminForm>
|
|
||||||
<AdminForm title="Create chemist" submitLabel="Create chemist"
|
|
||||||
rules={{ headquarters_id: [required("Headquarters")], name: nameRule("Name"), address: addressRule("Shop address"), phone: [phoneRule] }}
|
|
||||||
onSubmit={(f) => refresh(api.createChemist({ headquarters_id: text(f, "headquarters_id"), name: text(f, "name"), shop_address: text(f, "address"), contact_number: optional(f, "phone") }))}>
|
|
||||||
<Field label="Headquarters" name="headquarters_id" required><Select name="headquarters_id"><option value="">Choose headquarters</option>{hqOptions}</Select></Field>
|
|
||||||
<Field label="Name" name="name" required><Input name="name" /></Field>
|
|
||||||
<Field label="Shop address" name="address" required span><Input name="address" /></Field>
|
|
||||||
<Field label="Phone" name="phone"><Input name="phone" inputMode="tel" /></Field>
|
|
||||||
</AdminForm>
|
|
||||||
<AdminForm title="Create product" submitLabel="Create product"
|
<AdminForm title="Create product" submitLabel="Create product"
|
||||||
rules={{ name: nameRule("Product name"), pack: [maxLength(100, "Pack")], unit: [maxLength(50, "Unit")] }}
|
rules={{ name: nameRule("Product name"), pack: [maxLength(100, "Pack")], unit: [maxLength(50, "Unit")] }}
|
||||||
onSubmit={(f) => refresh(api.createProduct({ name: text(f, "name"), pack: optional(f, "pack"), unit: optional(f, "unit") }))}>
|
onSubmit={(f) => refresh(api.createProduct({ name: text(f, "name"), pack: optional(f, "pack"), unit: optional(f, "unit") }))}>
|
||||||
@@ -191,17 +249,12 @@ export function AdminPage() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Owner name per headquarters, from the current Area Manager mappings. */
|
|
||||||
function ownersOf(mappings: AreaManagerMapping[], users: User[]): Record<string, string> {
|
|
||||||
const name = new Map(users.map((u) => [u.id, u.full_name]));
|
|
||||||
return Object.fromEntries(mappings.map((m) => [m.headquarters_id, name.get(m.area_manager_user_id) ?? "an Area Manager"]));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Choose an Area Manager, then tick every headquarters they should manage. */
|
/** Choose an Area Manager, then tick every headquarters they should manage. */
|
||||||
function AreaManagerForm({ ams, hqs, mappings, users, onSaved }: { ams: User[]; hqs: Headquarters[]; mappings: AreaManagerMapping[]; users: User[]; onSaved: () => Promise<unknown> }) {
|
function AreaManagerForm({ ams, hqs, mappings, users, onSaved }: { ams: User[]; hqs: Headquarters[]; mappings: AreaManagerMapping[]; users: User[]; onSaved: () => Promise<unknown> }) {
|
||||||
const [amId, setAmId] = useState("");
|
const [amId, setAmId] = useState("");
|
||||||
const [picked, setPicked] = useState<Set<string>>(new Set());
|
const [picked, setPicked] = useState<Set<string>>(new Set());
|
||||||
const owners = ownersOf(mappings, users);
|
// The other Area Managers of each headquarters: ticking one adds this AM beside them.
|
||||||
|
const owners = areaManagersOf(mappings, users, amId || undefined);
|
||||||
|
|
||||||
function choose(id: string) {
|
function choose(id: string) {
|
||||||
setAmId(id);
|
setAmId(id);
|
||||||
@@ -210,7 +263,7 @@ function AreaManagerForm({ ams, hqs, mappings, users, onSaved }: { ams: User[];
|
|||||||
return (
|
return (
|
||||||
<AdminForm
|
<AdminForm
|
||||||
title="Assign headquarters to an Area Manager"
|
title="Assign headquarters to an Area Manager"
|
||||||
description="An Area Manager can manage any number of headquarters. A headquarters has one Area Manager, so ticking one that is managed by someone else moves it."
|
description="An Area Manager can manage any number of headquarters, and a headquarters can have several Area Managers. Ticking one already managed by someone else adds this Area Manager beside them."
|
||||||
submitLabel="Save assignments"
|
submitLabel="Save assignments"
|
||||||
rules={{ area_manager_user_id: [required("Area Manager")] }}
|
rules={{ area_manager_user_id: [required("Area Manager")] }}
|
||||||
onSubmit={async () => {
|
onSubmit={async () => {
|
||||||
@@ -234,13 +287,13 @@ function AreaManagerForm({ ams, hqs, mappings, users, onSaved }: { ams: User[];
|
|||||||
|
|
||||||
/** Every headquarters and who manages it — visible at a glance. */
|
/** Every headquarters and who manages it — visible at a glance. */
|
||||||
function HeadquartersOverview({ hqs, users, mappings, loading }: { hqs: Headquarters[]; users: User[]; mappings: AreaManagerMapping[]; loading: boolean }) {
|
function HeadquartersOverview({ hqs, users, mappings, loading }: { hqs: Headquarters[]; users: User[]; mappings: AreaManagerMapping[]; loading: boolean }) {
|
||||||
const owners = ownersOf(mappings, users);
|
const owners = areaManagersOf(mappings, users);
|
||||||
const mrCount = (id: string) => users.filter((u) => u.role === "MR" && u.is_active && u.headquarters_id === id).length;
|
const mrCount = (id: string) => users.filter((u) => isField(u.role) && u.is_active && u.headquarters_id === id).length;
|
||||||
const columns: Column<Headquarters>[] = [
|
const columns: Column<Headquarters>[] = [
|
||||||
{ key: "code", header: "Code", render: (h) => <strong>{h.code}</strong>, nowrap: true },
|
{ key: "code", header: "Code", render: (h) => <strong>{h.code}</strong>, nowrap: true },
|
||||||
{ key: "name", header: "Headquarters", render: (h) => h.name },
|
{ key: "name", header: "Headquarters", render: (h) => h.name },
|
||||||
{ key: "place", header: "District / State", render: (h) => [h.district, h.state].filter(Boolean).join(", ") || "—" },
|
{ key: "place", header: "District / State", render: (h) => [h.district, h.state].filter(Boolean).join(", ") || "—" },
|
||||||
{ key: "am", header: "Area Manager", render: (h) => owners[h.id] ?? <Badge tone="warning">Not assigned</Badge> },
|
{ key: "am", header: "Area Managers", render: (h) => owners[h.id] ?? <Badge tone="warning">Not assigned</Badge> },
|
||||||
{ key: "mrs", header: "MRs", render: (h) => mrCount(h.id), align: "right", nowrap: true },
|
{ key: "mrs", header: "MRs", render: (h) => mrCount(h.id), align: "right", nowrap: true },
|
||||||
];
|
];
|
||||||
return (
|
return (
|
||||||
@@ -254,7 +307,7 @@ function HeadquartersOverview({ hqs, users, mappings, loading }: { hqs: Headquar
|
|||||||
}
|
}
|
||||||
|
|
||||||
const ROLES = [
|
const ROLES = [
|
||||||
{ value: "MR", label: "Medical Representative" }, { value: "AM", label: "Area Manager" },
|
{ value: "MR", label: "Medical Representative" }, { value: "SFE", label: "Senior Field Executive" }, { value: "AM", label: "Area Manager" },
|
||||||
{ value: "GM", label: "General Manager" }, { value: "ADMIN", label: "Administrator" },
|
{ value: "GM", label: "General Manager" }, { value: "ADMIN", label: "Administrator" },
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
@@ -262,6 +315,7 @@ const ROLES = [
|
|||||||
function PeopleForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: <T>(task: Promise<T>) => Promise<T> }) {
|
function PeopleForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: <T>(task: Promise<T>) => Promise<T> }) {
|
||||||
const [role, setRole] = useState<string>("MR");
|
const [role, setRole] = useState<string>("MR");
|
||||||
const [picked, setPicked] = useState<Set<string>>(new Set());
|
const [picked, setPicked] = useState<Set<string>>(new Set());
|
||||||
|
const [extras, setExtras] = useState<Set<string>>(new Set());
|
||||||
return (
|
return (
|
||||||
<AdminForm
|
<AdminForm
|
||||||
title="Create user" submitLabel="Create user"
|
title="Create user" submitLabel="Create user"
|
||||||
@@ -271,16 +325,17 @@ function PeopleForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: <T>(task:
|
|||||||
email: [required("Email"), emailRule],
|
email: [required("Email"), emailRule],
|
||||||
password: [required("Password"), passwordRule],
|
password: [required("Password"), passwordRule],
|
||||||
phone: [phoneRule],
|
phone: [phoneRule],
|
||||||
...(role === "MR" ? { headquarters_id: [required("Headquarters")] } : {}),
|
...(isField(role) ? { headquarters_id: [required("Headquarters")] } : {}),
|
||||||
}}
|
}}
|
||||||
onSubmit={async (f) => {
|
onSubmit={async (f) => {
|
||||||
const created = await api.createUser({
|
const created = await api.createUser({
|
||||||
email: text(f, "email"), password: text(f, "password"), full_name: text(f, "full_name"),
|
email: text(f, "email"), password: text(f, "password"), full_name: text(f, "full_name"),
|
||||||
employee_code: text(f, "employee_code"), phone: optional(f, "phone"), role,
|
employee_code: text(f, "employee_code"), phone: optional(f, "phone"), role,
|
||||||
headquarters_id: role === "MR" ? text(f, "headquarters_id") : null,
|
headquarters_id: isField(role) ? text(f, "headquarters_id") : null,
|
||||||
|
...(role === "SFE" ? { extra_headquarter_ids: [...extras].filter((id) => id !== text(f, "headquarters_id")) } : {}),
|
||||||
});
|
});
|
||||||
if (role === "AM" && picked.size > 0) await api.setAreaManagerHeadquarters(created.id, [...picked]);
|
if (role === "AM" && picked.size > 0) await api.setAreaManagerHeadquarters(created.id, [...picked]);
|
||||||
setRole("MR"); setPicked(new Set());
|
setRole("MR"); setPicked(new Set()); setExtras(new Set());
|
||||||
await refresh(Promise.resolve(created));
|
await refresh(Promise.resolve(created));
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@@ -288,13 +343,18 @@ function PeopleForm({ hqs, refresh }: { hqs: Headquarters[]; refresh: <T>(task:
|
|||||||
<Field label="Employee code" name="employee_code" required><Input name="employee_code" /></Field>
|
<Field label="Employee code" name="employee_code" required><Input name="employee_code" /></Field>
|
||||||
<Field label="Email" name="email" required><Input type="email" name="email" autoComplete="off" /></Field>
|
<Field label="Email" name="email" required><Input type="email" name="email" autoComplete="off" /></Field>
|
||||||
<Field label="Password" name="password" required hint="At least 8 characters, with a letter and a number."><Input type="password" name="password" autoComplete="new-password" /></Field>
|
<Field label="Password" name="password" required hint="At least 8 characters, with a letter and a number."><Input type="password" name="password" autoComplete="new-password" /></Field>
|
||||||
<Field label="Role"><Select name="role" value={role} onChange={(e) => { setRole(e.target.value); setPicked(new Set()); }}>{ROLES.map((r) => <option key={r.value} value={r.value}>{r.label}</option>)}</Select></Field>
|
<Field label="Role"><Select name="role" value={role} onChange={(e) => { setRole(e.target.value); setPicked(new Set()); setExtras(new Set()); }}>{ROLES.map((r) => <option key={r.value} value={r.value}>{r.label}</option>)}</Select></Field>
|
||||||
<Field label="Phone" name="phone"><Input name="phone" inputMode="tel" /></Field>
|
<Field label="Phone" name="phone"><Input name="phone" inputMode="tel" /></Field>
|
||||||
{role === "MR" && (
|
{isField(role) && (
|
||||||
<Field label="Headquarters" name="headquarters_id" required hint="The headquarters this Medical Representative works in.">
|
<Field label="Headquarters" name="headquarters_id" required hint={role === "SFE" ? "Their main headquarters: reports go to its Area Manager." : "The headquarters this Medical Representative works in."}>
|
||||||
<Select name="headquarters_id"><option value="">Choose headquarters</option>{hqs.map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}</Select>
|
<Select name="headquarters_id"><option value="">Choose headquarters</option>{hqs.map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}</Select>
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
|
{role === "SFE" && (
|
||||||
|
<Field label="Other districts they cover" span group hint={`Optional. ${extras.size} selected. They can visit doctors and chemists of these headquarters too; reports still go to the main headquarters' Area Manager.`}>
|
||||||
|
<HeadquartersChecklist headquarters={hqs} selected={extras} onChange={setExtras} />
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
{role === "AM" && (
|
{role === "AM" && (
|
||||||
<Field label="Headquarters they manage" span group hint={`Optional now — you can also set these later. ${picked.size} selected.`}>
|
<Field label="Headquarters they manage" span group hint={`Optional now — you can also set these later. ${picked.size} selected.`}>
|
||||||
<HeadquartersChecklist headquarters={hqs} selected={picked} onChange={setPicked} />
|
<HeadquartersChecklist headquarters={hqs} selected={picked} onChange={setPicked} />
|
||||||
|
|||||||
@@ -0,0 +1,168 @@
|
|||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { Badge } from "../../components/ui/Badge";
|
||||||
|
import { Button } from "../../components/ui/Button";
|
||||||
|
import { Card, CardBody, CardHeader } from "../../components/ui/Card";
|
||||||
|
import { DataTable, type Column } from "../../components/ui/DataTable";
|
||||||
|
import { PageHeader } from "../../components/ui/PageHeader";
|
||||||
|
import { StatusBadge } from "../../components/reports/StatusBadge";
|
||||||
|
import { EmptyState, ErrorState, Skeleton } from "../../components/ui/States";
|
||||||
|
import { LIVE, useAsync } from "../../hooks/useAsync";
|
||||||
|
import { api } from "../../api";
|
||||||
|
import { ROLE_LABEL, REPORT_TYPE_LABEL, STATUS_LABEL, formatDate, isField } from "../../lib/format";
|
||||||
|
import { Link } from "../../lib/router";
|
||||||
|
import { useUser } from "../../lib/session";
|
||||||
|
import type { DcrListItem, DcrStatus, ReportType, UserOverview } from "../../types";
|
||||||
|
|
||||||
|
const STATUSES: DcrStatus[] = ["DRAFT", "PENDING_AM", "RETURNED", "APPROVED"];
|
||||||
|
const APPROVAL_TONE = { draft: "neutral", pending: "warning", approved: "success" } as const;
|
||||||
|
const APPROVAL_LABEL = { draft: "Draft", pending: "With Area Manager", approved: "Approved" } as const;
|
||||||
|
|
||||||
|
/** One person's whole picture, for the General Manager and Admin: where they work, who they report to, their people, reports and forms. */
|
||||||
|
export function UserDetailPage({ id }: { id: string }) {
|
||||||
|
const viewer = useUser();
|
||||||
|
const data = useAsync(() => api.userOverview(id), [id], { poll: LIVE });
|
||||||
|
const o = data.data;
|
||||||
|
|
||||||
|
if (data.error) return <ErrorState message={data.error} onRetry={() => void data.reload()} />;
|
||||||
|
if (!o) return <Skeleton lines={8} />;
|
||||||
|
const { user } = o;
|
||||||
|
const field = isField(user.role);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PageHeader
|
||||||
|
back={{ to: "/users", label: "All users" }}
|
||||||
|
title={<>{user.full_name} <Badge tone="brand">{user.is_superadmin ? "Super Admin" : ROLE_LABEL[user.role]}</Badge> <Badge tone={user.is_active ? "success" : "neutral"} dot>{user.is_active ? "Active" : "Inactive"}</Badge></>}
|
||||||
|
description={`${user.email} · Code ${user.employee_code}${user.phone ? ` · ${user.phone}` : ""}`}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="detail-grid">
|
||||||
|
<Card>
|
||||||
|
<CardHeader title={user.role === "AM" ? "Headquarters they manage" : field ? "Headquarters" : "Headquarters"} description={user.role === "AM" ? `${o.headquarters.length} headquarters` : field ? "The main headquarters is where their reports are sent." : undefined} />
|
||||||
|
<CardBody>
|
||||||
|
{o.headquarters.length === 0
|
||||||
|
? <span className="muted">{field || user.role === "AM" ? "None assigned" : "This role sees every headquarters."}</span>
|
||||||
|
: <div className="chip-row">{o.headquarters.map((h) => (
|
||||||
|
<Badge key={h.id} tone={h.main ? "brand" : "neutral"}>{h.code} · {h.name}{h.main && field && o.headquarters.length > 1 ? " (main)" : ""}{h.field_staff !== undefined ? ` · ${h.field_staff} field staff` : ""}</Badge>
|
||||||
|
))}</div>}
|
||||||
|
</CardBody>
|
||||||
|
</Card>
|
||||||
|
{field && (
|
||||||
|
<Card>
|
||||||
|
<CardHeader title="Reports to" description="Area Manager(s) of the main headquarters" />
|
||||||
|
<CardBody>
|
||||||
|
{o.reporting_managers.length === 0 ? <span className="muted">No Area Manager assigned</span>
|
||||||
|
: <div className="chip-row">{o.reporting_managers.map((m) => <Link key={m.id} to={`/users/${m.id}`}><Badge tone="brand">{m.full_name}</Badge></Link>)}</div>}
|
||||||
|
</CardBody>
|
||||||
|
</Card>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{field && <PeopleCards o={o} />}
|
||||||
|
{user.role === "AM" && <Team o={o} />}
|
||||||
|
{(field || user.role === "AM") && <ReportsSection o={o} viewerRole={viewer.role} title={user.role === "AM" ? "Reports in their headquarters" : "Daily call reports"} />}
|
||||||
|
{user.role === "AM" && o.own_reports && o.own_reports.length > 0 && (
|
||||||
|
<ReportList title="Their own reports (Daily Call Report (Self))" rows={o.own_reports} link={viewer.role === "GM"} />
|
||||||
|
)}
|
||||||
|
{field && <Forms o={o} />}
|
||||||
|
{!field && user.role !== "AM" && <Card><CardBody><EmptyState icon="users" title="Nothing field-related to show" description="This role sets things up or looks across the company; it has no doctors, reports or forms of its own." /></CardBody></Card>}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function PeopleCards({ o }: { o: UserOverview }) {
|
||||||
|
const doctorCols: Column<UserOverview["doctors"][number]>[] = [
|
||||||
|
{ key: "n", header: "Doctor", render: (d) => <strong>{d.name}{d.is_core_doctor ? " ★" : ""}</strong> },
|
||||||
|
{ key: "s", header: "Speciality", render: (d) => d.speciality ?? "—" },
|
||||||
|
{ key: "h", header: "Headquarters", render: (d) => d.headquarters_name, nowrap: true },
|
||||||
|
{ key: "a", header: "Clinic", render: (d) => d.clinic_address },
|
||||||
|
];
|
||||||
|
const chemistCols: Column<UserOverview["chemists"][number]>[] = [
|
||||||
|
{ key: "n", header: "Chemist", render: (c) => <strong>{c.name}</strong> },
|
||||||
|
{ key: "h", header: "Headquarters", render: (c) => c.headquarters_name, nowrap: true },
|
||||||
|
{ key: "a", header: "Shop", render: (c) => c.shop_address },
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Card>
|
||||||
|
<CardHeader title="Assigned doctors" description={`${o.doctors.length} doctor${o.doctors.length === 1 ? "" : "s"} · ★ core doctor`} />
|
||||||
|
<CardBody flush><DataTable columns={doctorCols} rows={o.doctors} rowKey={(d) => d.id} minWidth={560} empty={<EmptyState icon="users" title="No doctors assigned" />} /></CardBody>
|
||||||
|
</Card>
|
||||||
|
<Card>
|
||||||
|
<CardHeader title="Assigned chemists" description={`${o.chemists.length} chemist${o.chemists.length === 1 ? "" : "s"}`} />
|
||||||
|
<CardBody flush><DataTable columns={chemistCols} rows={o.chemists} rowKey={(c) => c.id} minWidth={520} empty={<EmptyState icon="users" title="No chemists assigned" />} /></CardBody>
|
||||||
|
</Card>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Team({ o }: { o: UserOverview }) {
|
||||||
|
const cols: Column<UserOverview["team"][number]>[] = [
|
||||||
|
{ key: "n", header: "Name", render: (p) => <Link to={`/users/${p.id}`} className="text-link"><strong>{p.full_name}</strong></Link> },
|
||||||
|
{ key: "r", header: "Role", render: (p) => <Badge tone="brand">{ROLE_LABEL[p.role]}</Badge>, nowrap: true },
|
||||||
|
{ key: "h", header: "Main headquarters", render: (p) => p.headquarters ?? "—", nowrap: true },
|
||||||
|
{ key: "s", header: "Status", render: (p) => <Badge tone={p.is_active ? "success" : "neutral"} dot>{p.is_active ? "Active" : "Inactive"}</Badge> },
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader title="Field team" description="MRs and SFEs who report to this Area Manager" />
|
||||||
|
<CardBody flush><DataTable columns={cols} rows={o.team} rowKey={(p) => p.id} minWidth={520} empty={<EmptyState icon="users" title="Nobody reports to them yet" />} /></CardBody>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ReportsSection({ o, viewerRole, title }: { o: UserOverview; viewerRole: string; title: string }) {
|
||||||
|
const types: ReportType[] = ["PLAN", "ACTUAL"];
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Card>
|
||||||
|
<CardHeader title={title} description="How many reports are in each state" />
|
||||||
|
<CardBody>
|
||||||
|
<div className="summary-grid">
|
||||||
|
{types.map((t) => (
|
||||||
|
<div key={t} className="summary-block">
|
||||||
|
<strong>{REPORT_TYPE_LABEL[t]}</strong>
|
||||||
|
<div className="chip-row">
|
||||||
|
{STATUSES.map((s) => <Badge key={s} tone={s === "APPROVED" ? "success" : s === "RETURNED" ? "danger" : s === "PENDING_AM" ? "warning" : "neutral"}>{STATUS_LABEL[s]}: {o.reports.counts[t]?.[s] ?? 0}</Badge>)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</CardBody>
|
||||||
|
</Card>
|
||||||
|
<ReportList title="Latest reports" rows={o.reports.recent} link={viewerRole === "GM"} />
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ReportList({ title, rows, link }: { title: string; rows: DcrListItem[]; link: boolean }) {
|
||||||
|
const cols: Column<DcrListItem>[] = [
|
||||||
|
{ key: "d", header: "Report date", render: (r) => link ? <Link to={`/reports/${r.id}`} className="text-link">{formatDate(r.report_date)}</Link> : formatDate(r.report_date), nowrap: true },
|
||||||
|
{ key: "t", header: "Report", render: (r) => <Badge>{r.report_type === "PLAN" ? "Plan" : r.report_type === "ACTUAL" ? "Done" : "Self"}</Badge> },
|
||||||
|
{ key: "p", header: "By", render: (r) => r.mr_name },
|
||||||
|
{ key: "h", header: "Headquarters", render: (r) => r.headquarters_name },
|
||||||
|
{ key: "v", header: "Visits", render: (r) => `${r.doctor_call_count} doctors · ${r.chemist_call_count} chemists`, nowrap: true },
|
||||||
|
{ key: "s", header: "Status", render: (r) => <StatusBadge status={r.status} type={r.report_type} /> },
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader title={title} />
|
||||||
|
<CardBody flush><DataTable columns={cols} rows={rows} rowKey={(r) => r.id} minWidth={640} empty={<EmptyState icon="file" title="No reports yet" />} /></CardBody>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Forms({ o }: { o: UserOverview }) {
|
||||||
|
const cols: Column<UserOverview["forms"][number]>[] = [
|
||||||
|
{ key: "l", header: "Company form", render: (f) => <Link to={`/forms/${f.table}`} className="text-link"><strong>{f.label}</strong></Link> },
|
||||||
|
{ key: "r", header: "Rows", render: (f) => f.rows, nowrap: true },
|
||||||
|
{ key: "m", header: "Months filled", render: (f) => (f.months.length ? f.months.join(", ") : <span className="muted">—</span>) },
|
||||||
|
{ key: "a", header: "Approval", render: (f): ReactNode => (f.approval_status ? <Badge tone={APPROVAL_TONE[f.approval_status]} dot>{APPROVAL_LABEL[f.approval_status]}</Badge> : <span className="muted">—</span>), nowrap: true },
|
||||||
|
];
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader title="Company forms" description="What they have filled in. Open a form to pick them under the MR filter." actions={<Link to="/forms"><Button size="sm">All forms</Button></Link>} />
|
||||||
|
<CardBody flush><DataTable columns={cols} rows={o.forms} rowKey={(f) => f.table} minWidth={560} /></CardBody>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { type FormEvent, useMemo, useState } from "react";
|
import { type FormEvent, useMemo, useState } from "react";
|
||||||
import { Alert } from "../../components/ui/Alert";
|
import { Alert } from "../../components/ui/Alert";
|
||||||
import { Field, Input } from "../../components/ui/Field";
|
import { Field, Input, Select } from "../../components/ui/Field";
|
||||||
import { Modal } from "../../components/ui/Modal";
|
import { Modal } from "../../components/ui/Modal";
|
||||||
import { Badge } from "../../components/ui/Badge";
|
import { Badge } from "../../components/ui/Badge";
|
||||||
import { Button } from "../../components/ui/Button";
|
import { Button } from "../../components/ui/Button";
|
||||||
@@ -14,11 +14,12 @@ import { useAsync } from "../../hooks/useAsync";
|
|||||||
import { api } from "../../api";
|
import { api } from "../../api";
|
||||||
import { LIVE } from "../../hooks/useAsync";
|
import { LIVE } from "../../hooks/useAsync";
|
||||||
import { HeadquartersChecklist } from "../../components/admin/HeadquartersChecklist";
|
import { HeadquartersChecklist } from "../../components/admin/HeadquartersChecklist";
|
||||||
import { headquartersOf } from "../../lib/headquarters";
|
import { areaManagersOf, headquartersOf } from "../../lib/headquarters";
|
||||||
import { code as codeRule, email as emailRule, maxLength, minLength, password as passwordRule, phone as phoneRule, required, useValidation } from "../../lib/validation";
|
import { code as codeRule, email as emailRule, maxLength, minLength, password as passwordRule, phone as phoneRule, required, useValidation } from "../../lib/validation";
|
||||||
import { ROLE_LABEL, errorMessage } from "../../lib/format";
|
import { ROLE_LABEL, errorMessage, isField } from "../../lib/format";
|
||||||
|
import { Link } from "../../lib/router";
|
||||||
import { useUser } from "../../lib/session";
|
import { useUser } from "../../lib/session";
|
||||||
import type { AreaManagerMapping, Headquarters, User } from "../../types";
|
import type { AreaManagerMapping, Headquarters, Role, User } from "../../types";
|
||||||
|
|
||||||
export function UsersPage() {
|
export function UsersPage() {
|
||||||
const me = useUser();
|
const me = useUser();
|
||||||
@@ -31,6 +32,7 @@ export function UsersPage() {
|
|||||||
const hqs = org.data?.hqs ?? [];
|
const hqs = org.data?.hqs ?? [];
|
||||||
const mappings = org.data?.mappings ?? [];
|
const mappings = org.data?.mappings ?? [];
|
||||||
const [query, setQuery] = useState("");
|
const [query, setQuery] = useState("");
|
||||||
|
const [hqFilter, setHqFilter] = useState("");
|
||||||
const canManage = me.role === "ADMIN";
|
const canManage = me.role === "ADMIN";
|
||||||
const [editing, setEditing] = useState<User | null>(null);
|
const [editing, setEditing] = useState<User | null>(null);
|
||||||
|
|
||||||
@@ -43,13 +45,15 @@ export function UsersPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const columns: Column<User>[] = [
|
const columns: Column<User>[] = [
|
||||||
{ key: "name", header: "Name", render: (u) => <strong>{u.full_name}</strong> },
|
{ key: "name", header: "Name", render: (u) => <Link to={`/users/${u.id}`} className="text-link"><strong>{u.full_name}</strong></Link> },
|
||||||
{ key: "email", header: "Email", render: (u) => u.email },
|
{ key: "email", header: "Email", render: (u) => u.email },
|
||||||
{ key: "code", header: "Code", render: (u) => u.employee_code, nowrap: true },
|
{ key: "code", header: "Code", render: (u) => u.employee_code, nowrap: true },
|
||||||
{ key: "role", header: "Role", render: (u) => <Badge tone="brand">{ROLE_LABEL[u.role]}</Badge>, nowrap: true },
|
{ key: "role", header: "Role", render: (u) => <Badge tone="brand">{u.is_superadmin ? "Super Admin" : ROLE_LABEL[u.role]}</Badge>, nowrap: true },
|
||||||
{ key: "hq", header: "Headquarters", render: (u) => <HqChips user={u} hqs={hqs} mappings={mappings} /> },
|
{ key: "hq", header: "Headquarters", render: (u) => <HqChips user={u} hqs={hqs} mappings={mappings} /> },
|
||||||
{ key: "status", header: "Status", render: (u) => <Badge tone={u.is_active ? "success" : "neutral"} dot>{u.is_active ? "Active" : "Inactive"}</Badge> },
|
{ key: "status", header: "Status", render: (u) => <Badge tone={u.is_active ? "success" : "neutral"} dot>{u.is_active ? "Active" : "Inactive"}</Badge> },
|
||||||
...(canManage ? [{ key: "action", header: "", align: "right" as const, nowrap: true, render: (u: User) => (
|
...(canManage ? [{ key: "action", header: "", align: "right" as const, nowrap: true, render: (u: User) => u.is_superadmin ? (
|
||||||
|
<Badge tone="neutral">Protected</Badge>
|
||||||
|
) : (
|
||||||
<span className="row-actions">
|
<span className="row-actions">
|
||||||
<Button size="sm" variant="ghost" icon="edit" onClick={() => setEditing(u)}>Edit</Button>
|
<Button size="sm" variant="ghost" icon="edit" onClick={() => setEditing(u)}>Edit</Button>
|
||||||
<Button size="sm" onClick={() => void toggle(u)} disabled={u.id === me.id}>{u.is_active ? "Deactivate" : "Activate"}</Button>
|
<Button size="sm" onClick={() => void toggle(u)} disabled={u.id === me.id}>{u.is_active ? "Deactivate" : "Activate"}</Button>
|
||||||
@@ -59,18 +63,28 @@ export function UsersPage() {
|
|||||||
const rows = useMemo(() => {
|
const rows = useMemo(() => {
|
||||||
const q = query.trim().toLowerCase();
|
const q = query.trim().toLowerCase();
|
||||||
return (users.data ?? []).filter((u) => {
|
return (users.data ?? []).filter((u) => {
|
||||||
if (!q) return true;
|
|
||||||
const place = headquartersOf(u, hqs, mappings);
|
const place = headquartersOf(u, hqs, mappings);
|
||||||
|
// One headquarters chosen: only the people who work in it (GM and Admin cover all, so they drop out).
|
||||||
|
if (hqFilter && !place.items.some((h) => h.id === hqFilter)) return false;
|
||||||
|
if (!q) return true;
|
||||||
const where = place.all ? "all headquarters" : place.items.map((h) => `${h.code} ${h.name}`).join(" ");
|
const where = place.all ? "all headquarters" : place.items.map((h) => `${h.code} ${h.name}`).join(" ");
|
||||||
return `${u.full_name} ${u.email} ${u.employee_code} ${u.role} ${where}`.toLowerCase().includes(q);
|
return `${u.full_name} ${u.email} ${u.employee_code} ${u.role} ${where}`.toLowerCase().includes(q);
|
||||||
});
|
});
|
||||||
}, [users.data, hqs, mappings, query]);
|
}, [users.data, hqs, mappings, query, hqFilter]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<PageHeader title="Users" description={canManage ? "Manage who can sign in and what they can do." : "View active and inactive users."} />
|
<PageHeader title="Users" description={canManage ? "Manage who can sign in and what they can do." : "View active and inactive users."} />
|
||||||
<Card>
|
<Card>
|
||||||
<div className="toolbar toolbar-end"><SearchInput value={query} onChange={setQuery} placeholder="Search users" /></div>
|
<div className="toolbar toolbar-end">
|
||||||
|
<div className="toolbar-group">
|
||||||
|
<Select className="hq-filter" value={hqFilter} onChange={(e) => setHqFilter(e.target.value)} aria-label="Filter by headquarters">
|
||||||
|
<option value="">All headquarters</option>
|
||||||
|
{[...hqs].sort((a, b) => a.name.localeCompare(b.name)).map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}
|
||||||
|
</Select>
|
||||||
|
<SearchInput value={query} onChange={setQuery} placeholder="Search users" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
{users.error
|
{users.error
|
||||||
? <ErrorState message={users.error} onRetry={() => void users.reload()} />
|
? <ErrorState message={users.error} onRetry={() => void users.reload()} />
|
||||||
: <DataTable columns={columns} rows={rows} rowKey={(u) => u.id} loading={users.loading} minWidth={860} empty={<EmptyState icon="users" title="No users found" />} />}
|
: <DataTable columns={columns} rows={rows} rowKey={(u) => u.id} loading={users.loading} minWidth={860} empty={<EmptyState icon="users" title="No users found" />} />}
|
||||||
@@ -96,12 +110,16 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
|
|||||||
const [phone, setPhone] = useState(user.phone ?? "");
|
const [phone, setPhone] = useState(user.phone ?? "");
|
||||||
const [password, setPassword] = useState("");
|
const [password, setPassword] = useState("");
|
||||||
const [showPassword, setShowPassword] = useState(false);
|
const [showPassword, setShowPassword] = useState(false);
|
||||||
const isAm = user.role === "AM";
|
const [role, setRole] = useState<Role>(user.role);
|
||||||
|
const [hqId, setHqId] = useState(user.headquarters_id ?? "");
|
||||||
|
const roleChanged = role !== user.role;
|
||||||
|
const isAm = role === "AM";
|
||||||
|
const hqChanged = !roleChanged && isField(user.role) && isField(role) && hqId !== (user.headquarters_id ?? "");
|
||||||
const editingSelf = user.id === me.id;
|
const editingSelf = user.id === me.id;
|
||||||
const credentialsChanged = email.trim().toLowerCase() !== user.email || password !== "";
|
const credentialsChanged = email.trim().toLowerCase() !== user.email || password !== "";
|
||||||
|
const [extras, setExtras] = useState<Set<string>>(() => new Set(user.extra_headquarter_ids ?? []));
|
||||||
const [picked, setPicked] = useState<Set<string>>(() => new Set(mappings.filter((m) => m.area_manager_user_id === user.id).map((m) => m.headquarters_id)));
|
const [picked, setPicked] = useState<Set<string>>(() => new Set(mappings.filter((m) => m.area_manager_user_id === user.id).map((m) => m.headquarters_id)));
|
||||||
const names = new Map(users.map((u) => [u.id, u.full_name]));
|
const owners = areaManagersOf(mappings, users, user.id);
|
||||||
const owners = Object.fromEntries(mappings.filter((m) => m.area_manager_user_id !== user.id).map((m) => [m.headquarters_id, names.get(m.area_manager_user_id) ?? "another Area Manager"]));
|
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
@@ -111,6 +129,7 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
|
|||||||
code: [required("Employee code"), maxLength(50, "Employee code"), codeRule("Employee code")],
|
code: [required("Employee code"), maxLength(50, "Employee code"), codeRule("Employee code")],
|
||||||
phone: [phoneRule],
|
phone: [phoneRule],
|
||||||
password: [passwordRule],
|
password: [passwordRule],
|
||||||
|
hq: [(value) => (isField(role) && !value ? "Headquarters is required" : null)],
|
||||||
});
|
});
|
||||||
const bind = (key: string, set: (value: string) => void) => ({
|
const bind = (key: string, set: (value: string) => void) => ({
|
||||||
onChange: (e: { target: { value: string } }) => { set(e.target.value); v.retouch(key, e.target.value); },
|
onChange: (e: { target: { value: string } }) => { set(e.target.value); v.retouch(key, e.target.value); },
|
||||||
@@ -119,7 +138,7 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
|
|||||||
|
|
||||||
async function submit(e: FormEvent<HTMLFormElement>) {
|
async function submit(e: FormEvent<HTMLFormElement>) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!v.check({ name, email, code, phone, password }, e.currentTarget)) return;
|
if (!v.check({ name, email, code, phone, password, hq: hqId }, e.currentTarget)) return;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
@@ -128,6 +147,10 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
|
|||||||
if (code.trim() !== user.employee_code) payload.employee_code = code.trim();
|
if (code.trim() !== user.employee_code) payload.employee_code = code.trim();
|
||||||
if (phone.trim() !== (user.phone ?? "")) payload.phone = phone.trim() || null;
|
if (phone.trim() !== (user.phone ?? "")) payload.phone = phone.trim() || null;
|
||||||
if (password) payload.password = password;
|
if (password) payload.password = password;
|
||||||
|
if (roleChanged) payload.role = role;
|
||||||
|
if (isField(role) && (roleChanged || hqId !== user.headquarters_id)) payload.headquarters_id = hqId;
|
||||||
|
else if (roleChanged) payload.headquarters_id = null;
|
||||||
|
if (role === "SFE") payload.extra_headquarter_ids = [...extras].filter((id) => id !== hqId);
|
||||||
await api.updateUser(user.id, payload);
|
await api.updateUser(user.id, payload);
|
||||||
if (isAm) await api.setAreaManagerHeadquarters(user.id, [...picked]);
|
if (isAm) await api.setAreaManagerHeadquarters(user.id, [...picked]);
|
||||||
onSaved();
|
onSaved();
|
||||||
@@ -151,6 +174,14 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
|
|||||||
<Field label="Full name" required error={v.errors.name}><Input value={name} {...bind("name", setName)} /></Field>
|
<Field label="Full name" required error={v.errors.name}><Input value={name} {...bind("name", setName)} /></Field>
|
||||||
<Field label="Email (sign-in)" required error={v.errors.email}><Input type="email" value={email} autoComplete="off" {...bind("email", setEmail)} /></Field>
|
<Field label="Email (sign-in)" required error={v.errors.email}><Input type="email" value={email} autoComplete="off" {...bind("email", setEmail)} /></Field>
|
||||||
<Field label="Employee code" required error={v.errors.code}><Input value={code} {...bind("code", setCode)} /></Field>
|
<Field label="Employee code" required error={v.errors.code}><Input value={code} {...bind("code", setCode)} /></Field>
|
||||||
|
{isField(role) && (
|
||||||
|
<Field label="Headquarters" required error={v.errors.hq} hint="The headquarters this Medical Representative works in. You can change it any time.">
|
||||||
|
<Select value={hqId} onChange={(e) => { setHqId(e.target.value); v.retouch("hq", e.target.value); }}>
|
||||||
|
<option value="">Choose headquarters</option>
|
||||||
|
{hqs.map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
<Field label="Phone" error={v.errors.phone}><Input value={phone} inputMode="tel" {...bind("phone", setPhone)} /></Field>
|
<Field label="Phone" error={v.errors.phone}><Input value={phone} inputMode="tel" {...bind("phone", setPhone)} /></Field>
|
||||||
<Field label="New password" error={v.errors.password} hint="Leave empty to keep the current password. At least 8 characters, with a letter and a number.">
|
<Field label="New password" error={v.errors.password} hint="Leave empty to keep the current password. At least 8 characters, with a letter and a number.">
|
||||||
<span className="input-row">
|
<span className="input-row">
|
||||||
@@ -159,15 +190,35 @@ function UserEditor({ user, hqs, mappings, users, onClose, onSaved }: { user: Us
|
|||||||
<Button size="sm" onClick={() => { setPassword(generatePassword()); setShowPassword(true); }}>Generate</Button>
|
<Button size="sm" onClick={() => { setPassword(generatePassword()); setShowPassword(true); }}>Generate</Button>
|
||||||
</span>
|
</span>
|
||||||
</Field>
|
</Field>
|
||||||
|
<Field label="Role" hint={editingSelf ? "You cannot change your own role." : undefined}>
|
||||||
|
<Select value={role} disabled={editingSelf} onChange={(e) => setRole(e.target.value as Role)}>
|
||||||
|
{(Object.keys(ROLE_LABEL) as Role[]).map((r) => <option key={r} value={r}>{ROLE_LABEL[r]}</option>)}
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
{roleChanged && (
|
||||||
|
<Alert tone="warning">
|
||||||
|
{user.full_name} will be signed out and must sign in again as {ROLE_LABEL[role]}.
|
||||||
|
{isField(user.role) && " Their doctor and chemist assignments end, so reassign them in Setup → Assignments."}
|
||||||
|
{user.role === "AM" && " The headquarters they manage are released; any that have no other Area Manager need a new one."}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
{hqChanged && (
|
||||||
|
<Alert tone="warning">{user.full_name} moves to the new headquarters. Their current doctor and chemist assignments end, so reassign them in Setup → Assignments. Their forms then show the new headquarters.</Alert>
|
||||||
|
)}
|
||||||
{credentialsChanged && (
|
{credentialsChanged && (
|
||||||
<Alert tone="warning">{editingSelf ? "You are changing your own sign-in details — you will need to sign in again. " : ""}{user.full_name} will be signed out everywhere{password ? " and must use the new password" : ""}. Share the new details securely.</Alert>
|
<Alert tone="warning">{editingSelf ? "You are changing your own sign-in details — you will need to sign in again. " : ""}{user.full_name} will be signed out everywhere{password ? " and must use the new password" : ""}. Share the new details securely.</Alert>
|
||||||
)}
|
)}
|
||||||
|
{role === "SFE" && (
|
||||||
|
<Field label="Other districts they cover" group hint={`${[...extras].filter((id) => id !== hqId).length} selected. They can visit doctors and chemists of these headquarters too; reports still go to the main headquarters' Area Manager.`}>
|
||||||
|
<HeadquartersChecklist headquarters={hqs.filter((h) => h.id !== hqId)} selected={extras} onChange={setExtras} />
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
{isAm && (
|
{isAm && (
|
||||||
<Field label="Headquarters they manage" group hint={`${picked.size} selected. Ticking one managed by someone else moves it here.`}>
|
<Field label="Headquarters they manage" group hint={`${picked.size} selected. A headquarters can have several Area Managers; the others keep theirs.`}>
|
||||||
<HeadquartersChecklist headquarters={hqs} selected={picked} onChange={setPicked} owners={owners} />
|
<HeadquartersChecklist headquarters={hqs} selected={picked} onChange={setPicked} owners={owners} />
|
||||||
</Field>
|
</Field>
|
||||||
)}
|
)}
|
||||||
{(user.role === "GM" || user.role === "ADMIN") && <p className="field-hint">This role sees every headquarters, so none is assigned.</p>}
|
{(role === "GM" || role === "ADMIN") && <p className="field-hint">This role sees every headquarters, so none is assigned.</p>}
|
||||||
</form>
|
</form>
|
||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -10,22 +10,45 @@ import { EmptyState, ErrorState, Skeleton } from "../../components/ui/States";
|
|||||||
import { useToast } from "../../components/ui/Toast";
|
import { useToast } from "../../components/ui/Toast";
|
||||||
import { LIVE, useAsync } from "../../hooks/useAsync";
|
import { LIVE, useAsync } from "../../hooks/useAsync";
|
||||||
import { api } from "../../api";
|
import { api } from "../../api";
|
||||||
import { columnLabel, errorMessage, formatDate } from "../../lib/format";
|
import { columnLabel, errorMessage, formatDate, isField } from "../../lib/format";
|
||||||
import { Link } from "../../lib/router";
|
import { Link } from "../../lib/router";
|
||||||
import { useUser } from "../../lib/session";
|
import { useUser } from "../../lib/session";
|
||||||
import type { CsvRow, CsvTable, FormApproval } from "../../types";
|
import type { CsvRow, CsvTable, FormApproval } from "../../types";
|
||||||
import { APPROVAL_FORMS, APPROVAL_POLL_MS } from "./approval";
|
import { APPROVAL_FORMS, APPROVAL_POLL_MS } from "./approval";
|
||||||
|
import { INLINE_COLUMNS, screenColumns } from "./layout";
|
||||||
|
import { InlineCell } from "./InlineCell";
|
||||||
import { RowEditor } from "./RowEditor";
|
import { RowEditor } from "./RowEditor";
|
||||||
|
|
||||||
const IDENTITY = new Set(["name", "employee_name", "headquarter"]);
|
const IDENTITY = new Set(["name", "employee_name", "headquarter"]);
|
||||||
const SERIAL = new Set(["serial_no", "doctor_sr_no", "chemist_sr_no"]);
|
const SERIAL = new Set(["serial_no", "doctor_sr_no", "chemist_sr_no"]);
|
||||||
const DATES = new Set(["report_date", "date_of_visit"]);
|
const DATES = new Set(["report_date", "date_of_visit"]);
|
||||||
|
/** "2026-10-13" -> "13": the Core Doctor Call Conversion form shows only the day of the month. */
|
||||||
|
const dayOfMonth = (iso: string) => (/^\d{4}-\d{2}-\d{2}/.test(iso) ? String(Number(iso.slice(8, 10))) : iso);
|
||||||
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
||||||
const sameMonth = (a: unknown, b: string) => String(a ?? "").trim().toLowerCase() === b.trim().toLowerCase();
|
const sameMonth = (a: unknown, b: string) => String(a ?? "").trim().toLowerCase() === b.trim().toLowerCase();
|
||||||
|
/** The month a row belongs to: its own Month column, else the month of its date. */
|
||||||
|
const rowMonth = (r: CsvRow): string => {
|
||||||
|
const m = String(r.month ?? "").trim();
|
||||||
|
if (m) return m;
|
||||||
|
const d = String(r.report_date ?? "").trim();
|
||||||
|
if (!d) return "";
|
||||||
|
const iso = /^(\d{4})-(\d{2})/.exec(d);
|
||||||
|
if (iso) return MONTHS[Number(iso[2]) - 1] ?? "";
|
||||||
|
const dmy = /^(\d{1,2})[/.-](\d{1,2})[/.-](\d{2,4})/.exec(d);
|
||||||
|
if (dmy) return MONTHS[Number(dmy[2]) - 1] ?? "";
|
||||||
|
const t = new Date(d);
|
||||||
|
return Number.isNaN(t.getTime()) ? "" : MONTHS[t.getMonth()]!;
|
||||||
|
};
|
||||||
/** Tables whose stored Sl. No. restarts at 1 for each month (see MONTH_NUMBERED_TABLES in
|
/** Tables whose stored Sl. No. restarts at 1 for each month (see MONTH_NUMBERED_TABLES in
|
||||||
* app/csv_data/router.py) — so it only means something within one chosen month. Viewed across
|
* app/csv_data/router.py) — so it only means something within one chosen month. Viewed across
|
||||||
* "All months" it would repeat 1, 1, 1…, so that view counts fresh over what's actually shown. */
|
* "All months" it would repeat 1, 1, 1…, so that view counts fresh over what's actually shown. */
|
||||||
const MONTH_NUMBERED_TABLES = new Set(["sales_projection"]);
|
const MONTH_NUMBERED_TABLES = new Set(["sales_projection", "sales_and_stock_statement"]);
|
||||||
|
/** Forms that are the company's product list: picking a month always shows every product, with
|
||||||
|
* that month's figures filled in where there are some and blank boxes where there are none. */
|
||||||
|
const PRODUCT_LIST_TABLES = new Set(["sales_projection", "sales_and_stock_statement"]);
|
||||||
|
const PRODUCT_COLUMNS = ["pts", "value_in_pts"];
|
||||||
|
const NEW_ROW = "new:";
|
||||||
|
const isNewRow = (r: CsvRow) => String(r.id).startsWith(NEW_ROW);
|
||||||
|
|
||||||
export function FormsPage({ table: routeTable }: { table?: string }) {
|
export function FormsPage({ table: routeTable }: { table?: string }) {
|
||||||
const user = useUser();
|
const user = useUser();
|
||||||
@@ -37,53 +60,96 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
|
|
||||||
const approvals = useAsync(api.formApprovals, [], { poll: APPROVAL_POLL_MS });
|
const approvals = useAsync(api.formApprovals, [], { poll: APPROVAL_POLL_MS });
|
||||||
const needsApproval = !!table && APPROVAL_FORMS.has(table.name);
|
const needsApproval = !!table && APPROVAL_FORMS.has(table.name);
|
||||||
const isManager = user.role === "AM" || user.role === "ADMIN";
|
const isManager = user.role === "AM" || user.role === "ADMIN" || user.role === "GM";
|
||||||
|
// Admin and the General Manager look across every medical representative; the GM only reads.
|
||||||
|
const seesAll = user.role === "ADMIN" || user.role === "GM";
|
||||||
// Each MR has their own copy of these forms. An Area Manager (or admin) opens one MR's copy at a time.
|
// Each MR has their own copy of these forms. An Area Manager (or admin) opens one MR's copy at a time.
|
||||||
const owners = useAsync(() => (isManager && needsApproval ? api.formOwners() : Promise.resolve([])), [isManager, needsApproval], { poll: LIVE });
|
// Sales Projection isn't an approval form but managers still pick a headquarters / MR to look at.
|
||||||
|
const hasPeopleFilter = isManager && (needsApproval || seesAll);
|
||||||
|
const owners = useAsync(() => (hasPeopleFilter ? api.formOwners() : Promise.resolve([])), [hasPeopleFilter], { poll: LIVE });
|
||||||
|
const [hqChoice, setHqChoice] = useState("");
|
||||||
|
const [mrChoice, setMrChoice] = useState("");
|
||||||
const [ownerChoice, setOwnerChoice] = useState("");
|
const [ownerChoice, setOwnerChoice] = useState("");
|
||||||
const [monthChoice, setMonthChoice] = useState<Record<string, string>>({});
|
const [monthChoice, setMonthChoice] = useState<Record<string, string>>({});
|
||||||
const pendingFor = (tableName: string, ownerId: string) => approvals.data?.some((a) => a.table_name === tableName && a.owner_user_id === ownerId && a.status === "pending") ?? false;
|
const pendingFor = (tableName: string, ownerId: string) => approvals.data?.some((a) => a.table_name === tableName && a.owner_user_id === ownerId && a.status === "pending") ?? false;
|
||||||
const ownerList = owners.data ?? [];
|
const ownerList = owners.data ?? [];
|
||||||
const viewOwner = useMemo(() => {
|
const viewOwner = useMemo(() => {
|
||||||
if (!isManager || !needsApproval || !table) return undefined;
|
if (!isManager || !needsApproval || !table) return undefined;
|
||||||
const chosen = ownerList.find((o) => o.id === ownerChoice);
|
const chosen = ownerList.find((o) => o.id === (seesAll ? mrChoice : ownerChoice));
|
||||||
if (chosen) return chosen;
|
if (chosen) return chosen;
|
||||||
// An Area Manager lands on the MR who is waiting for them; an admin starts with everyone.
|
// An Area Manager lands on the MR who is waiting for them; an admin starts with everyone.
|
||||||
return user.role === "AM" ? ownerList.find((o) => pendingFor(table.name, o.id)) ?? ownerList[0] : undefined;
|
return user.role === "AM" ? ownerList.find((o) => pendingFor(table.name, o.id)) ?? ownerList[0] : undefined;
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [isManager, needsApproval, table?.name, ownerList, ownerChoice, user.role, approvals.data]);
|
}, [isManager, needsApproval, table?.name, ownerList, ownerChoice, mrChoice, seesAll, user.role, approvals.data]);
|
||||||
const waitingForOwners = isManager && needsApproval && !owners.data;
|
const waitingForOwners = isManager && needsApproval && !owners.data;
|
||||||
|
|
||||||
const rows = useAsync<CsvRow[]>(
|
const rows = useAsync<CsvRow[]>(
|
||||||
() => (table && !waitingForOwners ? api.csvRows(table.name, viewOwner?.id) : Promise.resolve([])),
|
() => (table && !waitingForOwners ? api.csvRows(table.name, viewOwner?.id ?? (seesAll && PRODUCT_LIST_TABLES.has(table.name) ? mrChoice || undefined : undefined)) : Promise.resolve([])),
|
||||||
[table?.name, viewOwner?.id, waitingForOwners], { poll: LIVE },
|
[table?.name, viewOwner?.id, mrChoice, waitingForOwners], { poll: LIVE },
|
||||||
);
|
);
|
||||||
const [acting, setActing] = useState(false);
|
const [acting, setActing] = useState(false);
|
||||||
const [editing, setEditing] = useState<{ row: CsvRow | null } | null>(null);
|
const [editing, setEditing] = useState<{ row: CsvRow | null } | null>(null);
|
||||||
const [deleting, setDeleting] = useState<CsvRow | null>(null);
|
const [deleting, setDeleting] = useState<CsvRow | null>(null);
|
||||||
|
|
||||||
const canEdit = user.role === "MR" || user.role === "ADMIN";
|
const canEdit = isField(user.role) || user.role === "ADMIN";
|
||||||
// Only an admin may delete a row — an MR can edit their own forms but not remove rows from them.
|
// Forms whose figures are typed straight into the table: those cells are boxes, and an MR
|
||||||
const canDelete = user.role === "ADMIN";
|
// has no Edit drawer (the admin keeps it, to change the product list itself).
|
||||||
|
const inline = table ? INLINE_COLUMNS[table.name] : undefined;
|
||||||
|
const showEdit = canEdit && !(inline && isField(user.role));
|
||||||
|
|
||||||
|
async function saveCell(row: CsvRow, column: string, value: string): Promise<boolean> {
|
||||||
|
if (!table) return false;
|
||||||
|
try {
|
||||||
|
if (isNewRow(row)) {
|
||||||
|
// A product with nothing yet in this month: the first figure typed creates its row.
|
||||||
|
const seed: Record<string, string> = { product_name: String(row.product_name ?? ""), month: String(row.month ?? ""), [column]: value };
|
||||||
|
for (const c of PRODUCT_COLUMNS) if (table.columns.includes(c) && row[c] !== undefined && c !== column) seed[c] = String(row[c]);
|
||||||
|
await api.createCsvRow(table.name, seed);
|
||||||
|
await rows.reload();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// A product's blank row picked up in a month belongs to that month from now on.
|
||||||
|
const claims: Record<string, string> = month && column !== "month" && !String(row.month ?? "").trim() ? { month } : {};
|
||||||
|
const saved = await api.updateCsvRow(table.name, row.id, { [column]: value, ...claims });
|
||||||
|
rows.setData((rows.data ?? []).map((r) => (r.id === row.id ? { ...r, ...saved } : r)));
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(errorMessage(e, "Could not save the value"));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Anyone who fills a form in can remove a row entered by mistake (an MR only their own; the
|
||||||
|
// server checks). On a shared product list an MR removes an extra copy of a product whole, but
|
||||||
|
// a product's only row stays for everyone — there they clear their figures instead.
|
||||||
|
const canDelete = canEdit;
|
||||||
|
const productKey = (r: CsvRow) => String(r.product_name ?? "").trim().toUpperCase();
|
||||||
|
const copies = useMemo(() => {
|
||||||
|
const count = new Map<string, number>();
|
||||||
|
for (const r of rows.data ?? []) count.set(productKey(r), (count.get(productKey(r)) ?? 0) + 1);
|
||||||
|
return count;
|
||||||
|
}, [rows.data]);
|
||||||
|
const clearsInstead = (r: CsvRow) => !!inline && isField(user.role) && (copies.get(productKey(r)) ?? 0) < 2;
|
||||||
|
const hasFigures = (r: CsvRow) => [...(inline ?? [])].some((c) => String(r[c] ?? "").trim());
|
||||||
// An admin adds rows on behalf of one chosen MR.
|
// An admin adds rows on behalf of one chosen MR.
|
||||||
const canAdd = canEdit && (!needsApproval || user.role === "MR" || !!viewOwner);
|
const canAdd = canEdit && (!needsApproval || isField(user.role) || !!viewOwner);
|
||||||
const subjectId = user.role === "MR" ? user.id : viewOwner?.id;
|
const subjectId = isField(user.role) ? user.id : viewOwner?.id;
|
||||||
const approval = table && subjectId ? approvals.data?.find((a) => a.table_name === table.name && a.owner_user_id === subjectId) : undefined;
|
const approval = table && subjectId ? approvals.data?.find((a) => a.table_name === table.name && a.owner_user_id === subjectId) : undefined;
|
||||||
const hasRows = (rows.data?.length ?? 0) > 0;
|
const hasRows = (rows.data?.length ?? 0) > 0;
|
||||||
const status: FormApproval["status"] = hasRows ? approval?.status ?? "draft" : "draft"; // an empty form has nothing to approve
|
const status: FormApproval["status"] = hasRows ? approval?.status ?? "draft" : "draft"; // an empty form has nothing to approve
|
||||||
// Only the controls that make sense right now: nothing to approve means nothing to show.
|
// Only the controls that make sense right now: nothing to approve means nothing to show.
|
||||||
const canSend = needsApproval && user.role === "MR" && status === "draft" && hasRows;
|
const canSend = needsApproval && isField(user.role) && status === "draft" && hasRows;
|
||||||
const canApprove = needsApproval && user.role === "AM" && status === "pending" && !!viewOwner;
|
const canApprove = needsApproval && user.role === "AM" && status === "pending" && !!viewOwner;
|
||||||
const showStatus = needsApproval && (status === "pending" || status === "approved");
|
const showStatus = needsApproval && (status === "pending" || status === "approved");
|
||||||
|
|
||||||
// Forms with a month can be downloaded one month at a time. Every month is always offered —
|
// Forms with a month can be downloaded one month at a time. Every month is always offered —
|
||||||
// not just ones with rows already in them — so choosing next month before anyone has filled
|
// not just ones with rows already in them — so choosing next month before anyone has filled
|
||||||
// it in is a normal, working choice, not something hidden until data happens to exist.
|
// it in is a normal, working choice, not something hidden until data happens to exist.
|
||||||
const hasMonth = !!table?.columns.includes("month");
|
const hasMonthColumn = !!table?.columns.includes("month");
|
||||||
|
const hasMonth = hasMonthColumn || !!table?.columns.includes("report_date");
|
||||||
const monthsWithRows = useMemo(() => {
|
const monthsWithRows = useMemo(() => {
|
||||||
if (!hasMonth) return [] as string[];
|
if (!hasMonth) return [] as string[];
|
||||||
const seen = new Map<string, string>();
|
const seen = new Map<string, string>();
|
||||||
for (const r of rows.data ?? []) { const m = String(r.month ?? "").trim(); if (m && !seen.has(m.toLowerCase())) seen.set(m.toLowerCase(), m); }
|
for (const r of rows.data ?? []) { const m = rowMonth(r); if (m && !seen.has(m.toLowerCase())) seen.set(m.toLowerCase(), m); }
|
||||||
const rank = (m: string) => { const i = MONTHS.findIndex((x) => sameMonth(x, m)); return i < 0 ? 99 : i; };
|
const rank = (m: string) => { const i = MONTHS.findIndex((x) => sameMonth(x, m)); return i < 0 ? 99 : i; };
|
||||||
return [...seen.values()].sort((a, b) => rank(a) - rank(b) || a.localeCompare(b));
|
return [...seen.values()].sort((a, b) => rank(a) - rank(b) || a.localeCompare(b));
|
||||||
}, [hasMonth, rows.data]);
|
}, [hasMonth, rows.data]);
|
||||||
@@ -92,22 +158,67 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
// Starts on the current month when the form already has rows for it, otherwise on everything.
|
// Starts on the current month when the form already has rows for it, otherwise on everything.
|
||||||
// Any of the twelve real months is a valid choice, whether or not it has rows yet.
|
// Any of the twelve real months is a valid choice, whether or not it has rows yet.
|
||||||
const month = chosenMonth !== undefined ? (chosenMonth === "" || MONTHS.some((m) => sameMonth(m, chosenMonth)) ? chosenMonth : "") : monthsWithRows.find((m) => sameMonth(m, thisMonth)) ?? "";
|
const month = chosenMonth !== undefined ? (chosenMonth === "" || MONTHS.some((m) => sameMonth(m, chosenMonth)) ? chosenMonth : "") : monthsWithRows.find((m) => sameMonth(m, thisMonth)) ?? "";
|
||||||
const shownRows = month ? (rows.data ?? []).filter((r) => sameMonth(r.month, month)) : rows.data ?? [];
|
// The General Manager and Admin can narrow every form by headquarters and medical representative.
|
||||||
const showToolbar = hasMonth || (isManager && needsApproval);
|
const peopleFilter = seesAll;
|
||||||
|
// Forms kept per MR on the server are narrowed there; the rest by the name and headquarters written on each row.
|
||||||
|
const narrowedByServer = !!mrChoice && !!table && (needsApproval || PRODUCT_LIST_TABLES.has(table.name));
|
||||||
|
const hqOptions = useMemo(() => [...new Set(ownerList.map((o) => o.headquarters_name).filter((h): h is string => !!h))].sort(), [ownerList]);
|
||||||
|
const mrOptions = ownerList.filter((o) => !hqChoice || sameMonth(o.headquarters_name, hqChoice));
|
||||||
|
const mrName = mrOptions.find((o) => o.id === mrChoice)?.name;
|
||||||
|
const isProductList = !!table && PRODUCT_LIST_TABLES.has(table.name);
|
||||||
|
const shownRows = useMemo(() => {
|
||||||
|
const base = (rows.data ?? []).filter((r) => !peopleFilter || narrowedByServer || (isProductList && !String(r.name ?? "").trim() && !String(r.headquarter ?? "").trim()) || ((!hqChoice || sameMonth(r.headquarter, hqChoice)) && (!mrName || sameMonth(r.name ?? r.employee_name, mrName))));
|
||||||
|
// "All MRs": the rows MRs have entered; for a month, every product of the list is there too, blank where nobody has entered it.
|
||||||
|
const listAcrossMrs = isProductList && peopleFilter && !mrChoice;
|
||||||
|
if (listAcrossMrs && user.role === "GM" && !month) return base.filter((r) => String(r.month ?? "").trim());
|
||||||
|
if (!month) return base;
|
||||||
|
if (listAcrossMrs) {
|
||||||
|
const key = (r: CsvRow) => String(r.product_name ?? "").trim().toUpperCase();
|
||||||
|
const order: string[] = [];
|
||||||
|
const entered = new Map<string, CsvRow[]>();
|
||||||
|
for (const r of base) {
|
||||||
|
if (!key(r)) continue;
|
||||||
|
if (!order.includes(key(r))) order.push(key(r));
|
||||||
|
if (sameMonth(r.month, month)) entered.set(key(r), [...(entered.get(key(r)) ?? []), r]);
|
||||||
|
}
|
||||||
|
// What MRs have entered comes first; the products nobody has filled in yet follow.
|
||||||
|
const blank = order.filter((k) => !entered.has(k)).map((k) => ({ id: NEW_ROW + k, source_row_number: 0, product_name: base.find((r) => key(r) === k)!.product_name, month, name: "", headquarter: "" } as CsvRow));
|
||||||
|
return [...order.flatMap((k) => entered.get(k) ?? []), ...blank];
|
||||||
|
}
|
||||||
|
// "All MRs": the rows that were actually entered. One MR picked: their whole product list for the month, blank lines included.
|
||||||
|
if (!isProductList || (peopleFilter && !mrChoice)) return base.filter((r) => sameMonth(rowMonth(r), month));
|
||||||
|
// Every product, once: its row for this month, else its still-unused blank row, else an empty
|
||||||
|
// placeholder that becomes a real row when a figure is typed into it.
|
||||||
|
const key = (r: CsvRow) => String(r.product_name ?? "").trim().toUpperCase();
|
||||||
|
const products = new Map<string, CsvRow[]>();
|
||||||
|
for (const r of base) if (key(r)) products.set(key(r), [...(products.get(key(r)) ?? []), r]);
|
||||||
|
return [...products.entries()].map(([k, copies]) => {
|
||||||
|
const mine = copies.find((r) => sameMonth(r.month, month)) ?? copies.find((r) => !String(r.month ?? "").trim());
|
||||||
|
if (mine) return mine;
|
||||||
|
const first = copies[0]!;
|
||||||
|
const seed: CsvRow = { id: NEW_ROW + k, source_row_number: 0, product_name: first.product_name, month };
|
||||||
|
for (const c of PRODUCT_COLUMNS) if (first[c] !== undefined) seed[c] = first[c];
|
||||||
|
return seed;
|
||||||
|
});
|
||||||
|
}, [rows.data, month, isProductList, peopleFilter, narrowedByServer, mrChoice, hqChoice, mrName]);
|
||||||
|
const showToolbar = hasMonth || peopleFilter || (isManager && needsApproval);
|
||||||
|
|
||||||
// Across "All months" a month-numbered table's own Sl. No. would repeat per month, so number
|
// Across "All months" a month-numbered table's own Sl. No. would repeat per month, so number
|
||||||
// by position in the list actually on screen instead; a single chosen month already has its
|
// by position in the list actually on screen instead; a single chosen month already has its
|
||||||
// own correct running numbers from the server, so those are kept as stored.
|
// own correct running numbers from the server, so those are kept as stored.
|
||||||
const continuousNumbering = !!table && MONTH_NUMBERED_TABLES.has(table.name) && !month;
|
const continuousNumbering = !!table && MONTH_NUMBERED_TABLES.has(table.name) && (!month || isProductList);
|
||||||
|
// A form with no Sl. No. column of its own would otherwise show the table-wide row id, which has
|
||||||
|
// gaps wherever another month or MR has rows in between — so it counts what is on screen instead.
|
||||||
|
const positional = continuousNumbering || (!!table && !table.columns.includes("serial_no"));
|
||||||
const positionOf = useMemo(() => new Map(shownRows.map((r, i) => [r.id, i + 1] as const)), [shownRows]);
|
const positionOf = useMemo(() => new Map(shownRows.map((r, i) => [r.id, i + 1] as const)), [shownRows]);
|
||||||
const numberOf = (r: CsvRow) => String(continuousNumbering ? positionOf.get(r.id) ?? "" : r.serial_no ?? r.source_row_number);
|
const numberOf = (r: CsvRow) => String(positional ? positionOf.get(r.id) ?? "" : r.serial_no ?? r.source_row_number);
|
||||||
|
|
||||||
/** Send (MR) or approve (AM). The screen changes at once; the server's answer confirms it, or undoes it. */
|
/** Send (MR) or approve (AM). The screen changes at once; the server's answer confirms it, or undoes it. */
|
||||||
async function act(kind: "request" | "approve") {
|
async function act(kind: "request" | "approve") {
|
||||||
if (!table || acting) return;
|
if (!table || acting) return;
|
||||||
const name = table.name;
|
const name = table.name;
|
||||||
const before = approvals.data ?? [];
|
const before = approvals.data ?? [];
|
||||||
const ownerId = user.role === "MR" ? user.id : viewOwner?.id;
|
const ownerId = isField(user.role) ? user.id : viewOwner?.id;
|
||||||
if (!ownerId) return;
|
if (!ownerId) return;
|
||||||
const base = { table_name: name, owner_user_id: ownerId, owner_name: viewOwner?.name ?? user.full_name, headquarters_name: viewOwner?.headquarters_name ?? null, updated_at: null };
|
const base = { table_name: name, owner_user_id: ownerId, owner_name: viewOwner?.name ?? user.full_name, headquarters_name: viewOwner?.headquarters_name ?? null, updated_at: null };
|
||||||
const next: FormApproval = kind === "request"
|
const next: FormApproval = kind === "request"
|
||||||
@@ -134,34 +245,65 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
|
|
||||||
async function confirmDelete() {
|
async function confirmDelete() {
|
||||||
if (!table || !deleting) return;
|
if (!table || !deleting) return;
|
||||||
|
const clearing = clearsInstead(deleting);
|
||||||
try {
|
try {
|
||||||
|
if (clearing) {
|
||||||
|
await api.updateCsvRow(table.name, deleting.id, Object.fromEntries([...(inline ?? [])].map((c) => [c, ""])));
|
||||||
|
toast.success("Figures cleared");
|
||||||
|
} else {
|
||||||
await api.deleteCsvRow(table.name, deleting.id);
|
await api.deleteCsvRow(table.name, deleting.id);
|
||||||
toast.success("Row deleted");
|
toast.success("Row removed");
|
||||||
|
}
|
||||||
setDeleting(null);
|
setDeleting(null);
|
||||||
await Promise.all([rows.reload(), approvals.reload()]);
|
await Promise.all([rows.reload(), approvals.reload()]);
|
||||||
} catch (e) { toast.error(errorMessage(e, "Could not delete the row")); }
|
} catch (e) { toast.error(errorMessage(e, clearing ? "Could not clear the row" : "Could not remove the row")); }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Sales Projection: a Total row combining every row on screen (the chosen month, and for
|
||||||
|
// managers every medical representative shown).
|
||||||
|
const footer = useMemo(() => {
|
||||||
|
if (table?.name === "field_activity_report") {
|
||||||
|
// Average calls per working day: total calls ÷ the number of distinct dates worked.
|
||||||
|
const days = new Set(shownRows.filter((r) => String(r.report_date ?? "").trim()).map((r) => String(r.report_date).slice(0, 10))).size;
|
||||||
|
const avg = (c: string) => {
|
||||||
|
const total = shownRows.reduce((t, r) => { const n = Number(String(r[c] ?? "").replace(/,/g, "").trim()); return Number.isFinite(n) ? t + n : t; }, 0);
|
||||||
|
return days ? String(Math.round((total / days) * 100) / 100) : "";
|
||||||
|
};
|
||||||
|
return { station_worked: `AVERAGE per working day (${days} day${days === 1 ? "" : "s"})`, no_of_doctors_called: avg("no_of_doctors_called"), no_of_chemists_pds_called: avg("no_of_chemists_pds_called") };
|
||||||
|
}
|
||||||
|
if (table?.name !== "sales_projection") return undefined;
|
||||||
|
const sum = (c: string) => shownRows.reduce((t, r) => { const n = Number(String(r[c] ?? "").replace(/,/g, "").trim()); return Number.isFinite(n) ? t + n : t; }, 0);
|
||||||
|
const out: Record<string, string> = { product_name: "TOTAL" };
|
||||||
|
for (const c of ["closing_qty", "closing_value", "projection_qty", "projection_value"]) out[c] = sum(c).toLocaleString("en-IN", { maximumFractionDigits: 2 });
|
||||||
|
return out;
|
||||||
|
}, [table?.name, shownRows]);
|
||||||
|
|
||||||
const columns: Column<CsvRow>[] = table ? [
|
const columns: Column<CsvRow>[] = table ? [
|
||||||
{ key: "_no", header: "No.", render: numberOf, width: "64px" },
|
{ key: "_no", header: "No.", render: numberOf, width: "64px" },
|
||||||
...table.columns
|
...screenColumns(table, user.role)
|
||||||
.filter((c) => !SERIAL.has(c) && !(user.role !== "ADMIN" && IDENTITY.has(c)))
|
.filter((c) => !SERIAL.has(c) && !(!seesAll && IDENTITY.has(c)))
|
||||||
.map<Column<CsvRow>>((c) => ({
|
.map<Column<CsvRow>>((c) => ({
|
||||||
key: c,
|
key: c,
|
||||||
header: columnLabel(c),
|
header: columnLabel(c),
|
||||||
nowrap: true,
|
nowrap: true,
|
||||||
render: (r) => {
|
render: (r) => {
|
||||||
const value = String(r[c] ?? "");
|
const value = String(r[c] ?? "");
|
||||||
return value ? (DATES.has(c) ? formatDate(value) : value) : <span className="muted">—</span>;
|
if (c === "month" && month && isProductList) return value || <span className="muted">—</span>;
|
||||||
|
if (canEdit && inline?.has(c)) return <InlineCell value={value} column={c} onSave={(v) => saveCell(r, c, v)} />;
|
||||||
|
return value ? (c === "date_of_visit" ? dayOfMonth(value) : DATES.has(c) ? formatDate(value) : value) : <span className="muted">—</span>;
|
||||||
},
|
},
|
||||||
})),
|
})),
|
||||||
{
|
{
|
||||||
key: "_actions", header: "", align: "right", nowrap: true, sticky: true,
|
key: "_actions", header: "", align: "right", nowrap: true, sticky: true,
|
||||||
render: (r) => (
|
render: (r) => (
|
||||||
<span className="row-actions">
|
<span className="row-actions">
|
||||||
{canEdit && <Button size="sm" variant="ghost" icon="edit" onClick={() => setEditing({ row: r })}>Edit</Button>}
|
{showEdit && !isNewRow(r) && <Button size="sm" variant="ghost" icon="edit" onClick={() => setEditing({ row: r })}>Edit</Button>}
|
||||||
<Button size="sm" variant="ghost" icon="download" onClick={() => void run(api.downloadCsvPdf(table.name, { rowId: r.id }))}>PDF</Button>
|
<Button size="sm" variant="ghost" icon="download" disabled={isNewRow(r)} onClick={() => void run(api.downloadCsvPdf(table.name, { rowId: r.id }))}>PDF</Button>
|
||||||
{canDelete && <Button size="sm" variant="ghost" icon="trash" onClick={() => setDeleting(r)} aria-label="Delete row" />}
|
{canDelete && (
|
||||||
|
<Button size="sm" variant="ghost" icon="trash" disabled={isNewRow(r) || (clearsInstead(r) && !hasFigures(r))} title={clearsInstead(r) ? (hasFigures(r) ? "This is the product's only row, so only its figures are cleared" : "Nothing entered in this row yet") : undefined} onClick={() => setDeleting(r)}>
|
||||||
|
{clearsInstead(r) ? "Clear" : "Remove"}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</span>
|
</span>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
@@ -171,7 +313,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<PageHeader title="Company forms" description="Fill in the company’s standard forms and print them as ready-to-sign PDFs." />
|
<PageHeader title="Company forms" description={user.role === "GM" ? "Every medical representative’s company forms, read-only. Download any of them as a PDF." : "Fill in the company’s standard forms and print them as ready-to-sign PDFs."} />
|
||||||
<div className="forms-layout">
|
<div className="forms-layout">
|
||||||
<nav className="form-nav" aria-label="Forms">
|
<nav className="form-nav" aria-label="Forms">
|
||||||
{tables.loading ? <Skeleton lines={6} /> : list.map((t) => (
|
{tables.loading ? <Skeleton lines={6} /> : list.map((t) => (
|
||||||
@@ -192,18 +334,18 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
<>
|
<>
|
||||||
{canSend && <Button icon="send" loading={acting} onClick={() => void act("request")}>Send for approval</Button>}
|
{canSend && <Button icon="send" loading={acting} onClick={() => void act("request")}>Send for approval</Button>}
|
||||||
{canApprove && <Button variant="primary" icon="check" loading={acting} onClick={() => void act("approve")}>Approve as AM</Button>}
|
{canApprove && <Button variant="primary" icon="check" loading={acting} onClick={() => void act("approve")}>Approve as AM</Button>}
|
||||||
<Button icon="download" disabled={shownRows.length === 0} onClick={() => void run(api.downloadCsvPdf(table.name, { ownerId: viewOwner?.id, month: month || undefined }))}>{month ? `Download ${month} PDF` : "Download PDF"}</Button>
|
<Button icon="download" disabled={shownRows.length === 0} onClick={() => void run(api.downloadCsvPdf(table.name, { ownerId: viewOwner?.id ?? (seesAll && PRODUCT_LIST_TABLES.has(table.name) ? mrChoice || undefined : undefined), month: hasMonthColumn ? month || undefined : undefined }))}>{month && hasMonthColumn ? `Download ${month} PDF` : "Download PDF"}</Button>
|
||||||
{canAdd && <Button variant="primary" icon="plus" onClick={() => setEditing({ row: null })}>New row</Button>}
|
{canAdd && <Button variant="primary" icon="plus" onClick={() => setEditing({ row: null })}>New row</Button>}
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
{showToolbar && (
|
{showToolbar && (
|
||||||
<div className="toolbar">
|
<div className="toolbar">
|
||||||
{isManager && needsApproval && (
|
{user.role === "AM" && needsApproval && (
|
||||||
<label className="filter">
|
<label className="filter">
|
||||||
<span>Medical representative</span>
|
<span>Medical representative</span>
|
||||||
<Select value={viewOwner?.id ?? ""} onChange={(e) => setOwnerChoice(e.target.value)} aria-label="Medical representative">
|
<Select value={viewOwner?.id ?? ""} onChange={(e) => setOwnerChoice(e.target.value)} aria-label="Medical representative">
|
||||||
{user.role === "ADMIN" && <option value="">All medical representatives</option>}
|
{seesAll && <option value="">All medical representatives</option>}
|
||||||
{ownerList.map((o) => <option key={o.id} value={o.id}>{o.name}{o.headquarters_name ? ` · ${o.headquarters_name}` : ""}{pendingFor(table.name, o.id) ? " — needs approval" : ""}</option>)}
|
{ownerList.map((o) => <option key={o.id} value={o.id}>{o.name}{o.headquarters_name ? ` · ${o.headquarters_name}` : ""}{pendingFor(table.name, o.id) ? " — needs approval" : ""}</option>)}
|
||||||
</Select>
|
</Select>
|
||||||
</label>
|
</label>
|
||||||
@@ -217,6 +359,24 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
</Select>
|
</Select>
|
||||||
</label>
|
</label>
|
||||||
)}
|
)}
|
||||||
|
{peopleFilter && (
|
||||||
|
<>
|
||||||
|
<label className="filter">
|
||||||
|
<span>Headquarter</span>
|
||||||
|
<Select value={hqChoice} onChange={(e) => { setHqChoice(e.target.value); setMrChoice(""); }} aria-label="Headquarter">
|
||||||
|
<option value="">All headquarters</option>
|
||||||
|
{hqOptions.map((h) => <option key={h} value={h}>{h}</option>)}
|
||||||
|
</Select>
|
||||||
|
</label>
|
||||||
|
<label className="filter">
|
||||||
|
<span>MR</span>
|
||||||
|
<Select value={mrChoice} onChange={(e) => setMrChoice(e.target.value)} aria-label="Medical representative">
|
||||||
|
<option value="">All MRs</option>
|
||||||
|
{mrOptions.map((o) => <option key={o.id} value={o.id}>{o.name}</option>)}
|
||||||
|
</Select>
|
||||||
|
</label>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{rows.error ? <ErrorState message={rows.error} onRetry={() => void rows.reload()} /> : (
|
{rows.error ? <ErrorState message={rows.error} onRetry={() => void rows.reload()} /> : (
|
||||||
@@ -224,6 +384,7 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
columns={columns}
|
columns={columns}
|
||||||
rows={shownRows}
|
rows={shownRows}
|
||||||
rowKey={(r) => r.id}
|
rowKey={(r) => r.id}
|
||||||
|
footer={footer}
|
||||||
loading={rows.loading || waitingForOwners}
|
loading={rows.loading || waitingForOwners}
|
||||||
minWidth={Math.max(640, columns.length * 115)}
|
minWidth={Math.max(640, columns.length * 115)}
|
||||||
empty={month
|
empty={month
|
||||||
@@ -254,12 +415,14 @@ export function FormsPage({ table: routeTable }: { table?: string }) {
|
|||||||
|
|
||||||
<Modal
|
<Modal
|
||||||
open={!!deleting}
|
open={!!deleting}
|
||||||
title="Delete this row?"
|
title={deleting && clearsInstead(deleting) ? "Clear this row?" : "Remove this row?"}
|
||||||
description="This cannot be undone."
|
description="This cannot be undone."
|
||||||
onClose={() => setDeleting(null)}
|
onClose={() => setDeleting(null)}
|
||||||
footer={<><Button onClick={() => setDeleting(null)}>Cancel</Button><Button variant="danger" onClick={() => void confirmDelete()}>Delete row</Button></>}
|
footer={<><Button onClick={() => setDeleting(null)}>Cancel</Button><Button variant="danger" onClick={() => void confirmDelete()}>{deleting && clearsInstead(deleting) ? "Clear figures" : "Remove row"}</Button></>}
|
||||||
>
|
>
|
||||||
<p className="prose">Row {deleting ? numberOf(deleting) : ""} will be removed from {table?.label}. The remaining rows are renumbered.</p>
|
<p className="prose">{deleting && clearsInstead(deleting)
|
||||||
|
? <>Everything entered for {String(deleting?.product_name ?? "this product")} (month and figures) will be emptied. The product stays in the list.</>
|
||||||
|
: <>Row {deleting ? numberOf(deleting) : ""} will be removed from {table?.label}. The remaining rows are renumbered.{needsApproval && isField(user.role) ? " If this form was sent for approval, it goes back to draft." : ""}</>}</p>
|
||||||
</Modal>
|
</Modal>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Input, Select } from "../../components/ui/Field";
|
||||||
|
import { columnLabel } from "../../lib/format";
|
||||||
|
|
||||||
|
const NUMBER = /^-?\d[\d,]*(\.\d+)?$/;
|
||||||
|
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A small box in the table that is typed into directly. Saves when the user leaves it (or
|
||||||
|
* presses Enter) and only if the value changed; Escape puts the saved value back. A refresh
|
||||||
|
* of the list never overwrites what is being typed.
|
||||||
|
*/
|
||||||
|
export function InlineCell({ value, column, onSave }: {
|
||||||
|
value: string; column: string; onSave: (value: string) => Promise<boolean>;
|
||||||
|
}) {
|
||||||
|
if (column === "month") return <MonthCell value={value} onSave={onSave} />;
|
||||||
|
return <NumberCell value={value} column={column} onSave={onSave} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The month, picked from the list; saved as soon as it is chosen. */
|
||||||
|
function MonthCell({ value, onSave }: { value: string; onSave: (value: string) => Promise<boolean> }) {
|
||||||
|
const [draft, setDraft] = useState(value);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
useEffect(() => { if (!saving) setDraft(value); }, [value, saving]);
|
||||||
|
|
||||||
|
async function choose(next: string) {
|
||||||
|
if (next === value) return;
|
||||||
|
setDraft(next);
|
||||||
|
setSaving(true);
|
||||||
|
const ok = await onSave(next);
|
||||||
|
setSaving(false);
|
||||||
|
if (!ok) setDraft(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Select className="cell-input cell-select" value={draft} disabled={saving} aria-label={columnLabel("month")} onChange={(e) => void choose(e.target.value)}>
|
||||||
|
<option value="">—</option>
|
||||||
|
{/* A month typed some other way in an imported row keeps showing as it was. */}
|
||||||
|
{draft && !MONTHS.includes(draft) && <option value={draft}>{draft}</option>}
|
||||||
|
{MONTHS.map((m) => <option key={m} value={m}>{m}</option>)}
|
||||||
|
</Select>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function NumberCell({ value, column, onSave }: {
|
||||||
|
value: string; column: string; onSave: (value: string) => Promise<boolean>;
|
||||||
|
}) {
|
||||||
|
const [draft, setDraft] = useState(value);
|
||||||
|
const [editing, setEditing] = useState(false);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [invalid, setInvalid] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => { if (!editing && !saving) setDraft(value); }, [value, editing, saving]);
|
||||||
|
|
||||||
|
async function commit() {
|
||||||
|
setEditing(false);
|
||||||
|
const next = draft.trim();
|
||||||
|
if (next === value.trim()) { setInvalid(false); return; }
|
||||||
|
if (next && !NUMBER.test(next)) { setInvalid(true); return; }
|
||||||
|
setInvalid(false);
|
||||||
|
setSaving(true);
|
||||||
|
const ok = await onSave(next);
|
||||||
|
setSaving(false);
|
||||||
|
if (!ok) setDraft(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Input
|
||||||
|
className={`cell-input${invalid ? " invalid" : ""}`}
|
||||||
|
value={draft}
|
||||||
|
inputMode="decimal"
|
||||||
|
disabled={saving}
|
||||||
|
aria-label={columnLabel(column)}
|
||||||
|
aria-invalid={invalid || undefined}
|
||||||
|
title={invalid ? "Numbers only" : undefined}
|
||||||
|
onFocus={() => setEditing(true)}
|
||||||
|
onChange={(e) => setDraft(e.target.value)}
|
||||||
|
onBlur={() => void commit()}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === "Enter") e.currentTarget.blur();
|
||||||
|
if (e.key === "Escape") { setDraft(value); setInvalid(false); e.currentTarget.blur(); }
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -8,16 +8,24 @@ import { useAsync } from "../../hooks/useAsync";
|
|||||||
import { columnLabel, errorMessage } from "../../lib/format";
|
import { columnLabel, errorMessage } from "../../lib/format";
|
||||||
import { isoDate, maxLength, numeric, required, useValidation, type Rule } from "../../lib/validation";
|
import { isoDate, maxLength, numeric, required, useValidation, type Rule } from "../../lib/validation";
|
||||||
import type { CsvRow, CsvTable, FormOwner, Profile, User } from "../../types";
|
import type { CsvRow, CsvTable, FormOwner, Profile, User } from "../../types";
|
||||||
|
import { screenColumns } from "./layout";
|
||||||
|
|
||||||
const SERIAL = new Set(["serial_no", "doctor_sr_no", "chemist_sr_no"]);
|
const SERIAL = new Set(["serial_no", "doctor_sr_no", "chemist_sr_no"]);
|
||||||
const IDENTITY = new Set(["name", "employee_name", "headquarter"]);
|
const IDENTITY = new Set(["name", "employee_name", "headquarter"]);
|
||||||
const DATES = new Set(["date", "report_date", "date_of_visit"]);
|
const DATES = new Set(["date", "report_date", "date_of_visit"]);
|
||||||
/** Columns that hold quantities or money — must be numbers (commas and decimals allowed). */
|
/** Columns that hold quantities or money — must be numbers (commas and decimals allowed). */
|
||||||
const NUMERIC = new Set([
|
const NUMERIC = new Set([
|
||||||
"pts", "secondary_qty", "value", "closing", "secondary_value", "aug_sales", "value_2", "opening", "receipt", "sale", "value_in_pts",
|
"pts", "closing_qty", "closing_value", "projection_qty", "projection_value", "closing", "opening", "receipt", "sale", "value_in_pts",
|
||||||
"kilometers_km", "no_of_days_worked", "no_of_doctor_called", "no_of_chemist_called", "no_of_doctors_called", "no_of_chemists_pds_called",
|
"kilometers_km", "no_of_days_worked", "no_of_doctor_called", "no_of_chemist_called", "no_of_doctors_called", "no_of_chemists_pds_called",
|
||||||
"pob_booked", "secondary_sales", "pob_objective", "secondary_objective", "doctor_call_avg", "chemist_call_avg", "pob",
|
"pob_booked", "secondary_sales", "pob_objective", "secondary_objective", "doctor_call_avg", "chemist_call_avg", "pob",
|
||||||
|
"fare", "da_hq", "da_ex", "da_out", "postage", "other_expense", "total", "business_achieved",
|
||||||
]);
|
]);
|
||||||
|
/** Expense Statement: TOTAL is always the sum of these, worked out here and again on the server. */
|
||||||
|
const EXPENSE_AMOUNTS = ["fare", "da_hq", "da_ex", "da_out", "postage", "other_expense"];
|
||||||
|
const expenseTotal = (d: Record<string, string>) => {
|
||||||
|
const amounts = EXPENSE_AMOUNTS.map((c) => (d[c] ?? "").replace(/,/g, "").trim()).filter(Boolean).map(Number);
|
||||||
|
return amounts.length && amounts.every(Number.isFinite) ? amounts.reduce((a, b) => a + b, 0).toFixed(2) : "";
|
||||||
|
};
|
||||||
const LONG_TEXT = new Set(["remarks", "area_to_cover", "product_offer_scheme_booked", "product_offer_scheme_objective"]);
|
const LONG_TEXT = new Set(["remarks", "area_to_cover", "product_offer_scheme_booked", "product_offer_scheme_objective"]);
|
||||||
|
|
||||||
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
|
||||||
@@ -28,10 +36,11 @@ export function RowEditor({ open, table, row, rows, user, profile, owner, onClos
|
|||||||
owner?: FormOwner;
|
owner?: FormOwner;
|
||||||
onClose: () => void; onSaved: (message: string) => void;
|
onClose: () => void; onSaved: (message: string) => void;
|
||||||
}) {
|
}) {
|
||||||
const columns = useMemo(() => table.columns.filter((c) => !SERIAL.has(c)), [table]);
|
const columns = useMemo(() => screenColumns(table, user.role).filter((c) => !SERIAL.has(c)), [table, user.role]);
|
||||||
const isAdmin = user.role === "ADMIN";
|
const isAdmin = user.role === "ADMIN";
|
||||||
// Admin maintains the product list, so PTS is editable for them; for MRs it follows the product.
|
// Admin maintains the product list, so PTS is editable for them; for MRs it follows the product.
|
||||||
const generated = (c: string) => IDENTITY.has(c) || (table.name === "sales_projection" && c === "pts" && !isAdmin);
|
const isExpense = table.name === "expense_statement";
|
||||||
|
const generated = (c: string) => IDENTITY.has(c) || (table.name === "sales_projection" && c === "pts" && !isAdmin) || (isExpense && c === "total");
|
||||||
// NAME / HEADQUARTER are the MR's: the signed-in MR, or the one an admin is filling the form in for.
|
// NAME / HEADQUARTER are the MR's: the signed-in MR, or the one an admin is filling the form in for.
|
||||||
const account = (c: string) => {
|
const account = (c: string) => {
|
||||||
if (isAdmin && owner) return c === "headquarter" ? owner.headquarters_name ?? "" : owner.name;
|
if (isAdmin && owner) return c === "headquarter" ? owner.headquarters_name ?? "" : owner.name;
|
||||||
@@ -66,13 +75,22 @@ export function RowEditor({ open, table, row, rows, user, profile, owner, onClos
|
|||||||
if (!open) return;
|
if (!open) return;
|
||||||
setError(null);
|
setError(null);
|
||||||
v.clear();
|
v.clear();
|
||||||
setDraft(Object.fromEntries(columns.map((c) => [c, IDENTITY.has(c) ? (row ? String(row[c] ?? "") : account(c)) : String(row?.[c] ?? "")])));
|
const initial = Object.fromEntries(columns.map((c) => [c, IDENTITY.has(c) ? (row ? String(row[c] ?? "") : account(c)) : String(row?.[c] ?? "")]));
|
||||||
|
// A new day on the expense statement starts with the designation used on the earlier days.
|
||||||
|
if (isExpense && !row) initial.designation = String([...rows].reverse().find((r) => r.designation)?.designation ?? "Medical Representative");
|
||||||
|
setDraft(initial);
|
||||||
// Keyed on the row's id and primitives — not object identity — so a background refresh
|
// Keyed on the row's id and primitives — not object identity — so a background refresh
|
||||||
// of the list can never wipe what the user is typing.
|
// of the list can never wipe what the user is typing.
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [open, row?.id, table.name, profile?.full_name, profile?.headquarters_name, owner?.id]);
|
}, [open, row?.id, table.name, profile?.full_name, profile?.headquarters_name, owner?.id]);
|
||||||
|
|
||||||
const set = (column: string, value: string) => { setDraft((d) => ({ ...d, [column]: value })); v.retouch(column, value); };
|
const set = (column: string, value: string) => {
|
||||||
|
setDraft((d) => {
|
||||||
|
const next = { ...d, [column]: value };
|
||||||
|
return isExpense && EXPENSE_AMOUNTS.includes(column) ? { ...next, total: expenseTotal(next) } : next;
|
||||||
|
});
|
||||||
|
v.retouch(column, value);
|
||||||
|
};
|
||||||
const blur = (column: string) => (e: { target: { value: string } }) => v.touch(column, e.target.value);
|
const blur = (column: string) => (e: { target: { value: string } }) => v.touch(column, e.target.value);
|
||||||
|
|
||||||
async function submit(e: FormEvent<HTMLFormElement>) {
|
async function submit(e: FormEvent<HTMLFormElement>) {
|
||||||
@@ -148,7 +166,8 @@ export function RowEditor({ open, table, row, rows, user, profile, owner, onClos
|
|||||||
error={v.errors[c]}
|
error={v.errors[c]}
|
||||||
required={table.name === "sales_projection" && c === "product_name"}
|
required={table.name === "sales_projection" && c === "product_name"}
|
||||||
hint={
|
hint={
|
||||||
generated(c) ? "Filled in automatically"
|
isExpense && c === "total" ? "Fare + daily allowance + postage + other expense"
|
||||||
|
: generated(c) ? "Filled in automatically"
|
||||||
: needsDoctors && c === "doctor_name" && !doctors.loading && coreDoctorNames.length === 0 ? "No core doctors are assigned yet — ask your administrator to assign some."
|
: needsDoctors && c === "doctor_name" && !doctors.loading && coreDoctorNames.length === 0 ? "No core doctors are assigned yet — ask your administrator to assign some."
|
||||||
: NUMERIC.has(c) ? "Numbers only"
|
: NUMERIC.has(c) ? "Numbers only"
|
||||||
: undefined
|
: undefined
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
/** Forms that carry an Area Manager approval signature on their PDF. */
|
/** Forms that carry an Area Manager approval signature on their PDF. */
|
||||||
export const APPROVAL_FORMS = new Set(["standard_tour_plan", "tour_plan", "fare_chart"]);
|
export const APPROVAL_FORMS = new Set(["standard_tour_plan", "tour_plan", "fare_chart", "expense_statement"]);
|
||||||
|
|
||||||
/** How often the approval state is re-checked, so an approval shows up for the other person within seconds. */
|
/** How often the approval state is re-checked, so an approval shows up for the other person within seconds. */
|
||||||
export const APPROVAL_POLL_MS = 3_000;
|
export const APPROVAL_POLL_MS = 3_000;
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import type { CsvTable, Role } from "../../types";
|
||||||
|
|
||||||
|
/** Columns shown in a different order than they are stored, to match the printed form (app/pdf/forms.py). */
|
||||||
|
const SCREEN_ORDER: Record<string, string[]> = {
|
||||||
|
sales_and_stock_statement: ["product_name", "value_in_pts"],
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Columns nobody sees or fills in on that form, whatever their role. */
|
||||||
|
const HIDDEN: Record<string, Set<string>> = {
|
||||||
|
sales_and_stock_statement: new Set(["report_date"]),
|
||||||
|
sales_projection: new Set(["report_date"]),
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Columns worked out by the system, never typed (Field Activity Report averages — shown as the Average row). */
|
||||||
|
const COMPUTED: Record<string, Set<string>> = {
|
||||||
|
field_activity_report: new Set(["doctor_call_avg", "chemist_call_avg"]),
|
||||||
|
area_covered: new Set(["sale_status"]),
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The form's columns as this role sees them: in printed order, without the ones hidden from them. */
|
||||||
|
export function screenColumns(table: CsvTable, role: Role): string[] {
|
||||||
|
const hidden = HIDDEN[table.name];
|
||||||
|
const columns = table.columns.filter((c) => !hidden?.has(c) && !COMPUTED[table.name]?.has(c));
|
||||||
|
const order = SCREEN_ORDER[table.name];
|
||||||
|
if (!order) return columns;
|
||||||
|
// The listed columns sit together, in that order, where the first of them was.
|
||||||
|
const rest = columns.filter((c) => !order.includes(c));
|
||||||
|
const at = columns.findIndex((c) => order.includes(c));
|
||||||
|
return at < 0 ? columns : [...rest.slice(0, at), ...order.filter((c) => columns.includes(c)), ...rest.slice(at)];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Columns typed straight into the table, in a small box per cell, instead of through the Edit drawer. */
|
||||||
|
export const INLINE_COLUMNS: Record<string, Set<string>> = {
|
||||||
|
sales_and_stock_statement: new Set(["month", "value_in_pts", "opening", "receipt", "sale", "closing"]),
|
||||||
|
sales_projection: new Set(["month", "closing_qty", "closing_value", "projection_qty", "projection_value"]),
|
||||||
|
};
|
||||||
@@ -2,31 +2,67 @@ import { type FormEvent, useState } from "react";
|
|||||||
import { Alert } from "../../components/ui/Alert";
|
import { Alert } from "../../components/ui/Alert";
|
||||||
import { Button } from "../../components/ui/Button";
|
import { Button } from "../../components/ui/Button";
|
||||||
import { Card, CardBody, CardHeader } from "../../components/ui/Card";
|
import { Card, CardBody, CardHeader } from "../../components/ui/Card";
|
||||||
import { Field, Input, Textarea } from "../../components/ui/Field";
|
import { Field, Input, Select, Textarea } from "../../components/ui/Field";
|
||||||
import { PageHeader } from "../../components/ui/PageHeader";
|
import { PageHeader } from "../../components/ui/PageHeader";
|
||||||
import { api } from "../../api";
|
import { api } from "../../api";
|
||||||
|
import { useAsync } from "../../hooks/useAsync";
|
||||||
import { errorMessage, todayISO } from "../../lib/format";
|
import { errorMessage, todayISO } from "../../lib/format";
|
||||||
|
import { REPORT_TYPE_LABEL } from "../../lib/format";
|
||||||
|
import { reportPath, reportsPath } from "../../lib/navigation";
|
||||||
import { navigate } from "../../lib/router";
|
import { navigate } from "../../lib/router";
|
||||||
import { isoDate, maxLength, notAfter, required, useValidation } from "../../lib/validation";
|
import { isoDate, maxLength, notAfter, required, useValidation } from "../../lib/validation";
|
||||||
|
import type { ReportType } from "../../types";
|
||||||
|
|
||||||
export function NewReportPage() {
|
const COPY: Record<ReportType, { title: string; description: string; remarks: string; create: string }> = {
|
||||||
|
SELF: {
|
||||||
|
title: "New Daily Call Report (Self)",
|
||||||
|
description: "Record the doctors and chemists you visited yourself. No approval is needed: once you submit it, the report is final.",
|
||||||
|
remarks: "Optional summary of the day",
|
||||||
|
create: "Start report",
|
||||||
|
},
|
||||||
|
PLAN: {
|
||||||
|
title: "New Daily Call Report (Plan)",
|
||||||
|
description: "List the doctors and chemists you intend to visit today and when, then send the plan to your Area Manager.",
|
||||||
|
remarks: "Optional note for your Area Manager, e.g. the area you will cover",
|
||||||
|
create: "Start plan",
|
||||||
|
},
|
||||||
|
ACTUAL: {
|
||||||
|
title: "New Daily Call Report (Done)",
|
||||||
|
description: "Once your plan is approved, record the visits you made. Planned visits you could not make need a short note.",
|
||||||
|
remarks: "Optional summary of the day",
|
||||||
|
create: "Start report",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A plan may be made this many days ahead (PLAN_AHEAD_DAYS on the server); Done and Self never. */
|
||||||
|
const PLAN_AHEAD_DAYS = 2;
|
||||||
|
|
||||||
|
export function NewReportPage({ type }: { type: ReportType }) {
|
||||||
|
const copy = COPY[type];
|
||||||
|
const latest = todayISO(type === "PLAN" ? PLAN_AHEAD_DAYS : 0);
|
||||||
|
const isSelf = type === "SELF";
|
||||||
|
// An Area Manager's own report is for one of the headquarters they manage.
|
||||||
|
const hqs = useAsync(() => (isSelf ? api.headquarters() : Promise.resolve([])), [isSelf]);
|
||||||
|
const [hqChoice, setHqChoice] = useState("");
|
||||||
|
const hqId = hqChoice || (hqs.data?.length === 1 ? hqs.data[0].id : "");
|
||||||
const [date, setDate] = useState(todayISO());
|
const [date, setDate] = useState(todayISO());
|
||||||
const [remarks, setRemarks] = useState("");
|
const [remarks, setRemarks] = useState("");
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const v = useValidation({
|
const v = useValidation({
|
||||||
date: [required("Report date"), isoDate("Report date"), notAfter(todayISO(), "Report date", "today")],
|
date: [required("Report date"), isoDate("Report date"), notAfter(latest, "Report date", type === "PLAN" ? `${PLAN_AHEAD_DAYS} days from today` : "today")],
|
||||||
|
hq: isSelf ? [required("Headquarters")] : [],
|
||||||
remarks: [maxLength(2000, "Remarks")],
|
remarks: [maxLength(2000, "Remarks")],
|
||||||
});
|
});
|
||||||
|
|
||||||
async function submit(e: FormEvent<HTMLFormElement>) {
|
async function submit(e: FormEvent<HTMLFormElement>) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!v.check({ date, remarks }, e.currentTarget)) return;
|
if (!v.check({ date, hq: hqId, remarks }, e.currentTarget)) return;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const created = await api.createReport({ report_date: date, mr_remarks: remarks || null });
|
const created = await api.createReport({ report_date: date, report_type: type, mr_remarks: remarks || null, ...(isSelf && { headquarters_id: hqId }) });
|
||||||
navigate(`/reports/${created.id}`);
|
navigate(reportPath(created));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(errorMessage(err, "Could not create the report"));
|
setError(errorMessage(err, "Could not create the report"));
|
||||||
setBusy(false);
|
setBusy(false);
|
||||||
@@ -35,21 +71,29 @@ export function NewReportPage() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="narrow">
|
<div className="narrow">
|
||||||
<PageHeader back={{ to: "/reports", label: "Daily Call Reports" }} title="New Daily Call Report" description="Start a draft, then add your doctor and chemist visits before submitting." />
|
<PageHeader back={{ to: reportsPath(type), label: REPORT_TYPE_LABEL[type] }} title={copy.title} description={copy.description} />
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader title="Report details" />
|
<CardHeader title="Report details" />
|
||||||
<CardBody>
|
<CardBody>
|
||||||
<form className="form-grid" onSubmit={submit} noValidate>
|
<form className="form-grid" onSubmit={submit} noValidate>
|
||||||
<Alert>{error}</Alert>
|
<Alert>{error}</Alert>
|
||||||
<Field label="Report date" required error={v.errors.date} hint="One report per day; you can file up to the configured backdating window.">
|
<Field label="Report date" required error={v.errors.date} hint={type === "PLAN" ? `One plan per day. You can plan today or up to ${PLAN_AHEAD_DAYS} days ahead.` : isSelf ? "One report per day." : "Your Daily Call Report (Plan) for this date must already be approved by your Area Manager."}>
|
||||||
<Input type="date" value={date} max={todayISO()} onChange={(e) => { setDate(e.target.value); v.retouch("date", e.target.value); }} onBlur={(e) => v.touch("date", e.target.value)} />
|
<Input type="date" value={date} max={latest} onChange={(e) => { setDate(e.target.value); v.retouch("date", e.target.value); }} onBlur={(e) => v.touch("date", e.target.value)} />
|
||||||
</Field>
|
</Field>
|
||||||
|
{isSelf && (
|
||||||
|
<Field label="Headquarters" required error={v.errors.hq ?? hqs.error ?? undefined} hint={hqs.data?.length === 0 ? "You do not manage a headquarters yet — ask your administrator." : "Its doctors and chemists can be added to the report."}>
|
||||||
|
<Select value={hqId} onChange={(e) => { setHqChoice(e.target.value); v.retouch("hq", e.target.value); }}>
|
||||||
|
<option value="">Choose headquarters</option>
|
||||||
|
{(hqs.data ?? []).map((h) => <option key={h.id} value={h.id}>{h.code} · {h.name}</option>)}
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
)}
|
||||||
<Field label="Daily remarks" span error={v.errors.remarks} hint={`${remarks.length}/2000`}>
|
<Field label="Daily remarks" span error={v.errors.remarks} hint={`${remarks.length}/2000`}>
|
||||||
<Textarea value={remarks} onChange={(e) => { setRemarks(e.target.value); v.retouch("remarks", e.target.value); }} onBlur={(e) => v.touch("remarks", e.target.value)} rows={4} placeholder="Optional summary of the day" />
|
<Textarea value={remarks} onChange={(e) => { setRemarks(e.target.value); v.retouch("remarks", e.target.value); }} onBlur={(e) => v.touch("remarks", e.target.value)} rows={4} placeholder={copy.remarks} />
|
||||||
</Field>
|
</Field>
|
||||||
<div className="form-actions">
|
<div className="form-actions">
|
||||||
<Button onClick={() => navigate("/reports")}>Cancel</Button>
|
<Button onClick={() => navigate(reportsPath(type))}>Cancel</Button>
|
||||||
<Button type="submit" variant="primary" loading={busy}>Create draft</Button>
|
<Button type="submit" variant="primary" loading={busy}>{copy.create}</Button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</CardBody>
|
</CardBody>
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user