# Task D.6 – CRM Activity Foundation & Audit Log Separation

## Objective

Separate system audit history from real CRM business activities.

Currently, several CRM document detail pages use the tab name `Activity` for system-generated history. This is semantically incorrect.

In CRM, `Activity` should mean actionable work performed by MK/Sales, such as:

* site visit
* customer meeting
* phone call
* follow-up
* requirement discussion
* site survey
* quotation follow-up

System-generated history should be displayed under `Audit Log`.

This task also improves follow-up date input UX by replacing plain date text input with a calendar date picker.

---

# Background

Current issue:

```text id="b2lkfk"
Activity tab
```

is being used for system history such as:

* created
* updated
* status changed
* approved
* rejected
* PDF generated
* customer package generated

But business users expect Activity to mean:

```text id="f8lcxc"
2026-07-01: Visit customer site

2026-07-03: Follow up quotation by phone

2026-07-05: Meeting with purchasing team
```

Therefore:

* System history = Audit Log
* Business work = Activity

---

# Scope

Included:

* Rename system history tab from `Activity` to `Audit Log`
* Standardize Audit Log tab across CRM documents
* Create CRM Activity foundation model
* Prepare Activity UI patterns
* Improve follow-up date input to use calendar picker
* Keep existing follow-up business behavior compatible
* Prepare future Calendar integration

Excluded:

* Full calendar module implementation
* Google Calendar / Outlook sync
* Notification automation
* Advanced recurring activity scheduling
* Mobile push reminders

---

# Discovery Requirement

Before implementation, inspect the actual codebase.

Review at minimum:

```text id="7scakw"
Quotation detail tabs
Lead detail tabs
Opportunity detail tabs
Customer detail tabs
Follow-up components
Audit log components
Existing activity/follow-up tables
Existing calendar/date picker components
Existing shadcn calendar/popover/date-input patterns
```

Identify:

* where `Activity` is used as audit history
* where follow-up forms use plain date input
* which modules already have follow-up data
* which audit log API/components can be reused
* current date format standards

Do not assume the current UI structure.

---

# Terminology Rules

## Audit Log

Means system-generated immutable history.

Examples:

```text id="zg8qvr"
Quotation Created

Status Changed

Approval Requested

Approved

Rejected

PDF Generated

Customer Package Generated

Email Sent
```

Characteristics:

* read-only
* system generated
* immutable
* audit/compliance focused

---

## Activity

Means CRM business work.

Examples:

```text id="g7k2rv"
Visit customer site

Call customer

Follow-up quotation

Site survey

Requirement gathering

Meeting purchasing team

Send revised offer
```

Characteristics:

* created by user
* assigned to user
* has due date
* may be planned or completed
* can appear in calendar
* may trigger notification/reminder later

---

# Part 1 - Audit Log Tab Refactor

Rename all tabs that currently show system history from:

```text id="q1j1zt"
Activity
```

to:

```text id="bmkkw7"
Audit Log
```

Apply at minimum to:

* Quotation detail
* Lead detail
* Opportunity detail
* Customer detail
* Any CRM document detail page that uses Activity for history

If a page already has true Activity content, do not rename it blindly. Split it into:

```text id="mfooo0"
Activity

Audit Log
```

---

# Audit Log UI Standard

Create or reuse a shared component:

```text id="tk4rn3"
<AuditLogTab />
```

Display:

* timestamp
* actor
* action
* before/after state
* remarks
* related artifact
* system-generated badge if applicable

Sort:

```text id="0or6f8"
newest first
```

Do not allow editing or deleting audit rows.

---

# Part 2 - CRM Activity Foundation

Design a reusable CRM Activity model.

Activities should support multiple CRM entities:

* Lead
* Opportunity
* Quotation
* Customer
* Contact
* Future PO / Service Report

Suggested fields:

```text id="svj0zq"
id
organizationId
entityType
entityId
activityType
subject
description
ownerId
assignedToId
dueDate
dueTime
completedAt
status
priority
outcome
nextAction
createdBy
createdAt
updatedAt
```

---

# Activity Types

Initial activity types:

```text id="zmet5e"
site_visit
meeting
phone_call
email_follow_up
quotation_follow_up
site_survey
requirement_discussion
internal_task
other
```

---

# Activity Status

Use:

```text id="8cmuir"
planned
in_progress
completed
cancelled
overdue
```

Overdue may be derived, not necessarily stored.

---

# Activity UI

For each supported CRM entity, Activity tab should eventually show:

```text id="bn6gr5"
Upcoming Activities

Completed Activities

Overdue Activities
```

Each activity card should show:

* activity type
* subject
* due date
* owner
* status
* priority
* related document
* outcome if completed

---

# Part 3 - Follow-up Date Picker Improvement

Replace plain follow-up date input with a calendar date picker.

Apply to existing follow-up forms in:

* Lead follow-up
* Opportunity follow-up
* Quotation follow-up
* Customer follow-up if present

Date input must be easy for users to click and choose.

Use existing UI components if available:

```text id="s1f84i"
Calendar
Popover
Button
FormControl
```

Preferred UX:

```text id="t9fzwi"
[ Select follow-up date 📅 ]
```

On click:

```text id="far25j"
Calendar opens
User selects date
Date displays as YYYY-MM-DD
```

---

# Date Format Rule

Display dates as:

```text id="srzquj"
YYYY-MM-DD
```

Storage should use existing backend-compatible date format.

