bu1 ad email config

This commit is contained in:
phaichayon
2026-07-07 14:37:17 +07:00
parent 3b5fede134
commit 62762fc70c
8 changed files with 2183 additions and 52 deletions

View File

@@ -448,3 +448,572 @@ Phase R.1 may begin when:
1. this blueprint is accepted as the business baseline
2. terminology conflicts are treated as governance backlog instead of hidden assumptions
3. capability audit work references this document explicitly
## 20. Activity Blueprint Freeze
### Purpose
Activity is the governed operational work record for business execution across marketing, sales, customer relationship work, quotation chasing, manager follow-through, and future service coordination.
Frozen rule:
- `Activity` is the source-of-truth work record.
- `Audit Log` is immutable system history.
- `Notification`, `Reminder`, `Calendar`, and `Timeline` are projections from activity state and business events, not parallel activity records.
### Activity Definition
An Activity represents one planned, in-progress, completed, rescheduled, or cancelled unit of work performed by or assigned to a user.
Examples:
- follow-up call
- customer meeting
- site visit
- site survey
- presentation
- internal task
- document chase
- reminder-backed action item
### Activity Ownership
- One activity has one accountable owner.
- One activity may also have one assignee when work is delegated.
- Owner is responsible for ensuring the activity reaches a terminal outcome.
- Assignee is responsible for execution when assigned.
- Customer owner, lead owner, opportunity owner, quotation salesman, or manager may create activities, but activity ownership must still resolve to one user.
### Activity Entity Relationships
Every activity must support:
- one required primary reference
- zero or more related references
Allowed primary reference targets:
- Customer
- Contact
- Lead
- Opportunity
- Quotation
- PO / Won Project
- Internal Only
Allowed related references:
- Customer + Contact
- Customer + Opportunity
- Opportunity + Quotation
- Lead + Customer
- Quotation + Opportunity + Customer
Frozen rule:
- Activity may span business context, but only one primary reference governs default visibility, ownership inheritance, and calendar placement.
### Activity Families
Shared activity families are:
- Follow-up
- Meeting
- Visit
- Phone Call
- Email Follow-up
- Site Survey
- Presentation
- Internal Task
- Reminder-Driven Action
- Other
### Activity Priority Freeze
Priority levels are:
- Critical
- High
- Normal
- Low
Priority is determined from:
- business deadline
- customer commitment date
- forecast sensitivity
- approval dependency
- manager escalation
Frozen rule:
- `Hot Project` is not the same thing as `Critical Activity`.
- Hot Project may increase suggested activity priority, but does not force it automatically.
### Activity Status Freeze
Primary status set:
- Planned
- In Progress
- Completed
- Cancelled
Derived operational views:
- Due Today
- Upcoming
- Overdue
- Completed Today
Frozen rules:
- `Overdue` is a derived operational condition, not a separate lifecycle state.
- `Rescheduled` is an activity event and timeline event, not a standalone terminal status.
### Activity State Machine Freeze
```text
Planned -> In Progress -> Completed
Planned -> Cancelled
Planned -> Overdue (derived view only, returns to Planned after reschedule)
In Progress -> Completed
In Progress -> Cancelled
```
### Activity Completion Rules
- Completion requires an outcome summary.
- Completion may optionally create a next activity suggestion.
- Follow-up completion should encourage explicit next action when the related lead, opportunity, or quotation remains open.
- Cancelled activities must capture cancellation reason when the activity was already scheduled with customer-facing commitment.
- Activities linked to lost or closed records may still be completed for documentation, but no new forward-driving activity should be auto-created from a terminal-lost record without user intent.
### Activity Visibility Freeze
Activity visibility inherits from the primary related record plus assignment.
Rules:
- Owner and assignee can always view the activity.
- Users who can access the primary record may view the activity unless the activity is marked internal-only.
- Internal-only activities are visible only to creator, owner, assignee, managers, and authorized admins.
- Contact-level sensitivity follows parent customer/contact access rules.
- Pricing-sensitive notes remain subject to quotation pricing visibility when activity content exposes commercial amounts.
### Activity Permission Freeze
Minimum governed permissions:
- Activity Read
- Activity Create
- Activity Update
- Activity Complete
- Activity Cancel
- Activity Delete
- Activity Reassign
Frozen rule:
- Activity authorization must follow resolved CRM access patterns and never bypass record scope rules.
### Follow-up Strategy Freeze
- Follow-up remains the first operational activity subtype.
- Existing lead, opportunity, and quotation follow-up records are the current implementation seam.
- Future unification should map those records into the shared activity model without changing business meaning.
- A follow-up should always answer: what happened, what is next, and when the next touch should happen.
### Reminder Strategy Freeze
- Reminder is not a separate business master entity from activity in the future target model.
- Reminder is a time-based prompt attached to an activity or milestone event.
- Users may receive multiple reminders for one activity without creating duplicate work records.
### Automation Strategy Freeze
Future automation may:
- suggest follow-up creation
- suggest priority increases
- suggest Hot Project activity escalation
- generate reminder prompts
- escalate manager visibility for overdue work
Frozen rule:
- Automation may propose or publish derived signals, but must not silently fabricate completed business work.
### Calendar Synchronization Freeze
- Scheduled activities appear in calendar.
- Reminder prompts appear in calendar only when configured as visible reminder events.
- Opportunity milestone dates and quotation milestone dates appear as milestone events, not as activity rows.
- Reschedule, cancel, and complete actions must update the calendar projection.
### Timeline Synchronization Freeze
- Activity created
- activity assigned
- activity rescheduled
- activity completed
- activity cancelled
- outcome summary captured
All create timeline entries on the related records.
### Notification Synchronization Freeze
Notifications may be created for:
- assignment
- due soon
- overdue
- manager escalation
- reminder prompt
- linked approval dependency
Frozen rule:
- Notification inbox is a delivery surface, not the system-of-record for work.
## 21. Workspace Interaction Blueprint Freeze
### Workspace Philosophy
Workspace means a role-oriented working surface over shared governed records.
Frozen rule:
- navigation should move users by decision context, not by raw table ownership alone.
### Daily Operating Pattern
The standard operating day is:
```text
My Day -> Customer / Lead / Opportunity / Quotation Workspace -> Calendar / Timeline check -> Follow-up completion -> Manager / Executive review
```
### Marketing Workflow
1. Review My Day for overdue and due-today lead activities.
2. Open Lead workspace to qualify new demand and capture follow-up outcome.
3. Escalate or convert demand into sales-ready handoff.
4. Confirm next touch date before leaving the record.
### Sales Workflow
1. Start in My Day for urgent follow-up, meetings, and quotation chases.
2. Move into Opportunity workspace for qualification, forecast, and customer coordination.
3. Enter Quotation workspace when pricing, revision, or approval work is required.
4. Return to Customer workspace when relationship context or cross-project view is needed.
5. End the day by closing completed work and scheduling next actions.
### Manager Workflow
1. Review Manager workspace for team overdue work, idle opportunities, approvals, and Hot Projects.
2. Jump into Team Calendar for schedule conflicts and near-term commitments.
3. Intervene on stalled records through assignment, escalation, and forecast review.
4. Finish with tomorrow-risk review rather than only historical KPI review.
### Executive Workflow
1. Review pipeline, revenue outlook, and strategic account movement.
2. Use customer relationship and manager signals for exception review.
3. Drill into customer, opportunity, or quotation only when escalation or business risk requires it.
## 22. Customer Workspace Blueprint Freeze
### Customer Workspace Philosophy
Customer is the relationship anchor and must become the main relationship workspace, not only a master-data form.
### Required Sections
- Overview
- Contacts
- Activities
- Timeline
- Leads
- Opportunities
- Quotations
- PO / Won History
- Files
- Notes / Relationship Summary
- Upcoming Activities
- Recent Visits / Meetings
### Customer 360 View Freeze
Customer 360 must answer:
- who owns the relationship
- who the active contacts are
- what work is next
- what open demand exists
- what quotation and revenue motion is active
- what history and risk the team should know before contacting the customer
### Relationship Health Freeze
Relationship health is a business assessment derived from:
- recency of meaningful contact
- number of overdue activities
- open opportunities without next action
- strategic account importance
- ownership clarity
Status bands:
- Healthy
- Watch
- At Risk
### Follow-up Health Freeze
Follow-up health is derived from:
- next scheduled activity exists
- overdue work count
- activity completion discipline
- follow-up gap age
### Customer Timeline Freeze
Customer timeline is generated from:
- customer updates
- contact updates
- lead events
- opportunity events
- quotation events
- activity events
- PO / outcome events
- file / document events
Frozen rule:
- Customer timeline is the relationship history view across all related work, not a separate manually maintained log.
## 23. Calendar Workspace Blueprint Freeze
### Calendar Philosophy
Calendar is the time-based operational workspace across roles.
### Calendar Lenses
- Personal Calendar
- Team Calendar
- Manager Calendar
- Executive Calendar
### Calendar Sources
- Activities
- Meetings
- Visits
- Site Surveys
- Follow-up commitments
- Reminder prompts
- Expected Award Date milestone
- Expected Delivery Date milestone
- Approval due / escalation events
- Quotation expiration / validity milestone
Frozen rules:
- milestone dates can appear in calendar without becoming standalone activities
- milestone events must be visually distinct from owned work
### Calendar Filters
- user
- team
- branch
- customer
- lead
- opportunity
- quotation
- activity type
- priority
- status
- Hot Project only
### Calendar Color Strategy
- Follow-up / task work
- Meeting / visit work
- Reminder prompts
- Opportunity milestone
- Quotation milestone
- Approval due event
Frozen rule:
- colors communicate event family, not authorization level.
### Calendar Views
- Day
- Week
- Month
- Agenda
Agenda view is the default manager-friendly review surface for operational workload.
## 24. My Day Blueprint Freeze
### Purpose
My Day is the personalized operational home screen for action-taking users.
### Required Modules
- Today's Activities
- Overdue Activities
- Upcoming Meetings
- Pending Approvals
- Hot Projects Requiring Action
- Today's Follow-up
- Urgent Quotations
- Relationship Alerts
### Priority Ordering Freeze
My Day orders work by:
1. overdue customer-facing commitments
2. due-today committed meetings / visits
3. urgent quotation and approval blockers
4. Hot Project follow-up gaps
5. scheduled upcoming work
### Urgency Rules
Urgency increases when:
- customer commitment date is today or missed
- expected award date is near
- quotation validity is near expiry
- manager escalated the record
- no next action exists on an open record
Frozen rule:
- My Day should guide the next best operational action, not become a passive report dashboard.
## 25. Manager Workspace Blueprint Freeze
### Purpose
Manager Workspace is the operational control tower for team execution quality.
### Required Sections
- Team Calendar
- Team Activities
- Overdue Activities
- Idle Opportunities
- Forecast Review
- Hot Projects
- Approval Queue
- Workload Balance
- Relationship Risk Alerts
### Daily Management Workflow
1. Review overdue and unowned work.
2. Review Hot Projects without recent activity.
3. Review expected-award opportunities with no next step.
4. Review approval queue and quotation blockers.
5. Rebalance assignments and escalate risks.
6. Review tomorrow's team calendar load.
### Manager Output Freeze
Manager workspace should enable:
- coaching
- escalation
- reassignment
- forecast challenge
- workload balancing
It is not only a KPI readout surface.
## 26. Business Event Blueprint Freeze
### Event Philosophy
Business events are immutable facts emitted from operational changes. One event may fan out to timeline, notification, dashboard, audit, and future automation.
### Business Event Matrix
| Event | Timeline | Notification | Reminder | Dashboard / Workspace | Audit Log | Future Automation |
| --- | --- | --- | --- | --- | --- | --- |
| Activity Created | Yes | Optional assignment notice | Optional | Yes | Yes | Yes |
| Activity Reassigned | Yes | Yes | Optional | Yes | Yes | Yes |
| Activity Completed | Yes | Optional | Close outstanding reminders | Yes | Yes | Yes |
| Activity Cancelled | Yes | Optional | Close reminders | Yes | Yes | Yes |
| Activity Overdue | Optional derived marker | Yes | Yes | Yes | No | Yes |
| Lead Created | Yes | Optional | Optional | Yes | Yes | Yes |
| Lead Assigned / Handoff Ready | Yes | Yes | Optional | Yes | Yes | Yes |
| Opportunity Created | Yes | Optional | Optional | Yes | Yes | Yes |
| Opportunity Reassigned | Yes | Yes | Optional | Yes | Yes | Yes |
| Expected Award Date Changed | Yes | Optional | Yes | Yes | Yes | Yes |
| Hot Project Flagged | Yes | Yes | Optional | Yes | Yes | Yes |
| Quotation Created | Yes | Optional | Optional | Yes | Yes | Yes |
| Quotation Sent | Yes | Optional | Optional | Yes | Yes | Yes |
| Quotation Pending Approval | Yes | Yes | Yes | Yes | Yes | Yes |
| Quotation Approved / Rejected / Returned | Yes | Yes | Close or move reminders | Yes | Yes | Yes |
| Quotation Expiring Soon | Optional | Yes | Yes | Yes | No | Yes |
| Opportunity Marked Won | Yes | Optional | Close forward-chasing reminders | Yes | Yes | Yes |
| Opportunity Marked Lost | Yes | Optional | Close forward-chasing reminders | Yes | Yes | Yes |
| PO Received | Yes | Optional | Optional | Yes | Yes | Yes |
Frozen rules:
- Audit log records mutation truth.
- Timeline records business-readable chronology.
- Dashboard / workspace metrics consume aggregated event effects, not raw notification counts.
## 27. Workspace Navigation Diagram Freeze
```text
My Day
|- Customer Workspace
| |- Contacts
| |- Activities
| |- Timeline
| |- Leads
| |- Opportunities
| |- Quotations
|
|- Lead Workspace
| |- Qualification
| |- Follow-up
| |- Handoff
|
|- Opportunity Workspace
| |- Execution
| |- Follow-up
| |- Forecast
| |- Outcome
|
|- Quotation Workspace
| |- Pricing
| |- Revision
| |- Approval
| |- Customer Package
|
|- Calendar Workspace
| |- Personal
| |- Team
| |- Manager
| |- Executive
|
|- Manager Workspace
| |- Team Activities
| |- Forecast
| |- Hot Projects
| |- Approval Queue
|
`- Executive Workspace
|- Pipeline
|- Revenue Outlook
`- Strategic Accounts
```
## 28. Customer 360 Diagram Freeze
```text
Customer
|- Ownership
|- Contacts
|- Relationship Health
|- Activities / Upcoming Work
|- Timeline
|- Leads
|- Opportunities
|- Quotations
|- PO / Won History
|- Files / Documents
`- Notes / Relationship Summary
```
## 29. Daily User Journey Freeze
### Marketing
```text
My Day -> Lead Queue -> Lead Detail -> Follow-up -> Handoff Ready -> Next Scheduled Action
```
### Sales
```text
My Day -> Opportunity Workspace -> Customer Context -> Quotation Workspace -> Next Activity -> Calendar Check
```
### Manager
```text
Manager Workspace -> Team Calendar -> Overdue / Idle Review -> Forecast Challenge -> Reassignment / Escalation
```
### Executive
```text
Executive Workspace -> Strategic Customer Review -> Pipeline / Revenue Review -> Exception Drill-down
```
## 30. Current-System Alignment Notes
Current implementation signals already supporting this blueprint:
- customer detail already behaves as relationship context plus related opportunity / quotation bridge
- opportunity and quotation already contain follow-up, Hot Project, forecast-related date fields
- dashboard already aggregates follow-up and Hot Project signals
- notification foundation already exists, but current production rules focus mainly on approval events
Current gaps still intentionally unresolved:
- no shared production `Activity` entity yet
- no dedicated calendar workspace yet
- no My Day workspace yet
- manager workspace is not yet implemented as a first-class operational surface
- current `workspaces` navigation still refers to organization / team administration, not business role workspaces
## 31. Freeze Outcome For BU-R.0.1
This pass extends the original blueprint without changing previously frozen principles.
Newly frozen business architecture in this pass:
- Activity as governed shared work model
- Customer Workspace as the relationship execution hub
- Calendar Workspace as cross-role time-based operating surface
- My Day as user action home screen
- Manager Workspace as execution control tower
- Business Event Matrix as the fan-out rule for timeline, notification, dashboard, reminder, and audit behavior

View File

@@ -0,0 +1,71 @@
# Task BU-R.0.1 Implementation Report - 2026-07-07
## Scope
- continue BU-R.0 by freezing the remaining business architecture for Activity, Workspace Interaction, Customer Workspace, Calendar Workspace, My Day, Manager Workspace, and Business Event fan-out
- update the main relationship and sales business blueprint without changing previously frozen BU-R.0 principles
- keep the task documentation-only with no schema, API, UI, service, permission, or ADR changes
## Review Summary
Reviewed before drafting:
- [AGENTS.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/AGENTS.md)
- [plans/task-bu-r.0.1.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/plans/task-bu-r.0.1.md)
- [plans/task-bu-r.0.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/plans/task-bu-r.0.md)
- [docs/standards/task-contract-template.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/standards/task-contract-template.md)
- [docs/standards/task-catalog.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/standards/task-catalog.md)
- [docs/standards/project-foundations.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/standards/project-foundations.md)
- [docs/standards/architecture-rules.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/standards/architecture-rules.md)
- [docs/standards/ui-ux-rules.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/standards/ui-ux-rules.md)
- [docs/standards/task-review-checklist.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/standards/task-review-checklist.md)
- [docs/business/crm-terminology.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/business/crm-terminology.md)
- [docs/business/relationship-sales-workspace-blueprint-v1.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/business/relationship-sales-workspace-blueprint-v1.md)
- [docs/security/crm-authorization-boundaries.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/security/crm-authorization-boundaries.md)
- [docs/adr/0015-customer-ownership-contact-sharing.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/adr/0015-customer-ownership-contact-sharing.md)
- [docs/adr/0016-won-lost-lifecycle-governance.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/adr/0016-won-lost-lifecycle-governance.md)
- [docs/adr/0017-report-foundation.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/adr/0017-report-foundation.md)
- [docs/adr/0018-lead-enquiry-domain-separation.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/adr/0018-lead-enquiry-domain-separation.md)
- [docs/implementation/task-bu-r.0-business-blueprint-freeze-2026-07-07.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/implementation/task-bu-r.0-business-blueprint-freeze-2026-07-07.md)
- [docs/implementation/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)
- current CRM customer, opportunity, quotation, dashboard, notification, and workspace implementations under `src/features/**`, `src/app/dashboard/**`, and `src/db/schema.ts`
## Current-State Findings Used For The Freeze
1. Customer detail already behaves as a relationship context surface with contacts plus linked opportunities and quotations, but it is not yet governed as the official Customer Workspace.
2. Opportunity and quotation features already store follow-up rows, Hot Project flags, and forecast-related dates, which makes them valid current seams for the future shared activity and calendar model.
3. Dashboard already aggregates follow-up and Hot Project signals, but those signals are still oriented around dashboards rather than a broader My Day, Calendar Workspace, or Manager Workspace philosophy.
4. The notification foundation is production-ready, but current event publishing is mainly approval-driven, so activity-driven notification fan-out still needed business governance before implementation.
5. Existing `/dashboard/workspaces` navigation currently means organization/team administration, not the future business-role workspace model. That distinction had to be frozen explicitly to avoid naming drift.
## Documentation Changes
- Expanded [relationship-sales-workspace-blueprint-v1.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/business/relationship-sales-workspace-blueprint-v1.md) with:
- Activity Blueprint Freeze
- Workspace Interaction Blueprint Freeze
- Customer Workspace Blueprint Freeze
- Calendar Workspace Blueprint Freeze
- My Day Blueprint Freeze
- Manager Workspace Blueprint Freeze
- Business Event Matrix
- Activity State Machine
- Workspace Navigation Diagram
- Customer 360 Diagram
- Daily User Journey for Marketing, Sales, Manager, and Executive
- Current-system alignment notes for Phase R.1 audit readiness
## Freeze Decisions Added In This Pass
- Activity is now the officially governed shared work model and remains distinct from Audit Log.
- Calendar is frozen as a workspace projection over activities and milestone events, not a detached scheduling module.
- My Day is frozen as the personalized action home screen prioritized by urgency and commitment risk.
- Manager Workspace is frozen as an execution-control workspace, not only a KPI dashboard.
- Business events are frozen as the common fan-out source for timeline, notification, reminder, dashboard, audit, and future automation behavior.
- Customer Workspace is frozen as the main relationship execution hub and Customer 360 surface.
## Verification
- Documentation-only change.
- No schema, API, UI, service, permission, ADR, or migration files changed.
- No build or test command was required for this pass.
## Outcome
BU-R.0.1 now closes the major business architecture gaps left outside BU-R.0 and leaves Phase R.1 with a clearer audit target for:
- follow-up-to-activity unification
- workspace and navigation semantics
- calendar and reminder projections
- activity-driven notification design
- manager and My Day operational surfaces

View File

@@ -0,0 +1,218 @@
# Task BU-R.1 Implementation Report - 2026-07-07
## Scope
- audit the current ALLA OS implementation against the frozen BU-R.0 and BU-R.0.1 business blueprint
- classify capabilities as `Existing`, `Partial`, `Missing`, `Legacy`, or `Refactor Candidate`
- document preservation, dependency, priority, and readiness guidance for later implementation phases
- keep the phase documentation-only with no schema, API, UI, service, permission, or business-logic changes
## Review Summary
Reviewed before auditing:
- [AGENTS.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/AGENTS.md)
- [plans/task-bu-r.1.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/plans/task-bu-r.1.md)
- [docs/business/relationship-sales-workspace-blueprint-v1.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/business/relationship-sales-workspace-blueprint-v1.md)
- [docs/implementation/task-bu-r.0-business-blueprint-freeze-2026-07-07.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/implementation/task-bu-r.0-business-blueprint-freeze-2026-07-07.md)
- [docs/implementation/task-bu-r.0.1-workspace-activity-business-blueprint-2026-07-07.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/implementation/task-bu-r.0.1-workspace-activity-business-blueprint-2026-07-07.md)
- [docs/standards/project-foundations.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/standards/project-foundations.md)
- [docs/standards/architecture-rules.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/standards/architecture-rules.md)
- [docs/standards/task-review-checklist.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/standards/task-review-checklist.md)
- [docs/security/crm-authorization-boundaries.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/security/crm-authorization-boundaries.md)
- relevant CRM/foundation source under `src/features/crm/**`, `src/features/foundation/**`, `src/app/dashboard/crm/**`, `src/app/api/**`, `src/config/nav-config.ts`, and `src/db/schema.ts`
## Executive Summary
1. Customer, Contact, Opportunity, Quotation, Approval, Dashboard, security, and PDF/document foundations are already mature and should be preserved.
2. Lead capability exists as a real separated workspace and schema, but its follow-up implementation remains lighter and more audit-log-backed than the blueprint target.
3. Follow-up capability is real across lead, opportunity, quotation, and dashboard analytics, but a shared production Activity platform does not exist yet.
4. Timeline, Calendar Workspace, My Day, Manager Workspace, and role-based business workspaces are still mostly target-state architecture, not production capability.
5. Notification foundation is reusable and production-ready, but current live business-event coverage is approval-centric rather than activity-centric.
## 1. Business Capability Matrix
| Domain | Capability | Status | Notes |
| --- | --- | --- | --- |
| Relationship | Customer master, profile, related opportunity/quotation linkage | Existing | Customer detail already acts as a relationship context surface with related commercial records. |
| Relationship | Customer ownership | Existing | Persisted owner assignment plus owner history exists and is governed by ADR-0015. |
| Relationship | Contact sharing and visibility | Existing | Persisted `crm_contact_shares` plus share-aware access enforcement exists. |
| Relationship | Customer account type / prospect classification | Partial | Customer type and status options exist, but relationship-health semantics are not governed in product behavior yet. |
| Relationship | Customer relationship health | Missing | No governed health model, scoring logic, or dedicated UI module yet. |
| Relationship | Customer timeline | Partial | Audit Log and related-record links exist, but no generated cross-entity customer timeline exists. |
| Activity | Lead follow-up | Existing | Lead follow-ups exist, but are stored via audit payloads instead of a dedicated follow-up table. |
| Activity | Opportunity follow-up | Existing | Persisted child resource with CRUD, UI tab, dashboard aggregation, and report reuse exists. |
| Activity | Quotation follow-up | Existing | Persisted child resource with CRUD, UI tab, dashboard aggregation, and report reuse exists. |
| Activity | Shared Activity entity/platform | Partial | Contract-first activity types and permissions exist under `src/features/crm/activity/types.ts`, but there is no production storage/service/UI yet. |
| Activity | Meeting / visit / phone / reminder / internal task | Missing | Only follow-up-oriented capability is implemented today. |
| Activity | Shared activity lifecycle and ownership rules | Partial | Blueprint-ready contract exists; production behavior still fragmented by feature. |
| Lead | Separate lead workspace | Existing | Dedicated pages, service layer, schema, assignment, follow-up, and linked opportunities are live. |
| Lead | Marketing handoff into opportunity | Partial | Linked opportunity visibility exists, but explicit governed conversion workflow is still limited. |
| Lead | Lead outcome derivation from downstream sales | Missing | Lead outcome behavior remains lighter than the blueprint target and ADR-0018 direction. |
| Opportunity | Opportunity ownership and assignment | Existing | Sales assignment, reassignment, branch/product scope, and linked lead provenance are implemented. |
| Opportunity | Forecast fields and probability | Existing | `expectedCloseDate`, `projectCloseDate`, `deliveryDate`, `chancePercent`, and `isHotProject` are live. |
| Opportunity | Expected Award Date / Expected Delivery Date semantics | Partial | Underlying dates exist, but exact blueprint naming/behavior still needs semantic reconciliation. |
| Opportunity | Outcome governance won/lost/reopen/PO | Existing | ADR-0016 behavior is implemented with mark-won, mark-lost, reopen, and PO attachment flows. |
| Commercial | Quotation CRUD, revision, approval, pricing | Existing | Mature quotation feature with revision chain, approval, preview, PDF, and customer package support exists. |
| Commercial | Customer package | Existing | Implemented as approved-PDF plus document-library assembly with permission checks. |
| Commercial | PO integration | Partial | PO capture is implemented on opportunity outcome, but customer-workspace and timeline integration are not yet complete. |
| Approval | Workflow runtime | Existing | Shared approval runtime, steps, actor resolution, notification publishing, and dashboard analytics exist. |
| Approval | Approval automation reminders/escalation | Existing | Reminder and escalation policy foundations are present. |
| Workspace | Customer workspace | Partial | Current customer detail is a strong base, but blueprint sections like Activities, Timeline, Health, Upcoming Work, and Notes are incomplete. |
| Workspace | Sales workspace | Partial | Lead, opportunity, quotation pages exist, but they are entity pages more than one unified role workspace. |
| Workspace | Manager workspace | Missing | No first-class manager control-tower page exists yet. |
| Workspace | Executive workspace | Missing | No dedicated executive workspace exists yet. |
| Workspace | My Day | Missing | No personalized action-home surface exists yet. |
| Workspace | Calendar workspace | Missing | No dedicated calendar route, projection layer, or calendar UI exists yet. |
| Timeline | Generated business timeline | Missing | Audit Log exists, but there is no platform-generated cross-entity timeline model. |
| Dashboard | CRM dashboard KPI foundation | Existing | Summary, funnel, follow-up, approval, revenue, ranking, and hot projects are implemented. |
| Dashboard | Manager / executive-specific dashboard layers | Partial | Current dashboard supports broad KPI visibility, but not fully distinct role workspaces. |
| Notification | Inbox foundation and read/archive flows | Existing | Generic app notifications and inbox UI are production-ready. |
| Notification | Approval notifications | Existing | Approval runtime publishes notification events and inbox surfaces them. |
| Notification | Activity / follow-up / assignment notifications | Missing | Business-event coverage for operational activity is not implemented yet. |
| Event Model | Audit events | Existing | Core audit foundation is widespread and mature. |
| Event Model | Approval events | Existing | Approval event publishing is live. |
| Event Model | Activity-driven business events | Partial | Opportunity and quotation mutations exist, but shared fan-out governance is not yet implemented as one event model. |
## 2. Capability Coverage Report
Coverage values below are qualitative readiness estimates based on audited business scope, not literal line-of-code metrics.
| Domain | Coverage | Summary |
| --- | --- | --- |
| Customer / Relationship | 70% | Strong ownership, sharing, profile, and related-record foundation; missing relationship health and generated timeline. |
| Activity | 35% | Follow-up is real, but shared activity platform, meeting/task/reminder families, and unified lifecycle are not implemented. |
| Lead | 70% | Dedicated domain and workspace exist, but downstream derived outcome and richer handoff workflow remain incomplete. |
| Opportunity | 85% | Assignment, forecast fields, follow-up, hot project, and outcome governance are mature. |
| Quotation | 90% | CRUD, revision, approval, document, package, and pricing foundations are strong. |
| Approval | 90% | Runtime, settings, automation, and dashboard visibility are well-established. |
| Dashboard | 80% | KPI dashboard is live and substantial, but role-specialized workspace behavior is still incomplete. |
| Calendar | 10% | Date fields and reminder policies exist, but no true calendar workspace capability exists. |
| Timeline | 20% | Audit Log exists, but blueprint-grade generated business timeline does not. |
| Notification | 50% | Good reusable foundation, but limited current business-event breadth. |
| Workspace Model | 40% | Entity routes exist, but My Day, Manager, Executive, and Calendar workspaces are still future capability. |
## 3. Gap Analysis: Current System vs Business Blueprint
### No Change
- Customer ownership and contact sharing foundation
- Opportunity outcome governance
- Quotation approval, document, PDF, artifact, and customer package foundations
- CRM dashboard KPI foundation
- CRM authorization and pricing-visibility enforcement
### Enhancement
- Customer detail evolving into Customer Workspace
- Opportunity/quotation date semantics aligning to expected-award and expected-delivery definitions
- Dashboard role layering for manager and executive needs
- Notification foundation expanded from approval-centric events into broader CRM business events
- Lead handoff and downstream outcome synchronization
### Refactor
- Fragmented follow-up behavior into a shared Activity platform over time
- Historical `enquiry` terminology remnants in docs and older lineage
- `workspaces` navigation semantics, which currently mean organization/team administration rather than business-role workspaces
### New Capability
- Generated Timeline
- Calendar Workspace
- My Day
- Manager Workspace
- Executive Workspace
- Activity platform with shared families beyond follow-up
## 4. Architecture Preservation Report
### Keep Unchanged
- `src/features/crm/customers/**`
- `src/features/crm/opportunities/**`
- `src/features/crm/quotations/**`
- `src/features/foundation/approval/**`
- `src/features/foundation/approval-automation/**`
- `src/features/foundation/notifications/**`
- `src/features/foundation/pdf-generator/**`
- `src/features/foundation/document-artifact/**`
- `src/features/crm/dashboard/**`
- `src/lib/auth/crm-access.ts` and CRM security enforcement
### Extend Only
- customer detail and related tabs into Customer Workspace sections
- lead/opportunity/quotation follow-up flows into future Activity adapters
- dashboard into manager and executive role surfaces
- notification event publishing into broader business-event coverage
- nav and workspace routing into clearer role-oriented destinations
### Controlled Refactor Required
- shared activity storage/service/UI
- timeline projection layer
- calendar projection and filtering layer
- terminology cleanup across historical docs and edge code paths
### Backward Compatibility Concerns
- lead follow-up currently depends on audit-log payloads rather than a dedicated persisted follow-up table
- approval and notification fan-out already exist for approvals, so later activity events must avoid double-publishing behavior
- dashboard/service/reporting logic already depends on current follow-up storage, so activity migration must preserve analytics continuity
- current `workspaces` routes are already used for organization/team administration and should not be silently repurposed
## 5. Business Capability Dependency Map
```text
Customer / Contact
|- Lead
| `- Opportunity
| |- Follow-up / Future Activity Platform
| |- Quotation
| | |- Approval
| | |- PDF / Artifact / Customer Package
| | `- Commercial Notifications
| |- Dashboard / Reports
| `- Won / Lost / PO
|
`- Future Customer Workspace
|- Timeline
|- Calendar Projection
|- My Day
`- Manager / Executive Workspace
```
## 6. Capability Priority Matrix
| Epic / Capability | Priority | Why |
| --- | --- | --- |
| Activity Platform | Critical | It is the main missing shared business model and blocks Calendar, Timeline, My Day, and richer notifications. |
| Customer Workspace | Critical | Customer is the relationship anchor and already has a strong partial base worth extending. |
| Timeline | High | Required for blueprint-aligned relationship history and event visibility. |
| Calendar Workspace | High | Strong business need, but depends on activity/event projection clarity. |
| My Day | High | Key daily operating surface and natural consumer of activity, reminders, and approvals. |
| Manager Workspace | High | Needed for operational control, workload balancing, and hot-project governance. |
| Notification Expansion | Medium | Foundation exists; main work is business-event coverage and orchestration. |
| Executive Workspace | Medium | Valuable, but depends on manager/dashboard/timeline foundations first. |
| Terminology / legacy cleanup | Medium | Important for governance clarity, but not as blocking as Activity or Workspace delivery. |
## 7. Implementation Readiness Report
| Area | Readiness | Notes |
| --- | --- | --- |
| Customer Workspace | Requires UI enhancement | Data foundation is strong; sections like health, upcoming work, and relationship summary need expansion. |
| Activity Platform | Requires schema + service + UI enhancement | Only contract-first types exist today. |
| Lead lifecycle enhancement | Requires service + UI enhancement | Existing lead feature is usable, but derived outcome/handoff depth is incomplete. |
| Opportunity forecast semantics | Requires service + UI enhancement | Core fields exist already. |
| Quotation commercial execution | Ready immediately | Mature enough to preserve and extend. |
| Approval runtime | Ready immediately | Mature enough to preserve and extend. |
| Dashboard role layering | Requires UI + service enhancement | Foundation exists and is reusable. |
| Timeline | Requires schema/service/UI future phase | No true generated timeline capability yet. |
| Calendar Workspace | Requires schema/service/UI future phase | No production projection layer or UI route exists yet. |
| My Day | Requires service/UI future phase | Depends on activity, reminder, approval, and hot-project orchestration. |
| Notification expansion | Requires service enhancement | Foundation exists; business-event coverage does not. |
## 8. Candidate Epics After BU-R.1
- Epic: Customer Workspace
- Epic: Activity Platform
- Epic: Timeline Projection
- Epic: Calendar Workspace
- Epic: My Day
- Epic: Manager Workspace
- Epic: Executive Workspace
- Epic: Notification Event Expansion
- Epic: Lead Handoff and Outcome Alignment
- Epic: Terminology and Governance Reconciliation
## Verification
- Documentation-only change.
- No schema, API, UI, service, permission, or business-logic files were modified for runtime behavior.
- No build or test command was required for this audit pass.
## Outcome
BU-R.1 confirms that the repo already has a strong production backbone for relationship, opportunity, quotation, approval, document, dashboard, and security work. The biggest blueprint gaps are no longer hidden inside core CRUD; they are concentrated in the cross-cutting operating model: shared Activity, Timeline, Calendar, My Day, Manager Workspace, Executive Workspace, and business-event-driven notifications.

501
plans/task-bu-r.0.1.md Normal file
View File

@@ -0,0 +1,501 @@
# Task BU-R.0.1 Workspace & Activity Business Blueprint Completion
Status: Planning
Priority: Critical
Type: Business Discovery / Business Architecture
Depends On:
- BU-R.0 Business Blueprint Freeze
---
# Objective
Complete the remaining business architecture that was intentionally left outside BU-R.0 before beginning Phase R.1 Business Capability Audit.
This phase completes the operational workspace philosophy of ALLA OS by defining:
- Activity Blueprint
- Workspace Interaction Blueprint
- Customer Workspace Blueprint
This task remains documentation-only.
No implementation, schema, API, UI, or migration work is allowed.
---
# Background
BU-R.0 successfully froze the core business architecture.
However several operational concepts still require business definition before implementation or capability audit.
The largest remaining gaps are:
- Activity Lifecycle
- Workspace Interaction
- Customer Workspace
- Daily User Workflow
Without these definitions, future Calendar, Timeline, Notification, Dashboard, and My Day implementations may diverge.
---
# Review Required
Review:
- Relationship & Sales Workspace Blueprint v1
- BU-R.0 Implementation Report
- Existing CRM UI
- Existing Customer UI
- Existing Opportunity Workspace
- Existing Quotation Workspace
- Existing Dashboard
- Existing Calendar discussions
- Existing Follow-up implementation
- Existing Task implementation
- Existing Notification implementation
Review current schema only for understanding.
Do not redesign existing foundations.
---
# Scope
## Part 1 — Activity Blueprint
Freeze Activity as the shared operational business model.
Determine
- Activity Definition
- Activity Ownership
- Activity Lifecycle
- Activity Types
- Activity Priority
- Activity Status
- Activity Assignment
- Activity Completion Rules
- Activity Visibility
- Activity Permission
- Activity Relationships
Determine whether Activity may reference
- Customer
- Contact
- Lead
- Opportunity
- Quotation
- PO
- Internal Only
Determine
- Follow-up Strategy
- Reminder Strategy
- Automation Strategy
Determine
- Calendar Synchronization
- Timeline Synchronization
- Notification Synchronization
Freeze the Activity State Machine.
---
## Part 2 — Workspace Interaction Blueprint
Freeze how each business role operates throughout an entire working day.
Define complete workflows for
Marketing
Sales
Sales Manager
Executive
Determine
Login Experience
Primary Landing Page
Workspace Navigation
My Day
Calendar Usage
Timeline Usage
Notification Usage
Customer Navigation
Lead Workflow
Opportunity Workflow
Quotation Workflow
Determine
Daily User Journey
instead of only entity relationships.
---
## Part 3 — Customer Workspace Blueprint
Freeze Customer as the Relationship Workspace.
Determine Customer Workspace layout.
Example sections
Overview
Contacts
Activities
Timeline
Leads
Opportunities
Quotations
PO
Files
Notes
Relationship Summary
Recent Visits
Upcoming Activities
Determine
Customer Timeline
Customer Relationship Health
Customer Follow-up Health
Customer Project History
Determine
Customer 360 View.
---
## Part 4 — Calendar Workspace Blueprint
Expand the Calendar philosophy.
Determine
Personal Calendar
Team Calendar
Manager Calendar
Executive Calendar
Determine
Calendar Sources
Activities
Meetings
Visits
Site Survey
Reminder
Task
Expected Award Date
Expected Delivery Date
Approval Due
Quotation Expiration
Determine
Calendar Filters
Calendar Colors
Calendar Views
Day
Week
Month
Agenda
---
## Part 5 — My Day Blueprint
Freeze
My Day
as the operational home screen.
Determine
Today's Activities
Overdue Activities
Upcoming Meetings
Pending Approvals
Hot Projects
Today's Follow-up
Urgent Quotations
Manager Tasks
Relationship Alerts
Determine
Priority Ordering
Sorting Rules
Urgency Rules
---
## Part 6 — Manager Workspace Blueprint
Freeze
Manager Workspace
Determine
Team Calendar
Team Activities
Overdue Activities
Idle Opportunities
Forecast
Hot Projects
Approval Queue
Workload Balance
Determine
Daily Management Workflow
---
## Part 7 — Business Event Blueprint
Identify every business event that should create
Timeline
Notification
Reminder
Dashboard Update
Audit Log
Future Automation
Examples
Activity Completed
Lead Assigned
Opportunity Created
Quotation Sent
Quotation Approved
Hot Project Flagged
Expected Award Date Changed
PO Received
---
# Deliverables
Produce
## 1
Activity Blueprint
---
## 2
Workspace Interaction Blueprint
---
## 3
Customer Workspace Blueprint
---
## 4
Calendar Workspace Blueprint
---
## 5
My Day Blueprint
---
## 6
Manager Workspace Blueprint
---
## 7
Business Event Matrix
---
## 8
Activity State Machine
---
## 9
Workspace Navigation Diagram
---
## 10
Customer 360 Diagram
---
## 11
Daily User Journey
Marketing
Sales
Manager
Executive
---
## 12
Updated Relationship & Sales Workspace Blueprint v1
Append these new chapters without changing frozen principles from BU-R.0.
---
# Constraints
This task is documentation only.
DO NOT
- modify schema
- modify migrations
- modify API
- modify services
- modify UI
- modify permissions
- modify database
- modify existing ADR decisions
Preserve current foundation.
Prefer extension over replacement.
---
# Success Criteria
The business operation of every role is fully documented.
Activity becomes the officially governed operational model.
Workspace interaction is fully standardized.
Customer Workspace is finalized.
Calendar philosophy is finalized.
My Day philosophy is finalized.
Manager Workspace is finalized.
Business Event model is frozen.
Blueprint reaches implementation-ready maturity.
Ready for
Phase R.1 Business Capability Audit.

617
plans/task-bu-r.1.md Normal file
View File

@@ -0,0 +1,617 @@
# Task BU-R.1 Business Capability Audit
Status: Planning
Priority: Critical
Type: Business Discovery / Capability Audit
Depends On
- BU-R.0 Business Blueprint Freeze
- BU-R.0.1 Workspace & Activity Business Blueprint Completion
---
# Objective
Audit the current ALLA OS implementation against the frozen Business Blueprint.
This phase must identify which business capabilities already exist, which are partially implemented, which require enhancement, and which should be introduced as new capabilities.
The purpose is to minimize disruption to the existing architecture while ensuring future implementation aligns with the approved business blueprint.
This is a documentation and analysis phase only.
No implementation work is allowed.
---
# Background
BU-R.0 and BU-R.0.1 established the official Business Constitution of ALLA OS.
The current repository already contains a mature CRM foundation including:
- Customer
- Contact
- Lead
- Opportunity
- Quotation
- Approval
- Document
- Organization
- RBAC
- PDF
- Dashboard
The next step is to determine how closely the current implementation aligns with the frozen business architecture.
---
# Review Required
Review all relevant documentation before auditing.
Minimum review
- AGENTS.md
- Project Standards
- Architecture Rules
- UI/UX Rules
- Task Catalog
- CRM Terminology
- Relationship & Sales Workspace Blueprint
- Existing ADRs
- Current Schema
- Current CRM APIs
- Existing Dashboard
- Existing Customer Workspace
- Existing Lead Workspace
- Existing Opportunity Workspace
- Existing Quotation Workspace
- Existing Approval Module
- Existing Notification Module
Review source code only for capability verification.
Do not redesign.
Do not implement.
---
# Audit Scope
---
## Part 1 — Relationship Capability Audit
Review
Customer
Contact
Customer Account Type
Customer Ownership
Contact Sharing
Relationship Health
Customer Timeline
Customer Workspace
Determine
Existing capability
Missing capability
Refactor candidates
Future enhancements
---
## Part 2 — Activity Capability Audit
Review
Follow-up
Meeting
Visit
Phone Call
Reminder
Task
Notification
Internal Task
Determine
Current activity implementation
Duplicate activity concepts
Reusable components
Potential shared Activity model
Activity ownership
Activity lifecycle support
Calendar readiness
Timeline readiness
---
## Part 3 — Lead Capability Audit
Review
Lead lifecycle
Lead ownership
Lead assignment
Lead qualification
Lead conversion
Lead follow-up
Lead dashboard
Determine
Blueprint compliance
Missing capabilities
Legacy behaviour
---
## Part 4 — Opportunity Capability Audit
Review
Opportunity ownership
Forecast
Expected Award Date
Expected Delivery Date
Probability
Hot Project
Pipeline
Outcome
Process Status
Status
Determine
Business alignment
Schema readiness
Service readiness
UI readiness
---
## Part 5 — Commercial Capability Audit
Review
Quotation
Revision
Approval
Pricing
PDF
Customer Package
PO integration
Determine
Blueprint compliance
Missing capabilities
---
## Part 6 — Workspace Capability Audit
Review
Customer Workspace
Sales Workspace
Manager Workspace
Executive Workspace
Calendar
Timeline
My Day
Notification
Dashboard
Determine
Existing workspaces
Navigation gaps
Role support
Operational readiness
---
## Part 7 — Dashboard Capability Audit
Review
Pipeline
Forecast
Hot Project
Follow-up
Overdue Work
Sales KPI
Manager KPI
Executive KPI
Determine
Current implementation
Metric ownership
Business alignment
---
## Part 8 — Notification Capability Audit
Review
Approval Notification
Reminder
Follow-up Notification
Manager Escalation
Assignment Notification
Determine
Current notification model
Missing business events
Automation opportunities
---
## Part 9 — Business Event Audit
Review
Lead Events
Opportunity Events
Quotation Events
Approval Events
Customer Events
Determine
Existing events
Missing events
Timeline support
Calendar support
Automation readiness
---
# Deliverables
Produce
## 1
Business Capability Matrix
For every capability identify
- Existing
- Partial
- Missing
- Legacy
- Refactor Candidate
---
## 2
Capability Coverage Report
Percentage coverage
Customer
Activity
Lead
Opportunity
Quotation
Approval
Dashboard
Calendar
Timeline
Notification
Workspace
---
## 3
Gap Analysis
Current System
vs
Business Blueprint
Categorize
No Change
Enhancement
Refactor
New Capability
---
## 4
Architecture Preservation Report
Identify
Core components that should remain unchanged
Core components requiring extension only
Components requiring controlled refactoring
Potential breaking changes
Backward compatibility concerns
---
## 5
Business Capability Dependency Map
Show dependency between
Customer
Activity
Lead
Opportunity
Quotation
Approval
Dashboard
Calendar
Timeline
Notification
---
## 6
Capability Priority Matrix
Prioritize
Critical
High
Medium
Low
based on business value and implementation impact.
---
## 7
Implementation Readiness Report
Identify
Ready immediately
Requires schema enhancement
Requires service enhancement
Requires UI enhancement
Requires future phase
---
## 8
Recommended Epic Breakdown
Group future implementation into epics.
Example
Epic
Customer Workspace
Epic
Activity Platform
Epic
Calendar Workspace
Epic
Timeline
Epic
Manager Workspace
Epic
My Day
Epic
Notification
Epic
Dashboard
---
# Constraints
This phase is documentation only.
DO NOT
- modify schema
- modify database
- modify migrations
- modify APIs
- modify services
- modify UI
- modify permissions
- modify business logic
No code changes are permitted.
---
# Success Criteria
Every business capability has been audited.
Current implementation is mapped to the approved Business Blueprint.
No duplicate business capability remains unidentified.
The impact of every future feature is understood.
Core architecture preservation strategy is documented.
A prioritized implementation roadmap can be produced without re-discovering business requirements.
Ready for
BU-R.2 Domain & Schema Audit.
# Implementation Result - 2026-07-07
Status: Completed
Completed:
- audited current customer, lead, opportunity, quotation, approval, dashboard, notification, workspace, and security capabilities against the frozen BU-R.0 and BU-R.0.1 blueprint
- classified current implementation into `Existing`, `Partial`, `Missing`, `Legacy`, and `Refactor Candidate` capability states
- documented preservation-safe direction for later phases without changing code or schema
Primary findings:
- customer ownership, contact sharing, opportunity lifecycle, quotation lifecycle, approval runtime, PDF/document delivery, dashboard KPIs, and CRM security are already strong foundations and should be preserved
- follow-up capability is real across lead, opportunity, quotation, and dashboard analytics, but a shared production Activity platform does not yet exist
- customer detail is a strong partial Customer Workspace, but generated timeline, relationship health, and activity-centered workspace sections are still missing
- calendar, My Day, manager workspace, executive workspace, and generated timeline remain mostly future capability rather than current implementation
- notification foundation exists and is production-ready, but business-event coverage is still mostly approval-centric
Recorded outputs:
- [task-bu-r.1-business-capability-audit-2026-07-07.md](/C:/Users/mtpphtaps/Documents/gitea/alla-allaos-fullstack/docs/implementation/task-bu-r.1-business-capability-audit-2026-07-07.md)
Verification:
- documentation-only phase
- no schema, API, service, UI, permission, or business-logic changes made
- no build or test command required

View File

@@ -10,6 +10,14 @@ import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import {
Sheet,
@@ -19,7 +27,6 @@ import {
SheetHeader,
SheetTitle,
} from '@/components/ui/sheet';
import { Separator } from '@/components/ui/separator';
import { useAppForm, useFormFields } from '@/components/ui/tanstack-form';
import { formatDateTime } from '@/lib/date-format';
import { cn } from '@/lib/utils';
@@ -120,7 +127,6 @@ function SecurityNote({ title, description }: { title: string; description: stri
function ConfigCard({
configuration,
sendRecipientEmail,
onEdit,
onDelete,
onTestConnection,
@@ -130,7 +136,6 @@ function ConfigCard({
isSending,
}: {
configuration: EmailConfigurationSummary;
sendRecipientEmail: string;
onEdit: (configuration: EmailConfigurationSummary) => void;
onDelete: (configuration: EmailConfigurationSummary) => void;
onTestConnection: (configuration: EmailConfigurationSummary) => void;
@@ -218,7 +223,6 @@ function ConfigCard({
type='button'
onClick={() => onSendTest(configuration)}
isLoading={isSending}
disabled={!sendRecipientEmail.trim()}
>
<Icons.send className='mr-2 h-4 w-4' />
Send test email
@@ -238,10 +242,93 @@ function ConfigCard({
);
}
function QuickVerificationDialog({
configuration,
recipientEmail,
onRecipientEmailChange,
onOpenChange,
onSubmit,
isSending,
}: {
configuration: EmailConfigurationSummary | null;
recipientEmail: string;
onRecipientEmailChange: (value: string) => void;
onOpenChange: (open: boolean) => void;
onSubmit: () => void;
isSending: boolean;
}) {
return (
<Dialog open={configuration !== null} onOpenChange={onOpenChange}>
<DialogContent className='sm:max-w-md'>
<DialogHeader>
<DialogTitle>Quick verification</DialogTitle>
<DialogDescription>
{configuration
? `Send a test email through ${configuration.name} to verify the active SMTP route.`
: 'Send a test email to verify the active SMTP route.'}
</DialogDescription>
</DialogHeader>
<div className='space-y-4'>
{configuration ? (
<div className='rounded-xl border border-border/60 bg-muted/30 p-3 text-sm'>
<div className='font-medium text-foreground'>{configuration.name}</div>
<div className='mt-1 text-muted-foreground'>
{configuration.host}:{configuration.port} via{' '}
{configuration.secure ? 'TLS/SSL' : 'STARTTLS / plain'}
</div>
</div>
) : null}
<div className='space-y-2'>
<label className='text-sm font-medium' htmlFor='email-test-recipient'>
Test recipient
</label>
<Input
id='email-test-recipient'
type='email'
value={recipientEmail}
onChange={(event) => onRecipientEmailChange(event.target.value)}
placeholder='ops@example.com'
/>
</div>
<div className='space-y-3 text-sm text-muted-foreground'>
<div className='flex items-start gap-3'>
<Icons.check className='mt-0.5 h-4 w-4 text-primary' />
<span>Connection test updates health state without exposing the stored password.</span>
</div>
<div className='flex items-start gap-3'>
<Icons.lock className='mt-0.5 h-4 w-4 text-primary' />
<span>Stored passwords can be replaced or cleared, but are never returned from the API.</span>
</div>
<div className='flex items-start gap-3'>
<Icons.settings className='mt-0.5 h-4 w-4 text-primary' />
<span>Setup wizard and notification runtime use the same organization-level SMTP source.</span>
</div>
</div>
</div>
<DialogFooter>
<Button type='button' variant='outline' onClick={() => onOpenChange(false)} disabled={isSending}>
Cancel
</Button>
<Button type='button' onClick={onSubmit} isLoading={isSending} disabled={!recipientEmail.trim()}>
<Icons.send className={cn('mr-2 h-4 w-4', isSending && 'hidden')} />
Send test email
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
export function EmailConfigurationPage() {
const [sheetOpen, setSheetOpen] = useState(false);
const [editingConfiguration, setEditingConfiguration] = useState<EmailConfigurationSummary | null>(null);
const [sendRecipientEmail, setSendRecipientEmail] = useState('');
const [quickVerificationConfiguration, setQuickVerificationConfiguration] =
useState<EmailConfigurationSummary | null>(null);
const [quickVerificationRecipientEmail, setQuickVerificationRecipientEmail] = useState('');
const emailConfigurationsQuery = useQuery(emailConfigurationsQueryOptions());
const createMutation = useMutation(createEmailConfigurationMutation);
@@ -336,12 +423,18 @@ export function EmailConfigurationPage() {
}
}
async function handleSendTest(configuration: EmailConfigurationSummary) {
async function handleSendTest() {
if (!quickVerificationConfiguration) {
return;
}
const normalizedRecipientEmail = quickVerificationRecipientEmail.trim().toLowerCase();
try {
const result = await sendTestEmailMutation.mutateAsync({
id: configuration.id,
id: quickVerificationConfiguration.id,
payload: {
recipientEmail: sendRecipientEmail.trim().toLowerCase(),
recipientEmail: normalizedRecipientEmail,
},
});
@@ -350,7 +443,8 @@ export function EmailConfigurationPage() {
return;
}
toast.success(`Test email queued to ${sendRecipientEmail.trim().toLowerCase()}.`);
toast.success(`Test email queued to ${normalizedRecipientEmail}.`);
setQuickVerificationConfiguration(null);
} catch (error) {
toast.error(error instanceof Error ? error.message : 'Unable to send test email.');
}
@@ -402,29 +496,16 @@ export function EmailConfigurationPage() {
<Card className='border-border/60 bg-background/80 shadow-none'>
<CardHeader>
<CardTitle>Quick verification</CardTitle>
<CardTitle>Operator actions</CardTitle>
<CardDescription>
Use one test recipient while reviewing multiple SMTP profiles.
Create and maintain SMTP routes for setup, notifications, and approvals.
</CardDescription>
</CardHeader>
<CardContent className='space-y-4'>
<div className='space-y-2'>
<label className='text-sm font-medium' htmlFor='email-test-recipient'>
Test recipient
</label>
<Input
id='email-test-recipient'
type='email'
value={sendRecipientEmail}
onChange={(event) => setSendRecipientEmail(event.target.value)}
placeholder='ops@example.com'
/>
</div>
<Separator />
<div className='space-y-3 text-sm text-muted-foreground'>
<div className='flex items-start gap-3'>
<Icons.check className='mt-0.5 h-4 w-4 text-primary' />
<span>Connection test updates the configuration health state without exposing the password.</span>
<span>Add a route, then use each row&apos;s quick verification modal to send a test email.</span>
</div>
<div className='flex items-start gap-3'>
<Icons.lock className='mt-0.5 h-4 w-4 text-primary' />
@@ -508,14 +589,15 @@ export function EmailConfigurationPage() {
<ConfigCard
key={configuration.id}
configuration={configuration}
sendRecipientEmail={sendRecipientEmail}
onEdit={(item) => {
setEditingConfiguration(item);
setSheetOpen(true);
}}
onDelete={handleDelete}
onTestConnection={handleTestConnection}
onSendTest={handleSendTest}
onSendTest={(item) => {
setQuickVerificationConfiguration(item);
}}
isDeleting={deleteMutation.isPending && deleteMutation.variables === configuration.id}
isTesting={
testConnectionMutation.isPending &&
@@ -672,6 +754,19 @@ export function EmailConfigurationPage() {
</SheetFooter>
</SheetContent>
</Sheet>
<QuickVerificationDialog
configuration={quickVerificationConfiguration}
recipientEmail={quickVerificationRecipientEmail}
onRecipientEmailChange={setQuickVerificationRecipientEmail}
onOpenChange={(open) => {
if (!open) {
setQuickVerificationConfiguration(null);
}
}}
onSubmit={handleSendTest}
isSending={sendTestEmailMutation.isPending}
/>
</div>
);
}

View File

@@ -1,42 +1,53 @@
import 'server-only';
import "server-only";
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto';
import {
createCipheriv,
createDecipheriv,
createHash,
randomBytes,
} from "node:crypto";
const ENCRYPTION_PREFIX = 'enc:v1';
const ENCRYPTION_ENV_KEY = 'EMAIL_CONFIG_ENCRYPTION_KEY';
const ENCRYPTION_PREFIX = "enc:v1";
const ENCRYPTION_ENV_KEY = "EMAIL_CONFIG_ENCRYPTION_KEY";
const MIN_KEY_BYTES = 32;
function decodeConfiguredKey(rawValue: string): Buffer {
const value = rawValue.trim();
if (/^[0-9a-fA-F]+$/.test(value) && value.length % 2 === 0) {
return Buffer.from(value, 'hex');
return Buffer.from(value, "hex");
}
try {
const base64Buffer = Buffer.from(value, 'base64');
if (base64Buffer.length > 0 && base64Buffer.toString('base64').replace(/=+$/, '') === value.replace(/=+$/, '')) {
const base64Buffer = Buffer.from(value, "base64");
if (
base64Buffer.length > 0 &&
base64Buffer.toString("base64").replace(/=+$/, "") ===
value.replace(/=+$/, "")
) {
return base64Buffer;
}
} catch {
// Fall back to UTF-8 below.
}
return Buffer.from(value, 'utf8');
return Buffer.from(value, "utf8");
}
function getEncryptionKeyMaterial(): Buffer {
const configured = process.env[ENCRYPTION_ENV_KEY]?.trim() ?? '';
const configured = process.env[ENCRYPTION_ENV_KEY]?.trim() ?? "";
if (!configured) {
throw new Error(`${ENCRYPTION_ENV_KEY} is not configured.`);
}
const keyMaterial = decodeConfiguredKey(configured);
if (keyMaterial.byteLength < MIN_KEY_BYTES) {
throw new Error(`${ENCRYPTION_ENV_KEY} must provide at least ${MIN_KEY_BYTES} bytes of key material.`);
throw new Error(
`${ENCRYPTION_ENV_KEY} must provide at least ${MIN_KEY_BYTES} bytes of key material.`,
);
}
return createHash('sha256').update(keyMaterial).digest();
return createHash("sha256").update(keyMaterial).digest();
}
export function assertSecretsEncryptionReady(): void {
@@ -46,37 +57,49 @@ export function assertSecretsEncryptionReady(): void {
export function encryptSecret(plainText: string): string {
const normalized = plainText.trim();
if (!normalized) {
throw new Error('Secret value is required for encryption.');
throw new Error("Secret value is required for encryption.");
}
const key = getEncryptionKeyMaterial();
const iv = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', key, iv);
const encrypted = Buffer.concat([cipher.update(normalized, 'utf8'), cipher.final()]);
const cipher = createCipheriv("aes-256-gcm", key, iv);
const encrypted = Buffer.concat([
cipher.update(normalized, "utf8"),
cipher.final(),
]);
const tag = cipher.getAuthTag();
return [
ENCRYPTION_PREFIX,
iv.toString('base64'),
tag.toString('base64'),
encrypted.toString('base64'),
].join(':');
iv.toString("base64"),
tag.toString("base64"),
encrypted.toString("base64"),
].join(":");
}
export function decryptSecret(cipherText: string): string {
const [prefix, ivPart, tagPart, encryptedPart] = cipherText.split(':');
if (prefix !== ENCRYPTION_PREFIX || !ivPart || !tagPart || !encryptedPart) {
throw new Error('Encrypted secret format is invalid.');
if (!cipherText.startsWith(`${ENCRYPTION_PREFIX}:`)) {
throw new Error("Encrypted secret format is invalid.");
}
const payload = cipherText.slice(ENCRYPTION_PREFIX.length + 1);
const [ivPart, tagPart, encryptedPart, ...extraParts] = payload.split(":");
if (!ivPart || !tagPart || !encryptedPart || extraParts.length > 0) {
throw new Error("Encrypted secret format is invalid.");
}
const key = getEncryptionKeyMaterial();
const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(ivPart, 'base64'));
decipher.setAuthTag(Buffer.from(tagPart, 'base64'));
const decipher = createDecipheriv(
"aes-256-gcm",
key,
Buffer.from(ivPart, "base64"),
);
decipher.setAuthTag(Buffer.from(tagPart, "base64"));
const plain = Buffer.concat([
decipher.update(Buffer.from(encryptedPart, 'base64')),
decipher.update(Buffer.from(encryptedPart, "base64")),
decipher.final(),
]);
return plain.toString('utf8');
return plain.toString("utf8");
}

View File

@@ -0,0 +1,37 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
decryptSecret,
encryptSecret,
} from '../../features/foundation/secrets/server/crypto.ts';
const previousKey = process.env.EMAIL_CONFIG_ENCRYPTION_KEY;
test.before(() => {
process.env.EMAIL_CONFIG_ENCRYPTION_KEY =
'0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
});
test.after(() => {
if (typeof previousKey === 'string') {
process.env.EMAIL_CONFIG_ENCRYPTION_KEY = previousKey;
return;
}
delete process.env.EMAIL_CONFIG_ENCRYPTION_KEY;
});
test('encryptSecret output decrypts back to the original value', () => {
const encrypted = encryptSecret('smtp-password');
assert.match(encrypted, /^enc:v1:/);
assert.equal(decryptSecret(encrypted), 'smtp-password');
});
test('decryptSecret rejects malformed ciphertext', () => {
assert.throws(
() => decryptSecret('enc:v1:missing-parts'),
/Encrypted secret format is invalid\./,
);
});