Do not introduce locale-dependent rendering that may cause hydration mismatch.

---

# Follow-up UX Rules

* Calendar picker must support keyboard navigation.
* Date must be clear after selection.
* Existing validation must remain.
* Required date rules must remain.
* User should not need to manually type dates.
* Manual typing may be disabled unless existing component requires it.
* If clearing date is allowed, provide a clear button.

---

# Part 4 - Compatibility With Existing Follow-up

Do not break existing follow-up APIs.

If current follow-up is stored separately from the new Activity model, keep it compatible.

Recommended strategy:

```text id="xyx67z"
Phase D.6

Rename Audit Log tab

Improve follow-up date picker

Introduce Activity foundation

Do not migrate all follow-ups yet
```

Future task can migrate:

```text id="543zj8"
Follow-up

↓

Activity
```

---

# Part 5 - Calendar Readiness

Activities must be designed so future calendar integration can use them.

Required future-ready fields:

* dueDate
* dueTime
* assignedToId
* ownerId
* status
* entityType
* entityId

This prepares future integration with:

```text id="ksqzgi"
Calendar module

Notifications

Reminders

Team visibility
```

---

# Permissions

Add or reuse permissions:

```text id="kujab3"
crmActivityRead
crmActivityCreate
crmActivityUpdate
crmActivityComplete
crmActivityDelete
crmAuditLogRead
```

Audit log should be read-only.

Activity should follow CRM visibility rules.

---

# Audit Logging

Creating, updating, completing, or cancelling an Activity should write audit logs.

Examples:

```text id="kqf2c1"
Activity Created

Activity Completed

Activity Cancelled

Activity Rescheduled
```

---

# Testing Requirements

Run:

```bash id="a4tuy5"
npm run typecheck
npm run build
npm run audit:pdf
```

Add tests where practical for:

* tab label transformation
* date picker value formatting
* activity status helpers
* audit log display helpers
* follow-up date conversion to YYYY-MM-DD

---

# Manual Verification Scenarios

## Scenario 1 - Audit Log Tab

Open quotation detail.

Expected:

```text id="1sabcz"
Activity tab is replaced by Audit Log
```

Audit rows still show correctly.

---

## Scenario 2 - True Activity

Create or inspect Activity tab where implemented.

Expected:

```text id="ofkfzg"
Shows business tasks, not system logs
```

Example:

```text id="jzae6e"
2026-07-01 Visit customer site
```

---

## Scenario 3 - Follow-up Date Picker

Open follow-up form.

Expected:

* Date picker opens on click.
* User can select date.
* Selected date displays as YYYY-MM-DD.
* Submitted payload remains compatible with existing API.

---

## Scenario 4 - No Hydration Issue

Reload detail page.

Expected:

* Date displays consistently as YYYY-MM-DD.
* No React hydration warning.

---

# Acceptance Criteria

* System history tabs are renamed to `Audit Log`.
* Audit Log is read-only.
* Activity is reserved for business tasks and follow-ups.
* CRM Activity foundation exists or is planned with schema/service contracts.
* Follow-up date input uses a calendar date picker.
* Selected date displays as YYYY-MM-DD.
* Existing follow-up APIs remain compatible.
* Existing audit log data still renders correctly.
* Build, typecheck, and PDF audit pass.

---

# Out of Scope

## Calendar Phase

* Full calendar module
* Team calendar
* Manager calendar
* Drag-and-drop schedule
* Reminder automation

## Notification Phase

* Activity reminder email
* Follow-up due notification
* Overdue notification

## Migration Phase

* Full migration of historical follow-up rows into Activity

---

# Final Success Condition

Task D.6 is complete when CRM system history is consistently shown as `Audit Log`, CRM `Activity` is clearly reserved for MK/Sales business work, and follow-up date entry is improved with a calendar picker using stable `YYYY-MM-DD` formatting.

---

# Implementation Result - 2026-07-01

Status: Completed

Implemented:
- Renamed system-history tabs from `Activity` to `Audit Log` in quotation, lead, opportunity, and customer detail views.
- Added shared `AuditLogTab` UI and reused it across CRM detail surfaces to present immutable audit entries consistently.
- Extended CRM audit-log records with `beforeData`, `afterData`, and `requestId` so the UI can show richer system history.
- Standardized date-picker placeholders to `YYYY-MM-DD` and added clear support in `CrmDateInput`.
- Migrated lead follow-up creation UI from plain text date entry to the shared calendar date-picker pattern.
- Added CRM Activity foundation contracts in `src/features/crm/activity/types.ts` for entity scope, activity types, statuses, priorities, derived overdue status, and future-ready permissions.
- Added permission keys for `crmActivityRead`, `crmActivityCreate`, `crmActivityUpdate`, `crmActivityComplete`, `crmActivityDelete`, and `crmAuditLogRead`.

Verification:
- `npm run typecheck` -> PASS
- `npm run build` -> PASS
- `npm run audit:pdf` -> PASS

Notes:
- `npm run build` still reports existing Turbopack warnings about workspace root lockfile detection and an NFT trace warning from PDF audit/template validation paths. Build still completed successfully.
- This task intentionally does not migrate historical follow-up rows into the new activity model yet; follow-ups remain API-compatible and activity contracts are prepared for a later phase.

Implementation report:
- [task-d.6-crm-activity-foundation-audit-log-separation-2026-07-01.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/implementation/task-d.6-crm-activity-foundation-audit-log-separation-2026-07-01.md)
