Compare commits

...

2 Commits

Author SHA1 Message Date
f1b68e5e78 Version 2.0 2026-05-12 09:23:05 +00:00
f2bc048219 update DOC 2026-05-12 07:18:09 +00:00
45 changed files with 1104 additions and 493 deletions

227
AGENTS.md
View File

@@ -3,19 +3,25 @@
> **Trước khi làm việc, đọc các file quan trọng:** > **Trước khi làm việc, đọc các file quan trọng:**
> - `CODEBASE_SNAPSHOT.md` — Toàn bộ cấu trúc codebase (thay vì scan lại code) > - `CODEBASE_SNAPSHOT.md` — Toàn bộ cấu trúc codebase (thay vì scan lại code)
> - `TASKS_ROADMAP.md` — Roadmap: đã làm, đang làm, sẽ làm > - `TASKS_ROADMAP.md` — Roadmap: đã làm, đang làm, sẽ làm
> - `PROGRESS.md` — Lịch sử tiến độ hoàn thành
> - `docs/I18N_GUIDE.md` — Hướng dẫn đa ngôn ngữ > - `docs/I18N_GUIDE.md` — Hướng dẫn đa ngôn ngữ
> - `docs/ENUM_GUIDE.md` — Hướng dẫn thêm Enum mới > - `docs/ENUM_GUIDE.md` — Hướng dẫn thêm Enum mới
> - `luutru/` — Archive các file đã lỗi thời (tham khảo nếu cần)
>
> **File đã lỗi thời trong luutru/:** PROGRESS.md, SOP_des.md, AI_01/02/03, CHANGELOG.md, README.md gốc, SYSTEM_ASSESSMENT_PROPOSALS.md
## Overview ## Overview
AfterSales CRM is a real-estate after-sales customer care system built with **Laravel 13.6** + **Filament 5.6**. AfterSales CRM is a real-estate after-sales customer care system built with **Laravel 13.6** + **Filament 5.6**.
Hệ thống có **2 Filament Panel**:
- `/admin` — Admin Panel: đầy đủ tất cả modules (Contract, Handover, Service, User/Role...)
- `/support` — Support Panel: rút gọn, tập trung Feedback (Feedback, Customer, Product, Channel, Tag, ActivityLog)
## How to Run ## How to Run
```bash ```bash
cd /home/phuongtc/vibecode/minicrm cd /home/phuongtc/vibecode/minicrm
php artisan migrate:fresh --seed php artisan migrate:fresh --seed
php artisan serve php artisan serve
# Open http://localhost:8000/admin # Admin panel: http://localhost:8000/admin
# Support panel: http://localhost:8000/support
``` ```
### Test Accounts (seeded) ### Test Accounts (seeded)
@@ -51,8 +57,30 @@ php artisan test # run pest tests
php artisan app:export-backup php artisan app:export-backup
php artisan app:export-backup --path=/custom/path --pretty php artisan app:export-backup --path=/custom/path --pretty
php artisan app:export-backup --tables=feedback,customers,products php artisan app:export-backup --tables=feedback,customers,products
# Import data from Excel
php artisan app:import-cskh ai_instructions/CSKH.xlsx --dry-run
php artisan app:import-cskh ai_instructions/CSKH.xlsx
``` ```
## Dual Panel Architecture
Hệ thống có 2 Filament Panel độc lập:
### Admin Panel (`/admin`) — `AdminPanelProvider.php`
Đầy đủ tất cả modules, bao gồm:
- Feedback, Customer, Product, Contract, FeedbackChannel, FeedbackTag
- User, Role (admin-only)
- 3 Dashboard widgets: ResolvedTicketsWidget, AvgProcessingTimeWidget, HandlerPerformanceWidget
### Support Panel (`/support`) — `SupportPanelProvider.php`
Rút gọn, chỉ tập trung vào quy trình xử lý feedback:
- Feedback, Customer, Product, FeedbackChannel, FeedbackTag, ActivityLog
- 3 Dashboard widgets giống Admin panel
- Không có: Contracts, Users, Roles, Handovers, ProductServices
Cả 2 panel dùng chung: Models, Services, Policies, Database, Translations.
## Directory Structure ## Directory Structure
``` ```
@@ -60,6 +88,9 @@ minicrm/
├── app/ ├── app/
│ ├── Filament/ │ ├── Filament/
│ │ ├── Resources/ │ │ ├── Resources/
│ │ │ ├── ActivityLogs/ # NEW: Audit trail (read-only)
│ │ │ │ ├── ActivityLogResource.php
│ │ │ │ └── Pages/ListActivityLogs.php
│ │ │ ├── Feedback/ │ │ │ ├── Feedback/
│ │ │ │ ├── FeedbackResource.php │ │ │ │ ├── FeedbackResource.php
│ │ │ │ ├── Schemas/FeedbackForm.php │ │ │ │ ├── Schemas/FeedbackForm.php
@@ -67,78 +98,119 @@ minicrm/
│ │ │ │ ├── Pages/{Create,Edit,List}Feedback.php │ │ │ │ ├── Pages/{Create,Edit,List}Feedback.php
│ │ │ │ └── RelationManagers/InteractionsRelationManager.php │ │ │ │ └── RelationManagers/InteractionsRelationManager.php
│ │ │ ├── Products/ │ │ │ ├── Products/
│ │ │ │ └── RelationManagers/{Contracts,Handovers,ProductServices}RelationManager.php
│ │ │ ├── Customers/ │ │ │ ├── Customers/
│ │ │ │ └── RelationManagers/FeedbacksRelationManager.php │ │ │ │ └── RelationManagers/FeedbacksRelationManager.php
│ │ │ ├── Contracts/
│ │ │ ├── FeedbackChannels/ │ │ │ ├── FeedbackChannels/
│ │ │ ├── FeedbackTags/ │ │ │ ├── FeedbackTags/
│ │ │ ├── Contracts/
│ │ │ ├── Users/ │ │ │ ├── Users/
│ │ │ └── Roles/ │ │ │ └── Roles/
│ │ └── Widgets/ │ │ └── Widgets/
│ │ ├── ResolvedTicketsWidget.php # Dashboard: resolved tickets table │ │ ├── ResolvedTicketsWidget.php # Dashboard: resolved tickets table
│ │ ├── AvgProcessingTimeWidget.php # Dashboard: stats overview │ │ ├── AvgProcessingTimeWidget.php # Dashboard: stats overview
│ │ └── HandlerPerformanceWidget.php # Dashboard: bar chart per handler │ │ └── HandlerPerformanceWidget.php # Dashboard: bar chart per handler
│ ├── Console/Commands/
│ │ ├── ImportCskh.php # app:import-cskh
│ │ └── ExportBackup.php # app:export-backup
│ ├── Enums/ │ ├── Enums/
│ │ ├── ContractCategory.php # V2: ownership/business
│ │ ├── ContractType.php │ │ ├── ContractType.php
│ │ ├── ContractStatus.php │ │ ├── ContractStatus.php
│ │ ├── HandoverStatus.php │ │ ├── HandoverStatus.php
│ │ └── ServiceType.php │ │ └── ServiceType.php
│ ├── Http/
│ │ ├── Controllers/Controller.php
│ │ └── Middleware/HandleUploadErrors.php
│ ├── Models/ │ ├── Models/
│ │ ├── User.php # HasRoles (Spatie), isAdmin(), isManager() │ │ ├── ActivityLog.php # NEW: Audit trail model
│ │ ├── Department.php # NEW: name, manager_id → User │ │ ├── Contract.php # V2: +category, +representative_*
│ │ ├── Product.php │ │ ├── Customer.php # V2: ownedProducts() qua contracts
│ │ ├── Customer.php │ │ ├── Department.php
│ │ ├── CustomerProduct.php │ │ ├── Feedback.php # V2: bỏ customer_product_id
│ │ ├── Feedback.php # added: current_department_id, is_escalated, transferLogs │ │ ├── FeedbackAttachment.php
│ │ ├── FeedbackChannel.php │ │ ├── FeedbackChannel.php
│ │ ├── FeedbackTag.php
│ │ ├── FeedbackInteraction.php │ │ ├── FeedbackInteraction.php
│ │ ├── FeedbackAttachment.php # added: uuid, disk, collection │ │ ├── FeedbackTag.php
│ │ ── TicketTransferLog.php # NEW: department-to-department transfer history │ │ ── Handover.php
│ │ ├── Product.php
│ │ ├── ProductService.php
│ │ ├── TicketTransferLog.php
│ │ └── User.php
│ ├── Policies/ │ ├── Policies/
│ │ ├── FeedbackPolicy.php # Spatie hasRole() checks │ │ ├── ActivityLogPolicy.php # NEW
│ │ ├── ProductPolicy.php │ │ ├── ContractPolicy.php
│ │ ├── CustomerPolicy.php │ │ ├── CustomerPolicy.php
│ │ ── FeedbackChannelPolicy.php │ │ ── FeedbackChannelPolicy.php
│ ├── Services/ │ ├── FeedbackPolicy.php
│ │ ├── FileService.php # Upload, validation, temp URLs, collections │ │ ├── ProductPolicy.php
│ │ ├── TransferService.php # Cross-dept transfer + notification │ │ ├── RolePolicy.php
│ │ └── ClosingService.php # Role-gated closing + evidence check │ │ └── UserPolicy.php
│ ├── Rules/
│ │ └── RequireProofOfResolution.php # Custom validation: proof_of_resolution required for close
│ ├── Notifications/ │ ├── Notifications/
│ │ ├── TicketTransferred.php # DB + Mail for department transfer │ │ ├── TicketTransferred.php
│ │ └── TicketClosed.php # DB + Mail for ticket closure │ │ └── TicketClosed.php
── Providers/Filament/ ── Providers/Filament/
── AdminPanelProvider.php ── AdminPanelProvider.php # Panel đầy đủ (/admin)
├── lang/ # i18n translation files └── SupportPanelProvider.php # Panel rút gọn (/support)
│ ├── en/ │ ├── Rules/
│ │ ── app.php # General UI labels, navigation, status, widgets │ │ ── RequireProofOfResolution.php
│ ├── feedback.php # Feedback domain: services, notifications, interactions └── Services/
── enums.php # Enum labels ── ActivityLogger.php # NEW: static log() cho audit trail
└── vi/ ├── ClosingService.php
│ ├── app.php │ ├── FileService.php
── feedback.php ── TransferService.php
│ └── enums.php ├── lang/ # i18n translation files
│ ├── en/{app.php, feedback.php, enums.php}
│ └── vi/{app.php, feedback.php, enums.php}
├── resources/views/filament/resources/feedback/ ├── resources/views/filament/resources/feedback/
│ ├── similar-cases.blade.php │ ├── similar-cases.blade.php
│ └── attachment-links.blade.php # Modal listing attachments with signed download URLs │ └── attachment-links.blade.php
├── webappUI/aftersales_crm_core/ # Design tokens & system
│ └── DESIGN.md
├── database/ ├── database/
│ ├── migrations/ │ ├── migrations/ # 25 migrations
│ └── seeders/AfterSalesSeeder.php # includes departments, logs, attachments │ └── seeders/{AfterSalesSeeder,PermissionSeeder}.php
├── tests/ ├── tests/Feature/
│ ├── Feature/ │ ├── ClosingPermissionTest.php
│ ├── ClosingPermissionTest.php # 4 tests: staff forbid, no-evidence, with-evidence, cross-dept └── TransferFlowTest.php
└── TransferFlowTest.php # 2 tests: successful + missing reason ├── luutru/ # Archive các file đã lỗi thời
│ └── Pest.php ├── UI_DESIGN_BRIEF.md # Thiết kế UI chi tiết
── storage/app/private/feedback-attachments/ # Private disk upload directory ── TASKS_ROADMAP.md
├── composer.json
├── PROGRESS.md
└── AGENTS.md
``` ```
## Database Schema ## Database Schema
### activity_logs (NEW)
| Column | Type | Notes |
|--------|------|-------|
| id | bigint PK | |
| user_id | fk -> users nullable | Who performed action |
| action | string | import, export, transfer, close, create, update, delete |
| description | text | Human-readable description |
| subject_type | string nullable | Related model class |
| subject_id | bigint nullable | Related model ID |
| metadata | json nullable | Extra data |
| created_at | timestamp | |
### contracts (V2: category + representative)
| Column | Type | Notes |
|--------|------|-------|
| id | bigint PK | |
| product_id | fk -> products | cascadeOnDelete |
| customer_id | fk -> customers | cascadeOnDelete |
| category | string | **(V2)** ownership \| business |
| type | string | **(V2)** deposit, purchase, transfer, rental, self_business, bcc |
| start_date, end_date | date nullable | |
| status | string | active, expired, liquidated |
| printed_at | date nullable | |
| signed_status | string nullable | |
| representative_name | string nullable | **(V2)** |
| representative_phone | string nullable | **(V2)** |
| representative_email | string nullable | **(V2)** |
| created_at, updated_at | timestamp | |
> **V2 Constraint:** Mỗi product chỉ có tối đa 1 contract active mỗi category. Validation ở cả Model level (`booted::saving`) và UI.
### departments (NEW) ### departments (NEW)
| Column | Type | Notes | | Column | Type | Notes |
|--------|------|-------| |--------|------|-------|
@@ -147,7 +219,7 @@ minicrm/
| manager_id | fk -> users nullable | Department head | | manager_id | fk -> users nullable | Department head |
| created_at, updated_at | timestamp | | | created_at, updated_at | timestamp | |
### ticket_transfer_logs (NEW) ### ticket_transfer_logs
| Column | Type | Notes | | Column | Type | Notes |
|--------|------|-------| |--------|------|-------|
| id | bigint PK | | | id | bigint PK | |
@@ -163,11 +235,11 @@ minicrm/
|--------|------|-------| |--------|------|-------|
| id | bigint PK | | | id | bigint PK | |
| customer_id | fk -> customers | cascadeOnDelete | | customer_id | fk -> customers | cascadeOnDelete |
| customer_product_id | fk -> customer_product nullable | null = general feedback | | contract_id | fk -> contracts nullable | **(V2)** Snapshot contract (thay thế customer_product_id) |
| feedback_channel_id | fk -> feedback_channels | | | feedback_channel_id | fk -> feedback_channels | |
| assigned_to | fk -> users nullable | Current handler | | assigned_to | fk -> users nullable | Current handler |
| current_department_id | fk -> departments nullable | **(NEW)** Current department | | current_department_id | fk -> departments nullable | Current department |
| is_escalated | boolean default false | **(NEW)** | | is_escalated | boolean default false | |
| title | string | | | title | string | |
| content | text | | | content | text | |
| status | string | pending, processing, resolved, closed | | status | string | pending, processing, resolved, closed |
@@ -177,20 +249,20 @@ minicrm/
| Column | Type | Notes | | Column | Type | Notes |
|--------|------|-------| |--------|------|-------|
| id | bigint PK | | | id | bigint PK | |
| uuid | string nullable unique | **(NEW)** | | uuid | string nullable unique | |
| feedback_id | fk -> feedback | | | feedback_id | fk -> feedback | |
| feedback_interaction_id | fk -> feedback_interactions nullable | | | feedback_interaction_id | fk -> feedback_interactions nullable | |
| user_id | fk -> users | | | user_id | fk -> users | |
| name | string | | | name | string | |
| path | string | | | path | string | |
| disk | string default 'local' | **(NEW)** | | disk | string default 'local' | |
| collection | string default 'general' | **(NEW)** proof_of_resolution, customer_evidence, general | | collection | string default 'general' | proof_of_resolution, customer_evidence, general |
| mime_type | string nullable | | | mime_type | string nullable | |
| size | bigint nullable | | | size | bigint nullable | |
| created_at, updated_at | timestamp | | | created_at, updated_at | timestamp | |
### Other tables ### Other tables
feedback_interactions, feedback_tags, feedback_feedback_tag, products, customers, customer_product, feedback_channels, users (Spatie permission tables: roles, permissions, model_has_roles, etc.) feedback_interactions, feedback_tags, feedback_feedback_tag, products, customers, feedback_channels, users, contracts, handovers, product_services, roles, permissions, model_has_roles (Spatie), notifications, sessions, cache
## Workflow ## Workflow
@@ -205,14 +277,24 @@ feedback_interactions, feedback_tags, feedback_feedback_tag, products, customers
## Key Features ## Key Features
### Transfer Department (NEW - SOP compliant) ### Dual Panel System (NEW)
- Action on EditFeedback page: TransferDepartment - **Admin Panel** (`/admin`): Đầy đủ modules, User/Role management
- **Support Panel** (`/support`): Rút gọn, tập trung Feedback. Dùng cho đội support không cần quản lý hệ thống
### ActivityLog — Audit Trail (NEW)
- Tự động ghi log các hành động: import, export, transfer, close, create, update, delete
- `ActivityLogger::log(action, description, subject, metadata, userId)`
- Xem tại `/admin/activity-logs` hoặc `/support/activity-logs`
- Admin-only access (ActivityLogPolicy)
### Transfer Department (SOP compliant)
- Action trên EditFeedback: TransferDepartment
- Modal: select target department + reason (required) + optional attachments - Modal: select target department + reason (required) + optional attachments
- Calls TransferService: creates TicketTransferLog, updates current_department_id, resets handler to dept manager - Calls TransferService: creates TicketTransferLog, updates current_department_id, resets handler to dept manager
- Sends TicketTransferred notification to target department manager - Sends TicketTransferred notification to target department manager
### Close Ticket (NEW - SOP compliant) ### Close Ticket (SOP compliant)
- Action on EditFeedback page: CloseTicket - Action trên EditFeedback: CloseTicket
- Visible only to admin/manager, only when status != 'closed' - Visible only to admin/manager, only when status != 'closed'
- Requires confirmation - Requires confirmation
- Staff (403) if tries to close - Staff (403) if tries to close
@@ -224,14 +306,14 @@ feedback_interactions, feedback_tags, feedback_feedback_tag, products, customers
- Manager/Admin: all options including "closed" - Manager/Admin: all options including "closed"
- When "closed" selected: calls ClosingService which validates evidence - When "closed" selected: calls ClosingService which validates evidence
### File Management (Updated - SOP compliant) ### File Management (SOP compliant)
- Files stored on private `local` disk (storage/app/private/feedback-attachments/) - Files stored on `public` disk (`storage/app/public/feedback-attachments/`)
- Collection system: `proof_of_resolution`, `customer_evidence`, `general` - Collection system: `proof_of_resolution`, `customer_evidence`, `general`
- FileService validates: jpg, png, pdf, mp4, mov, max 20MB - FileService validates: jpg, png, pdf, mp4, mov, max 20MB
- Temporary signed URLs for private file access - Temporary signed URLs for private file access
- FileService::hasCollection() checks existence of required evidence - FileService::hasCollection() checks existence of required evidence
### Dashboard Widgets (NEW) ### Dashboard Widgets
- ResolvedTicketsWidget: table of resolved tickets awaiting closure (manager: filtered to own department) - ResolvedTicketsWidget: table of resolved tickets awaiting closure (manager: filtered to own department)
- AvgProcessingTimeWidget: 4 stats (resolved count, avg time, pending count, escalated count) - AvgProcessingTimeWidget: 4 stats (resolved count, avg time, pending count, escalated count)
- HandlerPerformanceWidget: bar chart of avg processing time per handler - HandlerPerformanceWidget: bar chart of avg processing time per handler
@@ -303,19 +385,35 @@ public function getHeading(): string | Htmlable | null
## Navigation Structure ## Navigation Structure
### Admin Panel (`/admin`)
``` ```
Dashboard Dashboard (AccountWidget + 3 custom widgets)
├── Customer Care / Chăm sóc khách hàng (group) ├── Customer Care / Chăm sóc khách hàng (group)
│ └── Feedbacks / Phản ánh (chat-bubble-left-right, sort=1) │ └── Feedbacks / Phản ánh (chat-bubble-left-right, sort=1)
└── Management / Quản lý (group) └── Management / Quản lý (group)
├── Products / Sản phẩm (building-storefront, sort=1) ├── Products / Sản phẩm (building-storefront, sort=1)
├── Customers / Khách hàng (user-group, sort=2) ├── Customers / Khách hàng (user-group, sort=2)
├── Channels / Kênh phản ánh (inbox-stack, sort=3) ├── Channels / Kênh phản ánh (inbox-stack, sort=3)
├── Contracts / Hợp đồng (document-text, sort=4)
├── Tags / Thẻ (tag, sort=default) ├── Tags / Thẻ (tag, sort=default)
├── Activity Logs (clock, sort=7) — admin only
├── Users / Người dùng (users, sort=5) — admin only ├── Users / Người dùng (users, sort=5) — admin only
└── Roles / Vai trò (shield-check, sort=6) — admin only └── Roles / Vai trò (shield-check, sort=6) — admin only
``` ```
### Support Panel (`/support`)
```
Dashboard (3 custom widgets)
├── Customer Care / Chăm sóc khách hàng (group)
│ └── Feedbacks
└── Management / Quản lý (group)
├── Products
├── Customers
├── Channels
├── Tags
└── Activity Logs
```
Dashboard widgets: ResolvedTicketsWidget, AvgProcessingTimeWidget, HandlerPerformanceWidget (admin/manager only) Dashboard widgets: ResolvedTicketsWidget, AvgProcessingTimeWidget, HandlerPerformanceWidget (admin/manager only)
## RBAC (Role-Based Access Control) - Spatie ## RBAC (Role-Based Access Control) - Spatie
@@ -400,6 +498,9 @@ use Filament\Schemas\Schema;
```php ```php
use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\App;
$service = App::make(FileService::class); $service = App::make(FileService::class);
// ActivityLogger (static)
\App\Services\ActivityLogger::log('transfer', '...', $feedback, ['dept' => 'CSKH']);
``` ```
### Spatie role check ### Spatie role check
@@ -432,6 +533,7 @@ $user->assignRole('manager');
19. **FileUpload in Actions**: When handling file uploads in Action callbacks (e.g., transfer attachments), file paths are strings (not UploadedFile). Create records directly instead of using FileService::upload(). 19. **FileUpload in Actions**: When handling file uploads in Action callbacks (e.g., transfer attachments), file paths are strings (not UploadedFile). Create records directly instead of using FileService::upload().
20. **Tailwind CSS in Filament**: Custom blade views render inside Filament layout which does NOT include full Tailwind CSS build. Must add needed utilities to `public/css/filament-custom.css` with `!important`. 20. **Tailwind CSS in Filament**: Custom blade views render inside Filament layout which does NOT include full Tailwind CSS build. Must add needed utilities to `public/css/filament-custom.css` with `!important`.
21. **SVG icon sizing**: Use inline `width`/`height` attributes on SVG icons (e.g., `<svg width="14" height="14">`) instead of Tailwind classes (`w-3.5 h-3.5`) — prevents Filament CSS from overriding sizes. 21. **SVG icon sizing**: Use inline `width`/`height` attributes on SVG icons (e.g., `<svg width="14" height="14">`) instead of Tailwind classes (`w-3.5 h-3.5`) — prevents Filament CSS from overriding sizes.
22. **Dual Panel**: Support panel at `/support` is separate from Admin panel at `/admin`. Both share the same models/services/policies/database.
## File Upload Architecture ## File Upload Architecture
@@ -501,3 +603,4 @@ protected function afterSave(): void
// For SVG icons, use inline attributes: // For SVG icons, use inline attributes:
<svg width="14" height="14" class="text-blue-600">...</svg> <svg width="14" height="14" class="text-blue-600">...</svg>
// NOT: <svg class="w-3.5 h-3.5 text-blue-600">...</svg> // NOT: <svg class="w-3.5 h-3.5 text-blue-600">...</svg>
```

View File

@@ -10,8 +10,8 @@
| Mục | Giá trị | | Mục | Giá trị |
|------|--------| |------|--------|
| Framework | Laravel 13.6.0 | | Framework | Laravel 13.6.0 |
| Admin Panel | Filament 5.6.1 | | Panels | Filament 5.6.1 — 2 panels: `/admin` (đầy đủ) + `/support` (rút gọn) |
| Auth/RBAC | Spatie laravel-permission (3 roles: admin, manager, staff) | | Auth/RBAC | Spatie laravel-permission (3 roles: admin, manager, staff, 29 permissions) |
| Database | SQLite (`database/database.sqlite`) | | Database | SQLite (`database/database.sqlite`) |
| Testing | Pest PHP | | Testing | Pest PHP |
| PHP | 8.3 | | PHP | 8.3 |
@@ -32,6 +32,9 @@
app/ app/
├── Filament/ ├── Filament/
│ ├── Resources/ │ ├── Resources/
│ │ ├── ActivityLogs/ # NEW: Audit trail (read-only)
│ │ │ ├── ActivityLogResource.php
│ │ │ └── Pages/ListActivityLogs.php
│ │ ├── Customers/ │ │ ├── Customers/
│ │ │ ├── CustomerResource.php │ │ │ ├── CustomerResource.php
│ │ │ ├── Pages/ │ │ │ ├── Pages/
@@ -56,7 +59,7 @@ app/
│ │ │ │ └── FeedbackForm.php │ │ │ │ └── FeedbackForm.php
│ │ │ └── Tables/ │ │ │ └── Tables/
│ │ │ └── FeedbackTable.php │ │ │ └── FeedbackTable.php
│ │ ├── Contracts/ # NEW │ │ ├── Contracts/
│ │ │ ├── ContractResource.php │ │ │ ├── ContractResource.php
│ │ │ ├── Pages/ │ │ │ ├── Pages/
│ │ │ │ ├── CreateContract.php │ │ │ │ ├── CreateContract.php
@@ -86,32 +89,32 @@ app/
│ │ │ │ └── FeedbackTagForm.php │ │ │ │ └── FeedbackTagForm.php
│ │ │ └── Tables/ │ │ │ └── Tables/
│ │ │ └── FeedbackTagsTable.php │ │ │ └── FeedbackTagsTable.php
│ │ ── Products/ │ │ ── Products/
│ │ ├── ProductResource.php │ │ ├── ProductResource.php
│ │ ├── Pages/ │ │ ├── Pages/
│ │ │ ├── CreateProduct.php │ │ │ ├── CreateProduct.php
│ │ │ ├── EditProduct.php │ │ │ ├── EditProduct.php
│ │ │ └── ListProducts.php │ │ │ └── ListProducts.php
│ │ ├── RelationManagers/ │ │ ├── RelationManagers/
│ │ │ ├── ContractsRelationManager.php # NEW │ │ │ ├── ContractsRelationManager.php
│ │ │ ├── HandoversRelationManager.php # NEW │ │ │ ├── HandoversRelationManager.php
│ │ │ └── ProductServicesRelationManager.php # NEW │ │ │ └── ProductServicesRelationManager.php
│ │ ├── Schemas/ │ │ ├── Schemas/
│ │ │ └── ProductForm.php │ │ │ └── ProductForm.php
│ │ └── Tables/ │ │ └── Tables/
│ │ └── ProductsTable.php │ │ └── ProductsTable.php
│ │ ── Users/ # NEW │ │ ── Users/ # Admin-only user management
│ │ ├── UserResource.php # Admin-only user management │ │ ├── UserResource.php
│ │ ├── Pages/ │ │ ├── Pages/
│ │ │ ├── CreateUser.php │ │ │ ├── CreateUser.php
│ │ │ ├── EditUser.php │ │ │ ├── EditUser.php
│ │ │ └── ListUsers.php # Tabs: All/Admin/Manager/Staff │ │ │ └── ListUsers.php # Tabs: All/Admin/Manager/Staff
│ │ ├── Schemas/ │ │ ├── Schemas/
│ │ │ └── UserForm.php # name, email, password, role (dynamic) │ │ │ └── UserForm.php # name, email, password, role (dynamic)
│ │ └── Tables/ │ │ └── Tables/
│ │ └── UsersTable.php # name, email, role badge │ │ └── UsersTable.php # name, email, role badge
│ │ └── Roles/ # NEW │ │ └── Roles/ # Admin-only role management
│ │ ├── RoleResource.php # Admin-only role management │ │ ├── RoleResource.php
│ │ ├── Pages/ │ │ ├── Pages/
│ │ │ ├── CreateRole.php │ │ │ ├── CreateRole.php
│ │ │ ├── EditRole.php │ │ │ ├── EditRole.php
@@ -124,49 +127,57 @@ app/
│ ├── AvgProcessingTimeWidget.php # 4 stats: resolved count, avg time, pending, escalated │ ├── AvgProcessingTimeWidget.php # 4 stats: resolved count, avg time, pending, escalated
│ ├── HandlerPerformanceWidget.php # bar chart: avg time per handler │ ├── HandlerPerformanceWidget.php # bar chart: avg time per handler
│ └── ResolvedTicketsWidget.php # table: resolved tickets awaiting closure │ └── ResolvedTicketsWidget.php # table: resolved tickets awaiting closure
├── Console/ # NEW ├── Console/
│ └── Commands/ │ └── Commands/
│ ├── ImportCskh.php # app:import-cskh command │ ├── ImportCskh.php # app:import-cskh command
│ └── ExportBackup.php # app:export-backup command (JSON backup) │ └── ExportBackup.php # app:export-backup command (JSON backup)
├── Enums/ # NEW ├── Enums/
│ ├── ContractType.php # SALE/LEASE/BCC │ ├── ContractCategory.php # V2: ownership/business
│ ├── ContractType.php # V2: deposit/purchase/transfer/rental/self_business/bcc
│ ├── ContractStatus.php # ACTIVE/EXPIRED/LIQUIDATED │ ├── ContractStatus.php # ACTIVE/EXPIRED/LIQUIDATED
│ ├── HandoverStatus.php # NOT_READY/READY/SCHEDULED/HANDED_OVER │ ├── HandoverStatus.php # NOT_READY/READY/SCHEDULED/HANDED_OVER
│ └── ServiceType.php # MANAGEMENT_FEE/GRATITUDE/SELF_BUSINESS │ └── ServiceType.php # MANAGEMENT_FEE/GRATITUDE/SELF_BUSINESS
├── Http/ ├── Http/
── Controllers/ ── Controllers/
└── Controller.php └── Controller.php
│ └── Middleware/
│ └── HandleUploadErrors.php
├── Models/ ├── Models/
│ ├── Contract.php # NEW │ ├── ActivityLog.php # NEW: Audit trail (user_id, action, description, metadata)
│ ├── Customer.php │ ├── Contract.php # V2: +category, +representative_*
│ ├── CustomerProduct.php # pivot model (customer_product table) │ ├── Customer.php # V2: ownedProducts() qua contracts
│ ├── Department.php │ ├── Department.php
│ ├── Feedback.php │ ├── Feedback.php
│ ├── FeedbackAttachment.php │ ├── FeedbackAttachment.php
│ ├── FeedbackChannel.php │ ├── FeedbackChannel.php
│ ├── FeedbackInteraction.php │ ├── FeedbackInteraction.php
│ ├── FeedbackTag.php │ ├── FeedbackTag.php
│ ├── Handover.php # NEW │ ├── Handover.php
│ ├── Product.php │ ├── Product.php
│ ├── ProductService.php # NEW │ ├── ProductService.php
│ ├── TicketTransferLog.php │ ├── TicketTransferLog.php
│ └── User.php │ └── User.php
├── Notifications/ ├── Notifications/
│ ├── TicketClosed.php │ ├── TicketClosed.php
│ └── TicketTransferred.php │ └── TicketTransferred.php
├── Policies/ ├── Policies/
│ ├── ContractPolicy.php # NEW │ ├── ActivityLogPolicy.php # NEW: Admin-only
│ ├── ContractPolicy.php
│ ├── CustomerPolicy.php │ ├── CustomerPolicy.php
│ ├── FeedbackChannelPolicy.php │ ├── FeedbackChannelPolicy.php
│ ├── FeedbackPolicy.php │ ├── FeedbackPolicy.php
── ProductPolicy.php ── ProductPolicy.php
│ ├── RolePolicy.php
│ └── UserPolicy.php
├── Providers/ ├── Providers/
│ ├── AppServiceProvider.php │ ├── AppServiceProvider.php
│ └── Filament/ │ └── Filament/
── AdminPanelProvider.php ── AdminPanelProvider.php # Panel đầy đủ (/admin)
│ └── SupportPanelProvider.php # Panel rút gọn (/support)
├── Rules/ ├── Rules/
│ └── RequireProofOfResolution.php │ └── RequireProofOfResolution.php
└── Services/ └── Services/
├── ActivityLogger.php # NEW: static log() cho audit trail
├── ClosingService.php ├── ClosingService.php
├── FileService.php ├── FileService.php
└── TransferService.php └── TransferService.php
@@ -174,8 +185,37 @@ app/
--- ---
## Dual Panel Architecture
### Admin Panel (`/admin`) — `AdminPanelProvider.php`
Đầy đủ tất cả modules:
- Resources: Feedback, Customer, Product, Contract, FeedbackChannel, FeedbackTag, User, Role, ActivityLog
- Widgets: ResolvedTicketsWidget, AvgProcessingTimeWidget, HandlerPerformanceWidget
- User/Role management (admin-only)
### Support Panel (`/support`) — `SupportPanelProvider.php`
Rút gọn, tập trung feedback:
- Resources: Feedback, Customer, Product, FeedbackChannel, FeedbackTag, ActivityLog
- Widgets: ResolvedTicketsWidget, AvgProcessingTimeWidget, HandlerPerformanceWidget
---
## Models — Chi tiết ## Models — Chi tiết
### ActivityLog (`activity_logs`) — NEW
| Cột | Kiểu |
|-----|------|
| id | bigint PK |
| user_id | FK->users nullable |
| action | string (import/export/transfer/close/create/update/delete) |
| description | text |
| subject_type | string nullable |
| subject_id | bigint nullable |
| metadata | json nullable |
| created_at | timestamp |
Relationships: `user()` BelongsTo
### Product (`products`) ### Product (`products`)
| Cột | Kiểu | | Cột | Kiểu |
|-----|------| |-----|------|
@@ -184,9 +224,9 @@ app/
| description | text nullable | | description | text nullable |
| status | string (active/inactive/sold_out) | | status | string (active/inactive/sold_out) |
Relationships: `customers()` BelongsToMany (pivot: customer_product, withPivot: purchase_date), `contracts()` HasMany, `handovers()` HasMany, `productServices()` HasMany Relationships: `contracts()` HasMany, `handovers()` HasMany, `productServices()` HasMany
### ProductService (`product_services`) — NEW ### ProductService (`product_services`)
| Cột | Kiểu | | Cột | Kiểu |
|-----|------| |-----|------|
| id | bigint PK | | id | bigint PK |
@@ -198,7 +238,7 @@ Relationships: `customers()` BelongsToMany (pivot: customer_product, withPivot:
Relationships: `product()` BelongsTo Relationships: `product()` BelongsTo
### Handover (`handovers`) — NEW ### Handover (`handovers`)
| Cột | Kiểu | | Cột | Kiểu |
|-----|------| |-----|------|
| id | bigint PK | | id | bigint PK |
@@ -210,22 +250,28 @@ Relationships: `product()` BelongsTo
Relationships: `product()` BelongsTo, `customer()` BelongsTo Relationships: `product()` BelongsTo, `customer()` BelongsTo
### Contract (`contracts`) — NEW ### Contract (`contracts`) — V2
| Cột | Kiểu | | Cột | Kiểu |
|-----|------| |-----|------|
| id | bigint PK | | id | bigint PK |
| product_id | FK->products cascadeOnDelete | | product_id | FK->products cascadeOnDelete |
| customer_id | FK->customers cascadeOnDelete | | customer_id | FK->customers cascadeOnDelete |
| type | string (sale/lease/bcc → ContractType enum) | | category | string (ownership/business → ContractCategory enum) |
| type | string (deposit/purchase/transfer/rental/self_business/bcc → ContractType enum) |
| start_date | date nullable | | start_date | date nullable |
| end_date | date nullable | | end_date | date nullable |
| status | string (active/expired/liquidated → ContractStatus enum) | | status | string (active/expired/liquidated → ContractStatus enum) |
| printed_at | date nullable | | printed_at | date nullable |
| signed_status | string nullable | | signed_status | string nullable |
| representative_name | string nullable |
| representative_phone | string nullable |
| representative_email | string nullable |
Relationships: `product()` BelongsTo, `customer()` BelongsTo, `feedbacks()` HasMany Relationships: `product()` BelongsTo, `customer()` BelongsTo, `feedbacks()` HasMany
### Customer (`customers`) > **Constraint:** Mỗi product tối đa 1 active contract mỗi category. Validation ở Model `booted::saving`.
### Customer (`customers`) — V2
| Cột | Kiểu | | Cột | Kiểu |
|-----|------| |-----|------|
| id | bigint PK | | id | bigint PK |
@@ -235,18 +281,7 @@ Relationships: `product()` BelongsTo, `customer()` BelongsTo, `feedbacks()` HasM
| address | text nullable | | address | text nullable |
| status | string (active) | | status | string (active) |
Relationships: `products()` BelongsToMany, `feedbacks()` HasMany Relationships: `ownedProducts()` BelongsToMany qua contracts (ownership + active), `feedbacks()` HasMany
### CustomerProduct (`customer_product` — pivot model)
| Cột | Kiểu |
|-----|------|
| id | bigint PK |
| customer_id | FK->customers cascadeOnDelete |
| product_id | FK->products cascadeOnDelete |
| purchase_date | date nullable |
UNIQUE(customer_id, product_id)
Relationships: `customer()` BelongsTo, `product()` BelongsTo, `feedbacks()` HasMany
### Department (`departments`) ### Department (`departments`)
| Cột | Kiểu | | Cột | Kiểu |
@@ -266,14 +301,13 @@ Relationships: `manager()` BelongsTo User, `feedbacks()` HasMany, `transferLogsF
| password | string | | password | string |
| role | string (admin/manager/staff) | | role | string (admin/manager/staff) |
Uses Spatie `HasRoles`. Relationships: `assignedFeedbacks()` HasMany Feedback. Uses Spatie `HasRoles`. Relationships: `assignedFeedbacks()` HasMany Feedback, `activityLogs()` HasMany.
### Feedback (`feedback`) ### Feedback (`feedback`) — V2
| Cột | Kiểu | | Cột | Kiểu |
|-----|------| |-----|------|
| id | bigint PK | | id | bigint PK |
| customer_id | FK->customers cascadeOnDelete | | customer_id | FK->customers cascadeOnDelete |
| customer_product_id | FK->customer_product nullable nullOnDelete |
| contract_id | FK->contracts nullable nullOnDelete | | contract_id | FK->contracts nullable nullOnDelete |
| feedback_channel_id | FK->feedback_channels | | feedback_channel_id | FK->feedback_channels |
| assigned_to | FK->users nullable nullOnDelete | | assigned_to | FK->users nullable nullOnDelete |
@@ -283,9 +317,9 @@ Uses Spatie `HasRoles`. Relationships: `assignedFeedbacks()` HasMany Feedback.
| content | text | | content | text |
| status | string (pending/processing/resolved/closed) | | status | string (pending/processing/resolved/closed) |
Fillable: `['customer_id', 'customer_product_id', 'contract_id', 'feedback_channel_id', 'assigned_to', 'title', 'content', 'status', 'current_department_id', 'is_escalated']` Fillable: `['customer_id', 'contract_id', 'feedback_channel_id', 'assigned_to', 'title', 'content', 'status', 'current_department_id', 'is_escalated']`
Relationships (10): `customer()`, `customerProduct()`, `contract()`, `feedbackChannel()`, `assignedTo()`, `currentDepartment()`, `transferLogs()`, `interactions()` ordered latest, `attachments()`, `tags()` BelongsToMany Relationships: `customer()`, `contract()`, `feedbackChannel()`, `assignedTo()`, `currentDepartment()`, `transferLogs()`, `interactions()` ordered latest, `attachments()`, `tags()` BelongsToMany
### FeedbackInteraction (`feedback_interactions`) ### FeedbackInteraction (`feedback_interactions`)
| Cột | Kiểu | | Cột | Kiểu |
@@ -323,6 +357,7 @@ Relationships: `feedback()`, `interaction()`, `user()`. Scopes: `byCollection()`
| name | string | | name | string |
| slug | string unique | | slug | string unique |
| icon | string nullable | | icon | string nullable |
| color | string nullable |
| is_active | boolean default true | | is_active | boolean default true |
Relationships: `feedbacks()` HasMany Relationships: `feedbacks()` HasMany
@@ -353,27 +388,31 @@ Relationships: `feedback()`, `fromDepartment()`, `toDepartment()`, `sender()`
## Services — Tóm tắt ## Services — Tóm tắt
### ActivityLogger (`app/Services/ActivityLogger.php`) — NEW
- `ActivityLogger::log(action, description, subject?, metadata?, userId?)`: Static method. Tạo ActivityLog record cho audit trail. Dùng trong Import/Export/Transfer/Close/Create/Update/Delete.
### TransferService (`app/Services/TransferService.php`) ### TransferService (`app/Services/TransferService.php`)
- `transfer(Feedback, Department, reason, User, ?int $newHandlerId)`: Tạo TicketTransferLog, cập nhật current_department_id + assigned_to, gửi TicketTransferred notification cho manager đích. - `transfer(Feedback, Department, reason, User, ?int $newHandlerId)`: Tạo TicketTransferLog, cập nhật current_department_id + assigned_to, gửi TicketTransferred notification cho manager đích.
- Validate reason không được rỗng (ValidationException). - Validate reason không được rỗng (ValidationException).
### FileService (`app/Services/FileService.php`)
- `upload()`: Validate (jpg/png/pdf/mp4/mov, ≤20MB), store vào public disk, tạo FeedbackAttachment record.
- `getTemporaryUrl()` / `getPreviewUrl()`: Signed URL cho private file.
- `getByCollection()` / `hasCollection()`: Query collection-based attachments.
### ClosingService (`app/Services/ClosingService.php`) ### ClosingService (`app/Services/ClosingService.php`)
- `close(Feedback, User)`: 4 guard: status ≠ closed, staff → 403, manager chỉ đóng ticket phòng mình, phải có proof_of_resolution attachment (FileService::hasCollection). Gửi TicketClosed notification. - `close(Feedback, User)`: 4 guard: status ≠ closed, staff → 403, manager chỉ đóng ticket phòng mình, phải có proof_of_resolution attachment (FileService::hasCollection). Gửi TicketClosed notification.
- `resolve(Feedback, User)`: Đánh dấu resolved (không role gate). - `resolve(Feedback, User)`: Đánh dấu resolved (không role gate).
### FileService (`app/Services/FileService.php`)
- `upload()`: Validate (jpg/png/pdf/mp4/mov, ≤20MB), store vào private local disk (`feedback-attachments/`), tạo FeedbackAttachment record.
- `getTemporaryUrl()` / `getPreviewUrl()`: Signed URL cho private file.
- `getByCollection()` / `hasCollection()`: Query collection-based attachments.
--- ---
## Policies — Tóm tắt ## Policies — Tóm tắt
> **Note:** Policies now use Spatie `hasPermissionTo()` instead of `hasRole()` for granular permission control. > **Note:** Policies use Spatie `hasPermissionTo()` instead of `hasRole()` for granular permission control.
| Policy | viewAny/view | create | update | delete | restore/forceDelete | | Policy | viewAny/view | create | update | delete | restore/forceDelete |
|--------|-------------|--------|--------|--------|---------------------| |--------|-------------|--------|--------|--------|---------------------|
| ActivityLogPolicy | admin only | — | — | — | — |
| ContractPolicy | view-contract | create-contract | update-contract | delete-contract | admin only | | ContractPolicy | view-contract | create-contract | update-contract | delete-contract | admin only |
| FeedbackPolicy | view-feedback | create-feedback | update-feedback | delete-feedback | admin only | | FeedbackPolicy | view-feedback | create-feedback | update-feedback | delete-feedback | admin only |
| ProductPolicy | view-product | create-product | update-product | delete-product | admin only | | ProductPolicy | view-product | create-product | update-product | delete-product | admin only |
@@ -386,6 +425,7 @@ Relationships: `feedback()`, `fromDepartment()`, `toDepartment()`, `sender()`
## Filament Navigation Structure ## Filament Navigation Structure
### Admin Panel (`/admin`)
``` ```
Dashboard (AccountWidget + 3 custom widgets) Dashboard (AccountWidget + 3 custom widgets)
├── Customer Care (group) ├── Customer Care (group)
@@ -394,8 +434,24 @@ Dashboard (AccountWidget + 3 custom widgets)
├── Products (heroicon-o-building-storefront, sort=1) ├── Products (heroicon-o-building-storefront, sort=1)
├── Customers (heroicon-o-user-group, sort=2) ├── Customers (heroicon-o-user-group, sort=2)
├── Channels (heroicon-o-inbox-stack, sort=3) ├── Channels (heroicon-o-inbox-stack, sort=3)
├── Contracts (heroicon-o-document-text, sort=4) # NEW ├── Contracts (heroicon-o-document-text, sort=4)
── Tags (heroicon-o-tag, default sort) ── Tags (heroicon-o-tag, default sort)
├── Activity Logs (heroicon-o-clock, sort=7) — admin only
├── Users (heroicon-o-users, sort=5) — admin only
└── Roles (heroicon-o-shield-check, sort=6) — admin only
```
### Support Panel (`/support`)
```
Dashboard (3 custom widgets)
├── Customer Care (group)
│ └── Feedbacks
└── Management (group)
├── Products
├── Customers
├── Channels
├── Tags
└── Activity Logs
``` ```
--- ---
@@ -407,7 +463,7 @@ Dashboard (AccountWidget + 3 custom widgets)
--- ---
## Database Migration files (23 files) ## Database Migration files (25 files)
| # | File | Tables | | # | File | Tables |
|---|------|--------| |---|------|--------|
@@ -430,17 +486,20 @@ Dashboard (AccountWidget + 3 custom widgets)
| 17 | `2026_04_27_083000_add_collection_to_feedback_attachments_table` | (modify feedback_attachments) add uuid, disk, collection | | 17 | `2026_04_27_083000_add_collection_to_feedback_attachments_table` | (modify feedback_attachments) add uuid, disk, collection |
| 18 | `2026_04_27_140000_fix_attachment_disk_default` | (modify feedback_attachments) fix disk default private→local | | 18 | `2026_04_27_140000_fix_attachment_disk_default` | (modify feedback_attachments) fix disk default private→local |
| 19 | `2026_04_27_150000_create_notifications_table` | notifications | | 19 | `2026_04_27_150000_create_notifications_table` | notifications |
| 20 | `2026_05_01_000000_create_contracts_table` | **(NEW)** contracts | | 20 | `2026_05_01_000000_create_contracts_table` | contracts |
| 21 | `2026_05_01_000001_add_contract_id_to_feedback_table` | **(NEW)** add contract_id FK to feedback | | 21 | `2026_05_01_000001_add_contract_id_to_feedback_table` | (modify feedback) add contract_id FK |
| 22 | `2026_05_01_000002_create_handovers_table` | **(NEW)** handovers | | 22 | `2026_05_01_000002_create_handovers_table` | handovers |
| 23 | `2026_05_01_000003_create_product_services_table` | **(NEW)** product_services | | 23 | `2026_05_01_000003_create_product_services_table` | product_services |
| 24 | `2026_05_01_000004_add_color_to_feedback_channels_table` | (modify feedback_channels) add color |
| 25 | `2026_05_09_104519_create_activity_logs_table` | activity_logs |
| 26 | `2026_05_12_075014_v2_restructure_contracts` | **(V2)** contracts +category, +representative; drop customer_product; drop feedback.customer_product_id |
--- ---
## Seeder (AfterSalesSeeder + PermissionSeeder) — Data mẫu ## Seeder (AfterSalesSeeder + PermissionSeeder) — Data mẫu
- 3 users (admin, manager, staff) + Spatie roles - 3 users (admin, manager, staff) + Spatie roles
- **29 granular permissions** (PermissionSeeder) — NEW - **29 granular permissions** (PermissionSeeder)
- Feedback: view/create/update/delete, add-interaction, close-ticket, transfer-department - Feedback: view/create/update/delete, add-interaction, close-ticket, transfer-department
- Products/Customers/Contracts/Channels/Tags: view/create/update/delete each - Products/Customers/Contracts/Channels/Tags: view/create/update/delete each
- Dashboard: view-dashboard-widgets, export-data - Dashboard: view-dashboard-widgets, export-data
@@ -459,12 +518,9 @@ Dashboard (AccountWidget + 3 custom widgets)
- 1 ticket_transfer_log - 1 ticket_transfer_log
- 3 feedback_attachments (2 proof_of_resolution, 1 customer_evidence) - 3 feedback_attachments (2 proof_of_resolution, 1 customer_evidence)
---|---
| 22 | `2026_05_01_000003_create_product_services_table` | **(NEW)** product_services |
--- ---
## Data Import (`app:import-cskh`) — NEW ## Data Import (`app:import-cskh`)
Command: `php artisan app:import-cskh {file_path}` Command: `php artisan app:import-cskh {file_path}`
- Sử dụng `spatie/simple-excel` với Lazy Collection (chống OOM) - Sử dụng `spatie/simple-excel` với Lazy Collection (chống OOM)
@@ -493,12 +549,13 @@ Tổng: 8 tests, 21 assertions.
1. **Form components:** `Filament\Forms\Components\*` (Select, TextInput, Textarea, Toggle, FileUpload, RichEditor) 1. **Form components:** `Filament\Forms\Components\*` (Select, TextInput, Textarea, Toggle, FileUpload, RichEditor)
2. **Schema/layout:** `Filament\Schemas\Components\*` (Section, Schema) 2. **Schema/layout:** `Filament\Schemas\Components\*` (Section, Schema)
3. **Service access:** `App::make(FileService::class)` hoặc inject constructor 3. **Service access:** `App::make(FileService::class)` hoặc inject constructor. `ActivityLogger::log()` là static.
4. **Role check:** `$user->hasRole('admin')` / `$user->hasRole(['admin', 'manager'])` 4. **Role check:** `$user->hasRole('admin')` / `$user->hasRole(['admin', 'manager'])`
5. **Dynamic form field:** dùng `$get` function injection, KHÔNG dùng `$component->getLivewire()->data` 5. **Dynamic form field:** dùng `$get` function injection, KHÔNG dùng `$component->getLivewire()->data`
6. **FileUpload với dehydrated(false):** File được Filament lưu trước, chỉ cần tạo FeedbackAttachment record trong after()/afterSave() — KHÔNG re-upload qua FileService 6. **FileUpload với dehydrated(false):** File được Filament lưu trước, chỉ cần tạo FeedbackAttachment record trong after()/afterSave() — KHÔNG re-upload qua FileService
7. **Private disk:** files lưu ở `storage/app/private/feedback-attachments/`, truy cập qua signed URL từ FileService 7. **Private disk:** files lưu ở `storage/app/private/feedback-attachments/`, truy cập qua signed URL từ FileService. Luôn dùng `disk('public')` cho FileUpload.
8. **Navigation group icons:** Filament 5 báo lỗi nếu cả navigation group VÀ child items đều có icons 8. **Navigation group icons:** Filament 5 báo lỗi nếu cả navigation group VÀ child items đều có icons
9. **Dual Panel:** Cả 2 panel share models, services, policies, database, translations
--- ---
@@ -506,9 +563,10 @@ Tổng: 8 tests, 21 assertions.
| File | Nội dung | | File | Nội dung |
|------|----------| |------|----------|
| `AGENTS.md` | Hướng dẫn cho AI Agent: cách chạy, cấu trúc, workflow, RBAC, gotchas | | `AGENTS.md` | Hướng dẫn cho AI Agent: cách chạy, cấu trúc, workflow, RBAC, gotchas, patterns |
| `PROGRESS.md` | Lịch sử tiến độ hoàn thành (8 giai đoạn + bug fix) | | `TASKS_ROADMAP.md` | Roadmap + lịch sử tiến độ hoàn thành |
| `ai_instructions/AI_01_*.md` | Business Logic & Policies (hợp đồng snapshot, transfer policy, handover) | | `docs/I18N_GUIDE.md` | Hướng dẫn đa ngôn ngữ chi tiết |
| `ai_instructions/AI_02_*.md` | Database Schema Upgrade (contracts, handovers, product_services) | | `docs/ENUM_GUIDE.md` | Hướng dẫn thêm Enum mới |
| `ai_instructions/AI_03_*.md` | Data Import Pipeline (spatie/simple-excel, lazy collection) | | `UI_DESIGN_BRIEF.md` | Thiết kế UI chi tiết (horizontal top bar) |
| `TASKS_ROADMAP.md` | Roadmap: việc đã làm, đang làm, sẽ làm | | `webappUI/aftersales_crm_core/DESIGN.md` | Design tokens (colors, typography, spacing) |
| `luutru/` | Archive các file đã lỗi thời (tham khảo nếu cần) |

View File

@@ -5,12 +5,23 @@
--- ---
## ✅ ĐÃ HOÀN THÀNH (SOP Phase 18) ## Trạng thái hiện tại
- **SOP Phase 1-8:** 100% hoàn thành
- **AI Instructions Core:** 85% (6/7, còn auto-suggest transfer)
- **V2 Restructure:** 100% hoàn thành (Contract category, bỏ pivot, đại diện)
- **Test:** Pest 8/8 tests (21 assertions) pass
- **Data import:** 3658 rows từ `ai_instructions/CSKH.xlsx` imported successfully
- **Dual Panel:** Admin (đầy đủ) + Support (rút gọn, tập trung feedback)
---
## ✅ ĐÃ HOÀN THÀNH
### Giai đoạn 1: Mở rộng CSDL ### Giai đoạn 1: Mở rộng CSDL
- [x] Bảng `departments` (id, name, manager_id → users) - [x] Bảng `departments` (id, name, manager_id → users)
- [x] Bổ sung `feedback`: current_department_id, is_escalated - [x] Bổ sung `feedback`: current_department_id, is_escalated
- [x] Bảng `ticket_transfer_logs` - [x] Bảng `ticket_transfer_logs` (feedback_id, from/to department, sender, reason)
- [x] Nâng cấp `feedback_attachments`: uuid, disk, collection - [x] Nâng cấp `feedback_attachments`: uuid, disk, collection
- [x] Cài Spatie laravel-permission - [x] Cài Spatie laravel-permission
@@ -26,128 +37,224 @@
- [x] `TicketClosed` (Database + Mail) - [x] `TicketClosed` (Database + Mail)
### Giai đoạn 4: Filament UI ### Giai đoạn 4: Filament UI
- [x] `TransferDepartment` Action trên EditFeedback - [x] `TransferDepartment` Action trên Edit Feedback (modal: department + reason + attachment)
- [x] `CloseTicket` Action - [x] `CloseTicket` Action (visible: admin/manager, status ≠ closed, requires confirmation)
- [x] InteractionsRelationManager: role-aware status options - [x] InteractionsRelationManager: role-aware status options (staff: no "closed"), department field
- [x] FeedbackForm: current_department_id, is_escalated - [x] FeedbackForm: current_department_id, is_escalated, attachment_collection
### Giai đoạn 5: Dashboard Widgets ### Giai đoạn 5: Dashboard Widgets
- [x] `ResolvedTicketsWidget` - [x] `ResolvedTicketsWidget`: bảng ticket resolved chờ đóng (manager lọc theo phòng quản lý)
- [x] `AvgProcessingTimeWidget` - [x] `AvgProcessingTimeWidget`: 4 stats (resolved count, avg time, pending, escalated)
- [x] `HandlerPerformanceWidget` - [x] `HandlerPerformanceWidget`: bar chart thời gian xử lý trung bình theo nhân viên
### Giai đoạn 6: Testing ### Giai đoạn 6: Testing
- [x] Pest: 8 tests (21 assertions) - [x] Pest cài đặt + 8 test scenarios
- [x] `ClosingPermissionTest`: 4 tests (staff 403, no evidence 422, with evidence OK, cross-department 403)
- [x] `TransferFlowTest`: 2 tests (success + missing reason)
### Giai đoạn 7: Seeder ### Giai đoạn 7: Seeder
- [x] 4 departments, 5 channels, 5 products, 4 customers, 5 feedbacks, 5 tags, 5 interactions, 1 transfer log, 3 attachments - [x] 4 departments (CSKH, Kỹ thuật, Kế toán, Pháp lý)
- [x] 1 ticket_transfer_log mẫu
- [x] 3 feedback_attachments (2 proof_of_resolution, 1 customer_evidence)
### Giai đoạn 8: Polish & Bug Fix ### Giai đoạn 8: Polish & Bug Fix
- [x] Dashboard widget filter Manager theo department - [x] Dashboard widget filter Manager theo department
- [x] Migration disk default fix - [x] Migration disk default fix (private → local)
- [x] File upload pattern fix - [x] File upload pattern fix
- [x] Department + Escalated columns trên FeedbackTable - [x] Department + Escalated columns trên FeedbackTable + Department filter
- [x] Validation proof_of_resolution khi close từ form - [x] Validation proof_of_resolution khi close từ form
- [x] Manager chỉ đóng ticket phòng mình - [x] Manager chỉ đóng ticket phòng mình
- [x] View Attachments trong Interaction History - [x] View Attachments trong Interaction History (temporary signed URL)
- [x] Docker deployment - [x] Docker deployment (Dockerfile, docker-compose, entrypoint)
- [x] Migration notifications table - [x] Migration notifications table
### Giai đoạn 9: Granular Permissions + Export Backup + User/Role Management ### Giai đoạn 9: Granular Permissions + Export Backup + User/Role Management
- [x] PermissionSeeder: 29 granular permissions (admin/manager/staff mapping) - [x] PermissionSeeder: 29 granular permissions (view/create/update/delete per module + close-ticket, transfer-department, export-data)
- [x] Role → Permission mapping: admin (all), manager (no delete/export), staff (view + limited write)
- [x] Policies updated to `hasPermissionTo()` (5 policies) - [x] Policies updated to `hasPermissionTo()` (5 policies)
- [x] ExportBackup command: `app:export-backup` (JSON, per-table, chunk 500) - [x] ExportBackup command: `app:export-backup` (JSON, per-table, chunk 500, manifest.json)
- [x] UserResource: CRUD users + assign role (admin only) - [x] UserResource: admin-only CRUD users + assign role
- [x] RoleResource: CRUD roles + assign permissions via CheckboxList (admin only) - [x] RoleResource: admin-only CRUD roles + assign permissions via CheckboxList
- [x] UserPolicy + RolePolicy (admin-only access) - [x] UserPolicy + RolePolicy (admin-only access)
### A: Module Hợp đồng (Contract)
- [x] Migration `contracts`: product_id, customer_id, type (sale/lease/bcc), dates, status, signed_status
- [x] Enum `ContractType` (SALE/LEASE/BCC) + `ContractStatus` (ACTIVE/EXPIRED/LIQUIDATED)
- [x] Model `Contract`: relationships product(), customer(), feedbacks()
- [x] Filament Resource `Contracts` (CRUD) + `ContractPolicy`
- [x] RelationManager `ContractsRelationManager` trên ProductResource
- [x] Model `Product` thêm `contracts()` HasMany
- [x] Seeder: 5 contracts mẫu
### B: Cơ chế Snapshot Hợp đồng
- [x] Migration thêm `contract_id` (FK->contracts, nullable) vào bảng `feedback`
- [x] Model `Feedback`: thêm `contract_id` fillable + `contract()` BelongsTo
- [x] FeedbackForm: auto-select active contract khi chọn sản phẩm, cho phép chọn lại thủ công
- [x] FeedbackTable: cột "Contract" hiển thị loại HĐ dạng badge
- [x] Seeder: gán contract_id cho 5 feedback mẫu
### C: Module Bàn giao (Handover)
- [x] Migration `handovers`: product_id, customer_id, handover_date, status, remark
- [x] Enum `HandoverStatus` (NOT_READY/READY/SCHEDULED/HANDED_OVER)
- [x] Model `Handover`: relationships product(), customer()
- [x] RelationManager `HandoversRelationManager` trên ProductResource
- [x] Model `Product` thêm `handovers()` HasMany
- [x] Seeder: 5 handovers mẫu
### D: Module Dịch vụ phụ trợ (ProductService)
- [x] Migration `product_services`: product_id, service_type, status, actual_collection_date, remark
- [x] Enum `ServiceType` (MANAGEMENT_FEE/GRATITUDE/SELF_BUSINESS)
- [x] Model `ProductService`: relationship product()
- [x] RelationManager `ProductServicesRelationManager` trên ProductResource
- [x] Model `Product` thêm `productServices()` HasMany
- [x] Seeder: 5 services mẫu
### E: Enhancement ProductResource
- [x] ProductResource có 3 tabs: Contracts + Handovers + Services (via getRelations())
### G: Data Import Pipeline
- [x] Cài `spatie/simple-excel` (Lazy Collection, chống OOM)
- [x] Command `app:import-cskh {file_path} --dry-run` với ProgressBar, chunk 100 rows
- [x] Pipeline per row: Product/Customer firstOrCreate → customer_product pivot → Contract → Handover → Service → Feedback + Interactions
- [x] Xử lý DateTimeImmutable object từ Excel, skip header/meta rows
- [x] Test thành công: 3658 rows → 3299 products, 2089 customers, 2637 contracts, 2077 handovers, 159 services, 71 feedbacks, 226 interactions
### Internationalization (i18n) — Vietnamese + English
- [x] Config: `APP_LOCALE=vi`, `APP_FALLBACK_LOCALE=en`
- [x] Created `lang/en/` and `lang/vi/` with 3 files each: `app.php`, `feedback.php`, `enums.php`
- [x] ~120 translation keys: navigation, labels, status, widgets, services, notifications, enums
- [x] All Resources: override `getPluralLabel()` + `getNavigationGroup()` with `__()` calls
- [x] All Form fields: explicit `->label(__('key'))`
- [x] All Table columns: explicit `->label(__('key'))`
- [x] All RelationManagers: `$title` uses translation key
- [x] All Widgets: `getHeading()`/`getDescription()` return translated strings
- [x] Enums: `ContractType`, `ContractStatus`, `HandoverStatus`, `ServiceType` use `__()` in `label()`
- [x] Filament vendor: 57 Vietnamese translation files auto-activated
### UI Polish & Bug Fixes
- [x] File upload: Fixed `disk('local')``disk('public')` across all components
- [x] File upload: Added `exists()` check before getting metadata
- [x] File upload: Fixed `dehydrated(false)` issue — use property to store paths
- [x] Tailwind CSS: Added ~200 utility classes to `public/css/filament-custom.css`
- [x] SVG icons: Use inline `width`/`height` attributes instead of Tailwind classes
- [x] GlobalSearch: Customized for all Resources with multi-field search
- [x] RelationManager titles: Override `getTitle()` for proper translation
- [x] Enum refactoring: Added `color()` method, static `options()`, developer comments
- [x] Documentation: Created `docs/I18N_GUIDE.md` and `docs/ENUM_GUIDE.md`
### Support Panel (Dual Panel)
- [x] `SupportPanelProvider`: panel thứ 2 tại path `/support`, rút gọn chỉ tập trung feedback
- [x] Resources trong Support: Feedback, Customer, Product, FeedbackChannel, FeedbackTag, ActivityLog
- [x] Widgets: ResolvedTicketsWidget, AvgProcessingTimeWidget, HandlerPerformanceWidget
### V2: Contract Restructure — Category + Representative + Bỏ Pivot
- [x] Migration: thêm `category` (ownership/business), `representative_*` vào contracts, xóa `customer_product`
- [x] Enum: `ContractCategory` (ownership, business) + cập nhật `ContractType` (deposit, purchase, transfer, rental, self_business, bcc)
- [x] Model: Contract (+category, +representative), Customer (ownedProducts qua contracts), Feedback (-customer_product_id)
- [x] Xóa `CustomerProduct` model/pivot
- [x] Validation: ràng buộc 1 active/category/product (CreateContract/EditContract)
- [x] FeedbackForm: filter mới (Customer → Product qua Contract ownership + đại diện), case-insensitive search
- [x] ContractForm: select category → dynamic type options, representative form section
- [x] FeedbackTable: `contract.product.name` thay `customerProduct.product.name`
- [x] Seeder: 6 contracts V2 (ownership+business, có representative), feedback no customer_product_id
- [x] ImportCskh: cập nhật pipeline, không còn customer_product
- [x] i18n: vi/en cho category, type mới, representative, validation
- [x] Tests: 8/8 pass (21 assertions)
### ActivityLog — Audit Trail
- [x] Migration `activity_logs`: user_id, action, description, subject_type/id, metadata
- [x] Model `ActivityLog` + Service `ActivityLogger` (static log method)
- [x] Filament Resource `ActivityLogResource` (read-only, list view with filters)
- [x] Policy `ActivityLogPolicy` (admin-only)
- [x] Translation keys: `resource_activity_logs`, `action_*`, `details`, `system`
--- ---
## 🔴 CHƯA LÀM — Theo AI Instructions ## 🔴 CHƯA LÀM
### A: Module Hợp đồng (Contract) — từ `AI_01`, `AI_02` ### F: Tự động gợi ý transfer (optional, nice-to-have)
- [x] Tạo migration bảng `contracts`:
- `product_id` FK, `customer_id` FK
- `type` (LEASE/BCC/SALE)
- `start_date`, `end_date`
- `status` (Active/Expired/Liquidated)
- `printed_at`, `signed_status`
- [x] Tạo Model `Contract` + Enum `ContractType`
- [x] Relationships: `product()`, `customer()`, `feedbacks()`
- [x] Tạo ContractResource Filament + ContractPolicy
- [x] Tạo ContractsRelationManager trên ProductResource
### B: Cơ chế Snapshot Hợp đồng — từ `AI_01`
- [x] Tạo migration thêm `contract_id` (FK->contracts, nullable) vào bảng `feedback`
- [x] Cập nhật Model `Feedback`: fillable + relationship `contract()`
- [x] Logic auto-select active contract khi tạo Feedback mới (FeedbackForm)
- [x] Hiển thị contract info trên Feedback list (FeedbackTable column)
- [x] Gán contract_id cho feedback mẫu trong Seeder
### C: Module Bàn giao (Handover) — từ `AI_01`, `AI_02`
- [x] Tạo migration bảng `handovers`:
- `product_id` FK, `customer_id` FK
- `handover_date` (date)
- `status` (Chưa đủ điều kiện/Đủ ĐK/Đã lên lịch/Đã BG)
- `remark` (text nullable)
- [x] Tạo Model `Handover` + Enum `HandoverStatus`
- [x] Relationships: `product()`, `customer()`
- [x] Tạo `HandoversRelationManager` gắn vào `ProductResource`
- [x] Cập nhật Product model: thêm `handovers()` HasMany
### D: Module Dịch vụ phụ trợ (ProductService) — từ `AI_02`
- [x] Tạo migration bảng `product_services`:
- `product_id` FK
- `service_type` (MANAGEMENT_FEE/GRATITUDE/SELF_BUSINESS)
- `status`
- `actual_collection_date` (date nullable)
- `remark` (text nullable)
- [x] Tạo Model `ProductService` + Enum `ServiceType`
- [x] Relationship: `product()`
- [x] Tạo `ProductServicesRelationManager` gắn vào `ProductResource`
- [x] Cập nhật Product model: thêm `productServices()` HasMany
### E: Enhancement ProductResource — từ `AI_02`
- [x] Thêm RelationManagers vào `ProductResource::getRelations()`
- ContractsRelationManager ✅
- HandoversRelationManager ✅
- ProductServicesRelationManager ✅
- [x] Product detail page có 3 tabs: Contracts + Handovers + Services
### F: Tự động gợi ý transfer — từ `AI_01` (optional)
- [ ] Hiển thị badge gợi ý: "Ticket BCC → khuyến nghị chuyển Pháp lý" - [ ] Hiển thị badge gợi ý: "Ticket BCC → khuyến nghị chuyển Pháp lý"
- [ ] Logic detect contract type → suggest department - [ ] Logic detect contract type → suggest department
### G: Data Import Pipeline — từ `AI_03`
- [x] Cài package `spatie/simple-excel`
- [x] Tạo Command `app:import-cskh {file_path} --dry-run`
- [x] Logic: Lazy Collection, chunk 100 rows, DB::transaction, ProgressBar
- [x] Pipeline per row: Product/Customer firstOrCreate → Contract/Handover/Service → Feedback + Interactions
- [x] Tạo customer_product pivot record
- [x] Xử lý DateTimeImmutable từ Excel
- [x] Skip header/meta rows
- [x] Đã test thành công với CSKH.xlsx (3658 rows → 3299 products, 2089 customers, 2637 contracts, 2077 handovers, 159 services, 71 feedbacks, 226 interactions)
--- ---
## 📋 Ưu tiên phát triển ## 📋 Ưu tiên phát triển
| Ưu tiên | Task | Phụ thuộc | | Ưu tiên | Task | Phụ thuộc |
|---------|------|-----------| |---------|------|-----------|
| 1 | ~~A: Module Hợp đng (Migration + Model)~~ ✅ | Không | | 1 | F: Tự đng gợi ý transfer (nice-to-have) | A |
| 2 | ~~B: contract_id trên feedback (Snapshot)~~ ✅ | A |
| 3 | ~~C: Module Bàn giao (Migration + Model + RelationManager)~~ ✅ | Không |
| 4 | ~~D: Module Dịch vụ (Migration + Model + RelationManager)~~ ✅ | Không |
| 5 | ~~E: Enhancement ProductResource~~ ✅ | A, C, D |
| 6 | ~~G: Data Import Pipeline~~ ✅ | A, B, C, D |
| 7 | F: Tự động gợi ý transfer (nice-to-have) | A |
--- ---
## 📊 Tiến độ tổng quan ## 📊 Tiến độ tổng quan
``` ```
SOP Phase 1-8: ████████████████████████ 100% (Hoàn thành) SOP Phase 1-9: ████████████████████████ 100% (Hoàn thành)
AI Instructions Core: ███████████████████████░ 85% (6/7 — Còn: auto-suggest transfer) AI Instructions Core: ███████████████████████░ 85% (6/7 — Còn: auto-suggest transfer)
Data Import Tested: ████████████████████████ 100% (3658 rows real data imported successfully) Support Panel: ████████████████████████ 100% (Hoàn thành)
ActivityLog: ████████████████████████ 100% (Hoàn thành)
i18n (vi/en): ████████████████████████ 100% (Hoàn thành)
Data Import: ████████████████████████ 100% (3658 rows imported)
Tests: ████████████████████████ 100% (8 tests, 21 assertions)
``` ```
---
## Cách chạy Local Dev
```bash
cd /home/phuongtc/vibecode/minicrm
php artisan migrate:fresh --seed
php artisan serve
# Admin panel: http://localhost:8000/admin
# Support panel: http://localhost:8000/support
php artisan test # 8 tests (21 assertions)
```
### Data Import
```bash
php artisan app:import-cskh ai_instructions/CSKH.xlsx --dry-run # phân tích
php artisan app:import-cskh ai_instructions/CSKH.xlsx # import thật
```
### Export Backup
```bash
php artisan app:export-backup
php artisan app:export-backup --path=/custom/path --pretty
php artisan app:export-backup --tables=feedback,customers,products
```
---
## Tài khoản test (seeded)
| Role | Email | Password |
|------|-------|----------|
| Admin | admin@minicrm.local | password |
| Manager | manager@minicrm.local | password |
| Staff | staff@minicrm.local | password |
---
## Tech Stack
- PHP 8.3, Laravel 13.6.0, Filament 5.6.1
- Database: SQLite (`database/database.sqlite`)
- Composer: `/home/phuongtc/composer`
- Spatie: laravel-permission (RBAC)
- Testing: Pest PHP
---
## File hướng dẫn cho AI Agent
| File | Nội dung |
|------|----------|
| `AGENTS.md` | Hướng dẫn toàn diện: chạy, cấu trúc, workflow, RBAC, gotchas, patterns |
| `CODEBASE_SNAPSHOT.md` | Snapshot cấu trúc codebase (đọc thay vì scan code) |
| `TASKS_ROADMAP.md` | File này — roadmap + tiến độ |
| `docs/I18N_GUIDE.md` | Hướng dẫn đa ngôn ngữ chi tiết |
| `docs/ENUM_GUIDE.md` | Hướng dẫn thêm Enum mới |
| `UI_DESIGN_BRIEF.md` | Thiết kế UI chi tiết (horizontal top bar) |
| `webappUI/aftersales_crm_core/DESIGN.md` | Design tokens (colors, typography, spacing) |
| `luutru/` | Archive các file đã lỗi thời (AI_01-03 specs, SOP_des, PROGRESS cũ...) |

View File

@@ -5,7 +5,6 @@ namespace App\Console\Commands;
use App\Services\ActivityLogger; use App\Services\ActivityLogger;
use App\Models\Contract; use App\Models\Contract;
use App\Models\Customer; use App\Models\Customer;
use App\Models\CustomerProduct;
use App\Models\Feedback; use App\Models\Feedback;
use App\Models\FeedbackInteraction; use App\Models\FeedbackInteraction;
use App\Models\Handover; use App\Models\Handover;
@@ -22,7 +21,7 @@ class ImportCskh extends Command
{file_path : Path to CSV/Excel file} {file_path : Path to CSV/Excel file}
{--dry-run : Analyze only, do not write to database}'; {--dry-run : Analyze only, do not write to database}';
protected $description = 'Import dữ liệu CSKH từ file Excel/CSV vào database relational'; protected $description = 'Import dữ liệu CSKH từ file Excel/CSV vào database relational (V2)';
private int $statsProducts = 0; private int $statsProducts = 0;
private int $statsCustomers = 0; private int $statsCustomers = 0;
@@ -123,11 +122,6 @@ class ImportCskh extends Command
return self::SUCCESS; return self::SUCCESS;
} }
private function isMetaRow(array $row): bool
{
return $this->getMetaRowReason($row) !== null;
}
private function getMetaRowReason(array $row): ?string private function getMetaRowReason(array $row): ?string
{ {
$code = $row['Mã căn hộ'] ?? ''; $code = $row['Mã căn hộ'] ?? '';
@@ -210,8 +204,6 @@ class ImportCskh extends Command
$product = $this->findOrCreateProduct($productCode); $product = $this->findOrCreateProduct($productCode);
$customer = $this->findOrCreateCustomer($customerName); $customer = $this->findOrCreateCustomer($customerName);
$this->ensureCustomerProduct($product, $customer);
$this->processContracts($row, $product, $customer); $this->processContracts($row, $product, $customer);
$this->processHandover($row, $product, $customer); $this->processHandover($row, $product, $customer);
$this->processServices($row, $product); $this->processServices($row, $product);
@@ -250,14 +242,6 @@ class ImportCskh extends Command
return $c; return $c;
} }
private function ensureCustomerProduct(Product $product, Customer $customer): void
{
CustomerProduct::firstOrCreate([
'customer_id' => $customer->id,
'product_id' => $product->id,
]);
}
private function processContracts(array $row, Product $product, Customer $customer): void private function processContracts(array $row, Product $product, Customer $customer): void
{ {
$leaseValue = $row['HỢP ĐỒNG THUÊ'] ?? null; $leaseValue = $row['HỢP ĐỒNG THUÊ'] ?? null;
@@ -265,14 +249,16 @@ class ImportCskh extends Command
if (! empty($leaseStr) && ! is_numeric($leaseStr) && $leaseStr !== 'Tình trạng') { if (! empty($leaseStr) && ! is_numeric($leaseStr) && $leaseStr !== 'Tình trạng') {
$exists = Contract::where('product_id', $product->id) $exists = Contract::where('product_id', $product->id)
->where('customer_id', $customer->id) ->where('customer_id', $customer->id)
->where('type', 'lease') ->where('category', 'business')
->where('type', 'rental')
->exists(); ->exists();
if (! $exists) { if (! $exists) {
Contract::create([ Contract::create([
'product_id' => $product->id, 'product_id' => $product->id,
'customer_id' => $customer->id, 'customer_id' => $customer->id,
'type' => 'lease', 'category' => 'business',
'type' => 'rental',
'status' => 'active', 'status' => 'active',
]); ]);
$this->statsContracts++; $this->statsContracts++;
@@ -284,6 +270,7 @@ class ImportCskh extends Command
if (! empty($bccStr) && ! is_numeric($bccStr) && $bccStr !== 'Tình trạng HĐ') { if (! empty($bccStr) && ! is_numeric($bccStr) && $bccStr !== 'Tình trạng HĐ') {
$exists = Contract::where('product_id', $product->id) $exists = Contract::where('product_id', $product->id)
->where('customer_id', $customer->id) ->where('customer_id', $customer->id)
->where('category', 'business')
->where('type', 'bcc') ->where('type', 'bcc')
->exists(); ->exists();
@@ -291,6 +278,7 @@ class ImportCskh extends Command
Contract::create([ Contract::create([
'product_id' => $product->id, 'product_id' => $product->id,
'customer_id' => $customer->id, 'customer_id' => $customer->id,
'category' => 'business',
'type' => 'bcc', 'type' => 'bcc',
'status' => 'active', 'status' => 'active',
'signed_status' => $bccStr, 'signed_status' => $bccStr,
@@ -386,20 +374,15 @@ class ImportCskh extends Command
$title = 'Ticket từ dữ liệu lịch sử'; $title = 'Ticket từ dữ liệu lịch sử';
$customerProduct = CustomerProduct::where('customer_id', $customer->id)
->where('product_id', $product->id)
->first();
$feedback = Feedback::firstOrCreate( $feedback = Feedback::firstOrCreate(
[ [
'customer_id' => $customer->id, 'customer_id' => $customer->id,
'customer_product_id' => $customerProduct?->id, 'contract_id' => $activeContract?->id,
'title' => $title, 'title' => $title,
], ],
[ [
'content' => $content, 'content' => $content,
'status' => 'pending', 'status' => 'pending',
'contract_id' => $activeContract?->id,
'feedback_channel_id' => 1, 'feedback_channel_id' => 1,
] ]
); );
@@ -429,9 +412,6 @@ class ImportCskh extends Command
} }
} }
/**
* Parse the PHP DateTime JSON format: {"date":"2021-06-09 00:00:00.000000","timezone_type":3,"timezone":"UTC"}
*/
private function parseHandoverDate(mixed $value): ?string private function parseHandoverDate(mixed $value): ?string
{ {
if (empty($value)) { if (empty($value)) {

View File

@@ -0,0 +1,39 @@
<?php
namespace App\Enums;
/**
* Contract Category Enum Phân loại hợp đồng cấp cao
*
* Mỗi căn hộ chỉ tối đa 1 active mỗi category tại cùng thời điểm.
* - ownership: Sở hữu (đặt cọc, mua bán, chuyển nhượng...)
* - business: Kinh doanh (cho thuê, tự doanh, hợp tác KD...)
*/
enum ContractCategory: string
{
case OWNERSHIP = 'ownership';
case BUSINESS = 'business';
public function label(): string
{
return match ($this) {
self::OWNERSHIP => __('enums.contract_category.ownership'),
self::BUSINESS => __('enums.contract_category.business'),
};
}
public function color(): string
{
return match ($this) {
self::OWNERSHIP => 'success',
self::BUSINESS => 'info',
};
}
public static function options(): array
{
return collect(self::cases())->mapWithKeys(fn ($case) => [
$case->value => $case->label(),
])->toArray();
}
}

View File

@@ -3,24 +3,33 @@
namespace App\Enums; namespace App\Enums;
/** /**
* Contract Type Enum * Contract Type Enum Loại hợp đồng chi tiết (subtype của category)
* *
* Để thêm loại hợp đồng mới: * Ownership: deposit (đặt cọc), purchase (mua bán), transfer (chuyển nhượng)
* 1. Thêm case mới vào enum * Business: rental (cho thuê), self_business (tự doanh), bcc (hợp tác KD)
*
* Để thêm loại mới:
* 1. Thêm case mới vào enum + gán category phù hợp trong category()
* 2. Thêm label trong lang/vi/enums.php lang/en/enums.php * 2. Thêm label trong lang/vi/enums.php lang/en/enums.php
* 3. Reload browser * 3. Reload browser
*/ */
enum ContractType: string enum ContractType: string
{ {
case SALE = 'sale'; case DEPOSIT = 'deposit';
case LEASE = 'lease'; case PURCHASE = 'purchase';
case TRANSFER = 'transfer';
case RENTAL = 'rental';
case SELF_BUSINESS = 'self_business';
case BCC = 'bcc'; case BCC = 'bcc';
public function label(): string public function label(): string
{ {
return match ($this) { return match ($this) {
self::SALE => __('enums.contract_type.sale'), self::DEPOSIT => __('enums.contract_type.deposit'),
self::LEASE => __('enums.contract_type.lease'), self::PURCHASE => __('enums.contract_type.purchase'),
self::TRANSFER => __('enums.contract_type.transfer'),
self::RENTAL => __('enums.contract_type.rental'),
self::SELF_BUSINESS => __('enums.contract_type.self_business'),
self::BCC => __('enums.contract_type.bcc'), self::BCC => __('enums.contract_type.bcc'),
}; };
} }
@@ -28,9 +37,20 @@ enum ContractType: string
public function color(): string public function color(): string
{ {
return match ($this) { return match ($this) {
self::SALE => 'success', self::DEPOSIT => 'warning',
self::LEASE => 'info', self::PURCHASE => 'success',
self::BCC => 'warning', self::TRANSFER => 'info',
self::RENTAL => 'info',
self::SELF_BUSINESS => 'warning',
self::BCC => 'danger',
};
}
public function category(): ContractCategory
{
return match ($this) {
self::DEPOSIT, self::PURCHASE, self::TRANSFER => ContractCategory::OWNERSHIP,
self::RENTAL, self::SELF_BUSINESS, self::BCC => ContractCategory::BUSINESS,
}; };
} }
@@ -40,4 +60,14 @@ enum ContractType: string
$case->value => $case->label(), $case->value => $case->label(),
])->toArray(); ])->toArray();
} }
public static function ownershipCases(): array
{
return [self::DEPOSIT, self::PURCHASE, self::TRANSFER];
}
public static function businessCases(): array
{
return [self::RENTAL, self::SELF_BUSINESS, self::BCC];
}
} }

View File

@@ -2,6 +2,7 @@
namespace App\Filament\Resources\Contracts; namespace App\Filament\Resources\Contracts;
use App\Enums\ContractCategory;
use App\Filament\Resources\Contracts\Pages\CreateContract; use App\Filament\Resources\Contracts\Pages\CreateContract;
use App\Filament\Resources\Contracts\Pages\EditContract; use App\Filament\Resources\Contracts\Pages\EditContract;
use App\Filament\Resources\Contracts\Pages\ListContracts; use App\Filament\Resources\Contracts\Pages\ListContracts;
@@ -64,7 +65,6 @@ class ContractResource extends Resource
]; ];
} }
// GlobalSearch customization
public static function getGlobalSearchEloquentQuery(): Builder public static function getGlobalSearchEloquentQuery(): Builder
{ {
return parent::getGlobalSearchEloquentQuery() return parent::getGlobalSearchEloquentQuery()
@@ -89,6 +89,7 @@ class ContractResource extends Resource
return [ return [
__('app.product') => $record->product?->name ?? '-', __('app.product') => $record->product?->name ?? '-',
__('app.widget_customer') => $record->customer?->name ?? '-', __('app.widget_customer') => $record->customer?->name ?? '-',
__('enums.contract_category_label') => ContractCategory::from($record->category)->label(),
__('app.blade_status') => \App\Enums\ContractStatus::from($record->status)->label(), __('app.blade_status') => \App\Enums\ContractStatus::from($record->status)->label(),
__('app.signed_status') => $record->signed_status ?? '-', __('app.signed_status') => $record->signed_status ?? '-',
]; ];

View File

@@ -3,9 +3,38 @@
namespace App\Filament\Resources\Contracts\Pages; namespace App\Filament\Resources\Contracts\Pages;
use App\Filament\Resources\Contracts\ContractResource; use App\Filament\Resources\Contracts\ContractResource;
use App\Models\Contract;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord; use Filament\Resources\Pages\CreateRecord;
class CreateContract extends CreateRecord class CreateContract extends CreateRecord
{ {
protected static string $resource = ContractResource::class; protected static string $resource = ContractResource::class;
protected function mutateFormDataBeforeCreate(array $data): array
{
if (($data['status'] ?? '') === 'active') {
$existing = Contract::where('product_id', $data['product_id'])
->where('category', $data['category'])
->where('status', 'active')
->first();
if ($existing) {
Notification::make()
->title(__('feedback.contract_duplicate_title', [
'category' => \App\Enums\ContractCategory::from($data['category'])->label(),
]))
->body(__('feedback.contract_duplicate_body', [
'product' => $existing->product?->name ?? '?',
'customer' => $existing->customer?->name ?? '?',
]))
->warning()
->send();
$this->halt();
}
}
return $data;
}
} }

View File

@@ -3,7 +3,9 @@
namespace App\Filament\Resources\Contracts\Pages; namespace App\Filament\Resources\Contracts\Pages;
use App\Filament\Resources\Contracts\ContractResource; use App\Filament\Resources\Contracts\ContractResource;
use App\Models\Contract;
use Filament\Actions\DeleteAction; use Filament\Actions\DeleteAction;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord; use Filament\Resources\Pages\EditRecord;
class EditContract extends EditRecord class EditContract extends EditRecord
@@ -16,4 +18,32 @@ class EditContract extends EditRecord
DeleteAction::make(), DeleteAction::make(),
]; ];
} }
protected function mutateFormDataBeforeSave(array $data): array
{
if (($data['status'] ?? '') === 'active') {
$existing = Contract::where('product_id', $data['product_id'])
->where('category', $data['category'])
->where('status', 'active')
->where('id', '!=', $this->getRecord()->id)
->first();
if ($existing) {
Notification::make()
->title(__('feedback.contract_duplicate_title', [
'category' => \App\Enums\ContractCategory::from($data['category'])->label(),
]))
->body(__('feedback.contract_duplicate_body', [
'product' => $existing->product?->name ?? '?',
'customer' => $existing->customer?->name ?? '?',
]))
->warning()
->send();
$this->halt();
}
}
return $data;
}
} }

View File

@@ -2,6 +2,7 @@
namespace App\Filament\Resources\Contracts\Schemas; namespace App\Filament\Resources\Contracts\Schemas;
use App\Enums\ContractCategory;
use App\Enums\ContractStatus; use App\Enums\ContractStatus;
use App\Enums\ContractType; use App\Enums\ContractType;
use Filament\Forms\Components\DatePicker; use Filament\Forms\Components\DatePicker;
@@ -16,6 +17,36 @@ class ContractForm
{ {
return $schema return $schema
->components([ ->components([
Section::make(__('app.contract_category_section'))
->schema([
Select::make('category')
->label(__('enums.contract_category_label'))
->options(ContractCategory::options())
->required()
->native(false)
->live(),
Select::make('type')
->label(__('enums.contract_type_label'))
->options(function ($get): array {
$category = $get('category');
if ($category === 'ownership') {
return collect(ContractType::ownershipCases())->mapWithKeys(fn ($c) => [
$c->value => $c->label(),
])->toArray();
}
if ($category === 'business') {
return collect(ContractType::businessCases())->mapWithKeys(fn ($c) => [
$c->value => $c->label(),
])->toArray();
}
return ContractType::options();
})
->required()
->native(false),
])
->columns(2),
Section::make(__('app.contract_info')) Section::make(__('app.contract_info'))
->schema([ ->schema([
Select::make('product_id') Select::make('product_id')
@@ -28,11 +59,6 @@ class ContractForm
->relationship('customer', 'name') ->relationship('customer', 'name')
->searchable() ->searchable()
->required(), ->required(),
Select::make('type')
->label(__('app.contract'))
->options(ContractType::options())
->required()
->native(false),
Select::make('status') Select::make('status')
->label(__('app.status')) ->label(__('app.status'))
->options(ContractStatus::ACTIVE->options()) ->options(ContractStatus::ACTIVE->options())
@@ -50,6 +76,22 @@ class ContractForm
->maxLength(255), ->maxLength(255),
]) ])
->columns(2), ->columns(2),
Section::make(__('app.representative_info'))
->description(__('app.representative_desc'))
->schema([
TextInput::make('representative_name')
->label(__('app.name'))
->maxLength(255),
TextInput::make('representative_phone')
->label(__('app.phone'))
->maxLength(20),
TextInput::make('representative_email')
->label(__('app.email'))
->email()
->maxLength(255),
])
->columns(3),
]); ]);
} }
} }

View File

@@ -2,10 +2,12 @@
namespace App\Filament\Resources\Contracts\Tables; namespace App\Filament\Resources\Contracts\Tables;
use App\Enums\ContractCategory;
use Filament\Actions\BulkActionGroup; use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction; use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction; use Filament\Actions\EditAction;
use Filament\Tables\Columns\TextColumn; use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table; use Filament\Tables\Table;
class ContractsTable class ContractsTable
@@ -17,15 +19,25 @@ class ContractsTable
TextColumn::make('id') TextColumn::make('id')
->sortable(), ->sortable(),
TextColumn::make('product.name') TextColumn::make('product.name')
->label(__('app.product'))
->searchable() ->searchable()
->sortable(), ->sortable(),
TextColumn::make('customer.name') TextColumn::make('customer.name')
->label(__('app.widget_customer'))
->searchable() ->searchable()
->sortable(), ->sortable(),
TextColumn::make('type') TextColumn::make('category')
->label(__('enums.contract_category_label'))
->badge() ->badge()
->formatStateUsing(fn (string $state): string => \App\Enums\ContractType::from($state)->label()), ->formatStateUsing(fn (string $state): string => ContractCategory::from($state)->label())
->color(fn (string $state): string => ContractCategory::from($state)->color()),
TextColumn::make('type')
->label(__('enums.contract_type_label'))
->badge()
->formatStateUsing(fn (string $state): string => \App\Enums\ContractType::from($state)->label())
->color(fn (string $state): string => \App\Enums\ContractType::from($state)->color()),
TextColumn::make('status') TextColumn::make('status')
->label(__('app.status'))
->badge() ->badge()
->color(fn (string $state): string => match ($state) { ->color(fn (string $state): string => match ($state) {
'active' => 'success', 'active' => 'success',
@@ -34,15 +46,22 @@ class ContractsTable
default => 'gray', default => 'gray',
}) })
->formatStateUsing(fn (string $state): string => \App\Enums\ContractStatus::from($state)->label()), ->formatStateUsing(fn (string $state): string => \App\Enums\ContractStatus::from($state)->label()),
TextColumn::make('representative_name')
->label(__('app.representative'))
->placeholder('-')
->toggleable(),
TextColumn::make('start_date') TextColumn::make('start_date')
->label(__('app.start_date'))
->date() ->date()
->sortable() ->sortable()
->toggleable(), ->toggleable(),
TextColumn::make('end_date') TextColumn::make('end_date')
->label(__('app.end_date'))
->date() ->date()
->sortable() ->sortable()
->toggleable(), ->toggleable(),
TextColumn::make('signed_status') TextColumn::make('signed_status')
->label(__('app.signed_status'))
->toggleable(), ->toggleable(),
TextColumn::make('feedbacks_count') TextColumn::make('feedbacks_count')
->counts('feedbacks') ->counts('feedbacks')
@@ -53,7 +72,12 @@ class ContractsTable
->toggleable(), ->toggleable(),
]) ])
->filters([ ->filters([
// SelectFilter::make('category')
->label(__('enums.contract_category_label'))
->options(ContractCategory::options()),
SelectFilter::make('status')
->label(__('app.status'))
->options(\App\Enums\ContractStatus::ACTIVE->options()),
]) ])
->recordActions([ ->recordActions([
EditAction::make(), EditAction::make(),

View File

@@ -23,12 +23,14 @@ class FeedbacksRelationManager extends RelationManager
->recordTitleAttribute('title') ->recordTitleAttribute('title')
->columns([ ->columns([
TextColumn::make('title') TextColumn::make('title')
->label(__('app.blade_title'))
->searchable() ->searchable()
->url(fn ($record) => FeedbackResource::getUrl('edit', ['record' => $record])), ->url(fn ($record) => FeedbackResource::getUrl('edit', ['record' => $record])),
TextColumn::make('customerProduct.product.name') TextColumn::make('contract.product.name')
->label(__('app.product')) ->label(__('app.product'))
->placeholder(__('app.general')), ->placeholder(__('app.general')),
TextColumn::make('status') TextColumn::make('status')
->label(__('app.status'))
->badge() ->badge()
->color(fn (string $state): string => match ($state) { ->color(fn (string $state): string => match ($state) {
'pending' => 'warning', 'pending' => 'warning',

View File

@@ -41,15 +41,6 @@ class CustomerForm
]) ])
->columns(2), ->columns(2),
Section::make(__('app.owned_products'))
->schema([
Select::make('products')
->label(__('app.resource_products'))
->relationship('products', 'name')
->multiple()
->preload()
->columnSpanFull(),
]),
]); ]);
} }
} }

View File

@@ -31,9 +31,6 @@ class CustomersTable
'inactive' => 'gray', 'inactive' => 'gray',
default => 'gray', default => 'gray',
}), }),
TextColumn::make('products_count')
->counts('products')
->label(__('app.resource_products')),
TextColumn::make('feedbacks_count') TextColumn::make('feedbacks_count')
->counts('feedbacks') ->counts('feedbacks')
->label(__('app.feedbacks')), ->label(__('app.feedbacks')),

View File

@@ -65,11 +65,10 @@ class FeedbackResource extends Resource
]; ];
} }
// GlobalSearch customization
public static function getGlobalSearchEloquentQuery(): Builder public static function getGlobalSearchEloquentQuery(): Builder
{ {
return parent::getGlobalSearchEloquentQuery() return parent::getGlobalSearchEloquentQuery()
->with(['customer', 'customerProduct.product', 'currentDepartment']); ->with(['customer', 'contract.product', 'currentDepartment']);
} }
public static function modifyGlobalSearchQuery(Builder $query, string $search): void public static function modifyGlobalSearchQuery(Builder $query, string $search): void
@@ -83,7 +82,7 @@ class FeedbackResource extends Resource
{ {
return [ return [
__('app.widget_customer') => $record->customer?->name ?? '-', __('app.widget_customer') => $record->customer?->name ?? '-',
__('app.product') => $record->customerProduct?->product?->name ?? __('app.general'), __('app.product') => $record->contract?->product?->name ?? __('app.general'),
__('app.blade_status') => match ($record->status) { __('app.blade_status') => match ($record->status) {
'pending' => __('app.status_pending'), 'pending' => __('app.status_pending'),
'processing' => __('app.status_processing'), 'processing' => __('app.status_processing'),

View File

@@ -15,14 +15,10 @@ class CreateFeedback extends CreateRecord
protected function mutateFormDataBeforeCreate(array $data): array protected function mutateFormDataBeforeCreate(array $data): array
{ {
if (($data['is_general'] ?? false) === true) {
$data['customer_product_id'] = null;
}
$this->pendingAttachments = $data['attachments'] ?? []; $this->pendingAttachments = $data['attachments'] ?? [];
$this->pendingCollection = $data['attachment_collection'] ?? 'general'; $this->pendingCollection = $data['attachment_collection'] ?? 'general';
unset($data['is_general'], $data['attachment_collection'], $data['attachments']); unset($data['is_general'], $data['attachment_collection'], $data['attachments'], $data['product_id_virtual']);
return $data; return $data;
} }

View File

@@ -66,7 +66,7 @@ class EditFeedback extends EditRecord
->disk('public') ->disk('public')
->directory('feedback-attachments') ->directory('feedback-attachments')
->acceptedFileTypes(['image/jpeg', 'image/png', 'application/pdf', 'video/mp4', 'video/quicktime']) ->acceptedFileTypes(['image/jpeg', 'image/png', 'application/pdf', 'video/mp4', 'video/quicktime'])
->maxSize(51200) // 50MB in KB ->maxSize(51200)
->columnSpanFull(), ->columnSpanFull(),
]) ])
->action(function (array $data): void { ->action(function (array $data): void {
@@ -166,14 +166,10 @@ class EditFeedback extends EditRecord
protected function mutateFormDataBeforeSave(array $data): array protected function mutateFormDataBeforeSave(array $data): array
{ {
if (($data['is_general'] ?? false) === true) {
$data['customer_product_id'] = null;
}
$this->pendingAttachments = $data['attachments'] ?? []; $this->pendingAttachments = $data['attachments'] ?? [];
$this->pendingCollection = $data['attachment_collection'] ?? 'general'; $this->pendingCollection = $data['attachment_collection'] ?? 'general';
unset($data['is_general'], $data['attachment_collection'], $data['attachments']); unset($data['is_general'], $data['attachment_collection'], $data['attachments'], $data['product_id_virtual']);
$newStatus = $data['status'] ?? null; $newStatus = $data['status'] ?? null;
if ($newStatus === 'closed' && $this->getRecord()->status !== 'closed') { if ($newStatus === 'closed' && $this->getRecord()->status !== 'closed') {
@@ -235,7 +231,7 @@ class EditFeedback extends EditRecord
protected function mutateFormDataBeforeFill(array $data): array protected function mutateFormDataBeforeFill(array $data): array
{ {
$data['is_general'] = $data['customer_product_id'] === null; $data['is_general'] = $data['contract_id'] === null;
return $data; return $data;
} }

View File

@@ -2,7 +2,7 @@
namespace App\Filament\Resources\Feedback\Schemas; namespace App\Filament\Resources\Feedback\Schemas;
use App\Models\CustomerProduct; use App\Models\Contract;
use App\Models\Department; use App\Models\Department;
use Filament\Forms\Components\ColorPicker; use Filament\Forms\Components\ColorPicker;
use Filament\Forms\Components\FileUpload; use Filament\Forms\Components\FileUpload;
@@ -25,6 +25,7 @@ class FeedbackForm
->icon('heroicon-o-user-group') ->icon('heroicon-o-user-group')
->schema([ ->schema([
Select::make('customer_id') Select::make('customer_id')
->label(__('app.widget_customer'))
->relationship('customer', 'name') ->relationship('customer', 'name')
->searchable() ->searchable()
->required() ->required()
@@ -37,48 +38,51 @@ class FeedbackForm
->live() ->live()
->columnSpan(1), ->columnSpan(1),
Select::make('customer_product_id') Select::make('product_id_virtual')
->label(__('app.product')) ->label(__('app.product'))
->searchable() ->searchable()
->options(fn ($get): array => self::getProductOptionsForCustomer($get('customer_id')))
->getSearchResultsUsing(function (string $search, $get): array { ->getSearchResultsUsing(function (string $search, $get): array {
$customerId = $get('customer_id'); $customerId = $get('customer_id');
if (! $customerId) { if (! $customerId) {
return []; return [];
} }
$keyword = mb_strtolower($search); $keyword = mb_strtolower($search);
return CustomerProduct::where('customer_id', $customerId) $allIds = self::getProductIdsForCustomer($customerId);
->whereHas('product', fn ($q) => $q->whereRaw('LOWER(name) LIKE ?', ["%{$keyword}%"]))
->with('product') if ($allIds->isEmpty()) {
return [];
}
return \App\Models\Product::whereIn('id', $allIds)
->whereRaw('LOWER(name) LIKE ?', ["%{$keyword}%"])
->limit(50) ->limit(50)
->get() ->pluck('name', 'id')
->pluck('product.name', 'id')
->toArray(); ->toArray();
}) })
->getOptionLabelUsing(fn ($value): ?string => ->getOptionLabelUsing(fn ($value): ?string =>
CustomerProduct::find($value)?->product?->name \App\Models\Product::find($value)?->name
) )
->visible(fn ($get): bool => ! $get('is_general')) ->visible(fn ($get): bool => ! $get('is_general'))
->nullable() ->nullable()
->live(), ->live()
->columnSpan(1),
Select::make('contract_id') Select::make('contract_id')
->label(__('app.contract')) ->label(__('app.contract'))
->visible(fn ($get): bool => ! $get('is_general') && filled($get('customer_product_id'))) ->visible(fn ($get): bool => ! $get('is_general') && filled($get('product_id_virtual')))
->options(function ($get): array { ->options(function ($get): array {
$customerProductId = $get('customer_product_id'); $productId = $get('product_id_virtual');
if (! $customerProductId) { if (! $productId) {
return []; return [];
} }
$cp = \App\Models\CustomerProduct::find($customerProductId);
if (! $cp) { return Contract::where('product_id', $productId)
return [];
}
return \App\Models\Contract::where('product_id', $cp->product_id)
->where('status', 'active') ->where('status', 'active')
->with('customer') ->with('customer')
->get() ->get()
->mapWithKeys(fn ($c) => [ ->mapWithKeys(fn ($c) => [
$c->id => sprintf('%s (%s) - %s', $c->id => sprintf('%s — %s (%s)',
\App\Enums\ContractType::from($c->type)->label(), \App\Enums\ContractType::from($c->type)->label(),
$c->customer->name, $c->customer->name,
$c->start_date?->format('d/m/Y') ?? 'N/A', $c->start_date?->format('d/m/Y') ?? 'N/A',
@@ -90,15 +94,11 @@ class FeedbackForm
if (filled($state)) { if (filled($state)) {
return; return;
} }
$customerProductId = $get('customer_product_id'); $productId = $get('product_id_virtual');
if (! $customerProductId) { if (! $productId) {
return; return;
} }
$cp = \App\Models\CustomerProduct::find($customerProductId); $activeContract = Contract::where('product_id', $productId)
if (! $cp) {
return;
}
$activeContract = \App\Models\Contract::where('product_id', $cp->product_id)
->where('status', 'active') ->where('status', 'active')
->first(); ->first();
if ($activeContract) { if ($activeContract) {
@@ -115,17 +115,20 @@ class FeedbackForm
->icon('heroicon-o-chat-bubble-left-right') ->icon('heroicon-o-chat-bubble-left-right')
->schema([ ->schema([
Select::make('feedback_channel_id') Select::make('feedback_channel_id')
->label(__('app.channel'))
->relationship('feedbackChannel', 'name') ->relationship('feedbackChannel', 'name')
->required() ->required()
->preload() ->preload()
->columnSpan(1), ->columnSpan(1),
TextInput::make('title') TextInput::make('title')
->label(__('app.blade_title'))
->required() ->required()
->maxLength(255) ->maxLength(255)
->columnSpan(1), ->columnSpan(1),
Textarea::make('content') Textarea::make('content')
->label(__('app.description'))
->required() ->required()
->rows(6) ->rows(6)
->columnSpanFull(), ->columnSpanFull(),
@@ -136,9 +139,9 @@ class FeedbackForm
->preload() ->preload()
->columnSpanFull() ->columnSpanFull()
->createOptionForm([ ->createOptionForm([
TextInput::make('name')->required(), TextInput::make('name')->label(__('app.name'))->required(),
TextInput::make('slug')->required(), TextInput::make('slug')->label(__('app.slug'))->required(),
ColorPicker::make('color')->default('#3b82f6'), ColorPicker::make('color')->label(__('app.color'))->default('#3b82f6'),
]), ]),
]) ])
->columns(2), ->columns(2),
@@ -148,6 +151,7 @@ class FeedbackForm
->icon('heroicon-o-arrow-path-rounded-square') ->icon('heroicon-o-arrow-path-rounded-square')
->schema([ ->schema([
Select::make('status') Select::make('status')
->label(__('app.status'))
->options([ ->options([
'pending' => __('app.status_pending'), 'pending' => __('app.status_pending'),
'processing' => __('app.status_processing'), 'processing' => __('app.status_processing'),
@@ -159,6 +163,7 @@ class FeedbackForm
->columnSpan(1), ->columnSpan(1),
Select::make('assigned_to') Select::make('assigned_to')
->label(__('app.assigned_to'))
->relationship('assignedTo', 'name') ->relationship('assignedTo', 'name')
->searchable() ->searchable()
->nullable() ->nullable()
@@ -198,10 +203,42 @@ class FeedbackForm
->disk('public') ->disk('public')
->directory('feedback-attachments') ->directory('feedback-attachments')
->acceptedFileTypes(['image/jpeg', 'image/png', 'application/pdf', 'video/mp4', 'video/quicktime']) ->acceptedFileTypes(['image/jpeg', 'image/png', 'application/pdf', 'video/mp4', 'video/quicktime'])
->maxSize(51200) // 50MB in KB ->maxSize(51200)
->columnSpan(1), ->columnSpan(1),
]) ])
->columns(2), ->columns(2),
]); ]);
} }
private static function getProductOptionsForCustomer(?int $customerId): array
{
$ids = self::getProductIdsForCustomer($customerId);
return \App\Models\Product::whereIn('id', $ids)
->limit(100)
->pluck('name', 'id')
->toArray();
}
private static function getProductIdsForCustomer(?int $customerId): \Illuminate\Support\Collection
{
if (! $customerId) {
return collect();
}
$ownedIds = Contract::where('customer_id', $customerId)
->where('category', 'ownership')
->where('status', 'active')
->pluck('product_id');
$customer = \App\Models\Customer::find($customerId);
$repIds = collect();
if ($customer?->email) {
$repIds = Contract::where('representative_email', $customer->email)
->where('status', 'active')
->pluck('product_id');
}
return $ownedIds->merge($repIds)->unique();
}
} }

View File

@@ -23,16 +23,18 @@ class FeedbackTable
->color('primary'), ->color('primary'),
TextColumn::make('title') TextColumn::make('title')
->label(__('app.blade_title'))
->searchable() ->searchable()
->sortable() ->sortable()
->weight('semibold') ->weight('semibold')
->limit(40), ->limit(40),
TextColumn::make('customer.name') TextColumn::make('customer.name')
->label(__('app.widget_customer'))
->searchable() ->searchable()
->sortable(), ->sortable(),
TextColumn::make('customerProduct.product.name') TextColumn::make('contract.product.name')
->label(__('app.product')) ->label(__('app.product'))
->placeholder(__('app.general')) ->placeholder(__('app.general'))
->sortable() ->sortable()
@@ -43,9 +45,12 @@ class FeedbackTable
->badge() ->badge()
->formatStateUsing(fn (?string $state): string => $state ? \App\Enums\ContractType::from($state)->label() : '-') ->formatStateUsing(fn (?string $state): string => $state ? \App\Enums\ContractType::from($state)->label() : '-')
->color(fn (?string $state): string => match ($state) { ->color(fn (?string $state): string => match ($state) {
'sale' => 'success', 'deposit' => 'warning',
'lease' => 'info', 'purchase' => 'success',
'bcc' => 'warning', 'transfer' => 'info',
'rental' => 'info',
'self_business' => 'warning',
'bcc' => 'danger',
default => 'gray', default => 'gray',
}) })
->placeholder('-') ->placeholder('-')
@@ -62,6 +67,7 @@ class FeedbackTable
->toggleable(), ->toggleable(),
TextColumn::make('status') TextColumn::make('status')
->label(__('app.status'))
->badge() ->badge()
->color(fn(string $state): string => match ($state) { ->color(fn(string $state): string => match ($state) {
'pending' => 'warning', 'pending' => 'warning',

View File

@@ -29,9 +29,9 @@ class ProductsTable
TextColumn::make('description') TextColumn::make('description')
->limit(50) ->limit(50)
->toggleable(isToggledHiddenByDefault: true), ->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('customers_count') TextColumn::make('contracts_count')
->counts('customers') ->counts('contracts')
->label(__('app.owners')), ->label(__('app.contracts')),
TextColumn::make('created_at') TextColumn::make('created_at')
->dateTime() ->dateTime()
->sortable() ->sortable()

View File

@@ -45,7 +45,7 @@ class ResolvedTicketsWidget extends BaseWidget
->label(__('app.widget_customer')) ->label(__('app.widget_customer'))
->searchable(), ->searchable(),
TextColumn::make('customerProduct.product.name') TextColumn::make('contract.product.name')
->label(__('app.product')) ->label(__('app.product'))
->placeholder(__('app.general')), ->placeholder(__('app.general')),

View File

@@ -7,9 +7,30 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['product_id', 'customer_id', 'type', 'start_date', 'end_date', 'status', 'printed_at', 'signed_status'])] #[Fillable(['product_id', 'customer_id', 'type', 'category', 'start_date', 'end_date', 'status', 'printed_at', 'signed_status', 'representative_name', 'representative_phone', 'representative_email'])]
class Contract extends Model class Contract extends Model
{ {
protected static function booted(): void
{
static::saving(function (self $contract) {
if ($contract->status === 'active') {
$exists = self::where('product_id', $contract->product_id)
->where('category', $contract->category)
->where('status', 'active')
->when($contract->exists, fn ($q) => $q->where('id', '!=', $contract->id))
->exists();
if ($exists) {
throw new \RuntimeException(
__('feedback.contract_duplicate_body', [
'product' => $contract->product?->name ?? $contract->product_id,
'customer' => $contract->customer?->name ?? '?',
])
);
}
}
});
}
protected function casts(): array protected function casts(): array
{ {
return [ return [

View File

@@ -6,14 +6,19 @@ use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
#[Fillable(['name', 'email', 'phone', 'address', 'status'])] #[Fillable(['name', 'email', 'phone', 'address', 'status'])]
class Customer extends Model class Customer extends Model
{ {
public function products(): BelongsToMany /**
* Các căn hộ khách hàng sở hữu (qua Ownership active)
*/
public function ownedProducts(): BelongsToMany
{ {
return $this->belongsToMany(Product::class, 'customer_product') return $this->belongsToMany(Product::class, 'contracts')
->withPivot('purchase_date') ->wherePivot('category', 'ownership')
->wherePivot('status', 'active')
->withTimestamps(); ->withTimestamps();
} }

View File

@@ -1,40 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class CustomerProduct extends Model
{
protected $table = 'customer_product';
protected $fillable = [
'customer_id',
'product_id',
'purchase_date',
];
protected function casts(): array
{
return [
'purchase_date' => 'date',
];
}
public function customer(): BelongsTo
{
return $this->belongsTo(Customer::class);
}
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
public function feedbacks(): HasMany
{
return $this->hasMany(Feedback::class);
}
}

View File

@@ -8,7 +8,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['customer_id', 'customer_product_id', 'contract_id', 'feedback_channel_id', 'assigned_to', 'title', 'content', 'status', 'current_department_id', 'is_escalated'])] #[Fillable(['customer_id', 'contract_id', 'feedback_channel_id', 'assigned_to', 'title', 'content', 'status', 'current_department_id', 'is_escalated'])]
class Feedback extends Model class Feedback extends Model
{ {
public function customer(): BelongsTo public function customer(): BelongsTo
@@ -16,11 +16,6 @@ class Feedback extends Model
return $this->belongsTo(Customer::class); return $this->belongsTo(Customer::class);
} }
public function customerProduct(): BelongsTo
{
return $this->belongsTo(CustomerProduct::class, 'customer_product_id');
}
public function contract(): BelongsTo public function contract(): BelongsTo
{ {
return $this->belongsTo(Contract::class); return $this->belongsTo(Contract::class);

View File

@@ -4,19 +4,11 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['name', 'description', 'status'])] #[Fillable(['name', 'description', 'status'])]
class Product extends Model class Product extends Model
{ {
public function customers(): BelongsToMany
{
return $this->belongsToMany(Customer::class, 'customer_product')
->withPivot('purchase_date')
->withTimestamps();
}
public function contracts(): HasMany public function contracts(): HasMany
{ {
return $this->hasMany(Contract::class); return $this->hasMany(Contract::class);

View File

@@ -0,0 +1,89 @@
<?php
namespace App\Providers\Filament;
use App\Filament\Resources\ActivityLogs\ActivityLogResource;
use App\Filament\Resources\Customers\CustomerResource;
use App\Filament\Resources\Feedback\FeedbackResource;
use App\Filament\Resources\FeedbackChannels\FeedbackChannelResource;
use App\Filament\Resources\FeedbackTags\FeedbackTagResource;
use App\Filament\Resources\Products\ProductResource;
use App\Filament\Widgets\AvgProcessingTimeWidget;
use App\Filament\Widgets\HandlerPerformanceWidget;
use App\Filament\Widgets\ResolvedTicketsWidget;
use Filament\Http\Middleware\Authenticate;
use Filament\Http\Middleware\AuthenticateSession;
use Filament\Http\Middleware\DisableBladeIconComponents;
use Filament\Http\Middleware\DispatchServingFilamentEvent;
use Filament\Pages\Dashboard;
use Filament\Panel;
use Filament\PanelProvider;
use Filament\View\PanelsRenderHook;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\PreventRequestForgery;
use Illuminate\Routing\Middleware\SubstituteBindings;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\View\Middleware\ShareErrorsFromSession;
class SupportPanelProvider extends PanelProvider
{
public function panel(Panel $panel): Panel
{
return $panel
->id('support')
->path('support')
->login()
->brandName('AfterSales CRM — Support')
->sidebarCollapsibleOnDesktop()
->colors([
'primary' => '#1a56db',
'secondary' => '#64748b',
'gray' => '#64748b',
'success' => '#059669',
'warning' => '#d97706',
'danger' => '#dc2626',
'info' => '#2563eb',
])
->font('Inter')
->favicon(asset('favicon.svg'))
->resources([
FeedbackResource::class,
CustomerResource::class,
ProductResource::class,
FeedbackChannelResource::class,
FeedbackTagResource::class,
ActivityLogResource::class,
])
->pages([
Dashboard::class,
])
->widgets([
ResolvedTicketsWidget::class,
AvgProcessingTimeWidget::class,
HandlerPerformanceWidget::class,
])
->middleware([
EncryptCookies::class,
AddQueuedCookiesToResponse::class,
StartSession::class,
AuthenticateSession::class,
ShareErrorsFromSession::class,
PreventRequestForgery::class,
SubstituteBindings::class,
DisableBladeIconComponents::class,
DispatchServingFilamentEvent::class,
])
->authMiddleware([
Authenticate::class,
])
->renderHook(
PanelsRenderHook::HEAD_END,
fn (): string => '<link rel="stylesheet" href="' . asset('css/filament-custom.css') . '">',
)
->renderHook(
PanelsRenderHook::BODY_END,
fn (): string => '<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@500;600;700;800&family=Material+Symbols+Outlined:wght,FILL@100..700,0..1&display=swap" rel="stylesheet">',
);
}
}

View File

@@ -3,4 +3,5 @@
return [ return [
App\Providers\AppServiceProvider::class, App\Providers\AppServiceProvider::class,
App\Providers\Filament\AdminPanelProvider::class, App\Providers\Filament\AdminPanelProvider::class,
App\Providers\Filament\SupportPanelProvider::class,
]; ];

View File

@@ -0,0 +1,69 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
// 1. Add category + representative fields to contracts
Schema::table('contracts', function (Blueprint $table) {
$table->string('category')->after('type')->default('ownership');
$table->string('representative_name')->nullable()->after('signed_status');
$table->string('representative_phone')->nullable()->after('representative_name');
$table->string('representative_email')->nullable()->after('representative_phone');
});
// 2. Drop customer_product_id FK and column from feedback
if (DB::getDriverName() === 'sqlite') {
// SQLite doesn't support dropping foreign keys cleanly, recreate table approach
Schema::table('feedback', function (Blueprint $table) {
// Drop the column directly (SQLite will handle)
});
}
try {
Schema::table('feedback', function (Blueprint $table) {
$table->dropForeign(['customer_product_id']);
});
} catch (\Throwable) {
// FK may not exist or already dropped
}
Schema::table('feedback', function (Blueprint $table) {
if (Schema::hasColumn('feedback', 'customer_product_id')) {
$table->dropColumn('customer_product_id');
}
});
// 3. Drop customer_product pivot table
Schema::dropIfExists('customer_product');
}
public function down(): void
{
// Restore customer_product table
Schema::create('customer_product', function (Blueprint $table) {
$table->id();
$table->foreignId('customer_id')->constrained('customers')->cascadeOnDelete();
$table->foreignId('product_id')->constrained('products')->cascadeOnDelete();
$table->date('purchase_date')->nullable();
$table->timestamps();
$table->unique(['customer_id', 'product_id']);
});
// Restore customer_product_id on feedback
Schema::table('feedback', function (Blueprint $table) {
$table->foreignId('customer_product_id')->nullable()->after('customer_id');
$table->foreign('customer_product_id')->references('id')->on('customer_product')->nullOnDelete();
});
// Remove V2 columns from contracts
Schema::table('contracts', function (Blueprint $table) {
$table->dropColumn(['category', 'representative_name', 'representative_phone', 'representative_email']);
});
}
};

View File

@@ -2,13 +2,13 @@
namespace Database\Seeders; namespace Database\Seeders;
use App\Enums\ContractCategory;
use App\Enums\ContractStatus; use App\Enums\ContractStatus;
use App\Enums\ContractType; use App\Enums\ContractType;
use App\Enums\HandoverStatus; use App\Enums\HandoverStatus;
use App\Enums\ServiceType; use App\Enums\ServiceType;
use App\Models\Contract; use App\Models\Contract;
use App\Models\Customer; use App\Models\Customer;
use App\Models\CustomerProduct;
use App\Models\Department; use App\Models\Department;
use App\Models\Feedback; use App\Models\Feedback;
use App\Models\FeedbackAttachment; use App\Models\FeedbackAttachment;
@@ -119,65 +119,62 @@ class AfterSalesSeeder extends Seeder
$c6 = Customer::create(['name' => 'Đỗ Văn Phúc', 'email' => 'dovanphuc@gmail.com', 'phone' => '0954678901', 'address' => 'Thủ Đức, TP.HCM', 'status' => 'inactive']); $c6 = Customer::create(['name' => 'Đỗ Văn Phúc', 'email' => 'dovanphuc@gmail.com', 'phone' => '0954678901', 'address' => 'Thủ Đức, TP.HCM', 'status' => 'inactive']);
// ============================================================ // ============================================================
// 7. CUSTOMER-PRODUCT pivots // 7. CONTRACTS (V2: category + representative)
// ============================================================
$c1->products()->attach($p1->id, ['purchase_date' => '2024-01-15']);
$c1->products()->attach($p2->id, ['purchase_date' => '2024-06-01']);
$c2->products()->attach($p1->id, ['purchase_date' => '2024-03-20']);
$c3->products()->attach($p3->id, ['purchase_date' => '2024-09-10']);
$c4->products()->attach($p2->id, ['purchase_date' => '2025-01-05']);
$c4->products()->attach($p5->id, ['purchase_date' => '2025-02-15']);
$c5->products()->attach($p5->id, ['purchase_date' => '2024-11-01']);
$c6->products()->attach($p6->id, ['purchase_date' => '2023-06-15']);
// ============================================================
// 8. CONTRACTS (6 contracts)
// ============================================================ // ============================================================
$contract1 = Contract::create([ $contract1 = Contract::create([
'product_id' => $p1->id, 'customer_id' => $c1->id, 'product_id' => $p1->id, 'customer_id' => $c1->id,
'type' => ContractType::SALE->value, 'category' => ContractCategory::OWNERSHIP->value,
'type' => ContractType::PURCHASE->value,
'start_date' => '2024-01-15', 'end_date' => null, 'start_date' => '2024-01-15', 'end_date' => null,
'status' => ContractStatus::ACTIVE->value, 'status' => ContractStatus::ACTIVE->value,
'signed_status' => 'Đã ký', 'signed_status' => 'Đã ký',
'representative_name' => 'Nguyễn Thị Hoa',
'representative_phone' => '0901000111',
'representative_email' => 'hoant@example.com',
]); ]);
$contract2 = Contract::create([ $contract2 = Contract::create([
'product_id' => $p2->id, 'customer_id' => $c1->id, 'product_id' => $p2->id, 'customer_id' => $c1->id,
'type' => ContractType::LEASE->value, 'category' => ContractCategory::BUSINESS->value,
'type' => ContractType::RENTAL->value,
'start_date' => '2024-06-01', 'end_date' => '2026-06-01', 'start_date' => '2024-06-01', 'end_date' => '2026-06-01',
'status' => ContractStatus::ACTIVE->value, 'status' => ContractStatus::ACTIVE->value,
'signed_status' => 'Đã ký', 'signed_status' => 'Đã ký',
]); ]);
$contract3 = Contract::create([ $contract3 = Contract::create([
'product_id' => $p1->id, 'customer_id' => $c2->id, 'product_id' => $p2->id, 'customer_id' => $c4->id,
'type' => ContractType::SALE->value, 'category' => ContractCategory::BUSINESS->value,
'start_date' => '2024-03-20', 'end_date' => null, 'type' => ContractType::RENTAL->value,
'status' => ContractStatus::ACTIVE->value, 'start_date' => '2025-01-05', 'end_date' => '2026-01-05',
'status' => ContractStatus::EXPIRED->value,
'signed_status' => 'Đã ký', 'signed_status' => 'Đã ký',
]); ]);
$contract4 = Contract::create([ $contract4 = Contract::create([
'product_id' => $p3->id, 'customer_id' => $c3->id, 'product_id' => $p3->id, 'customer_id' => $c3->id,
'category' => ContractCategory::BUSINESS->value,
'type' => ContractType::BCC->value, 'type' => ContractType::BCC->value,
'start_date' => '2024-09-10', 'end_date' => '2029-09-10', 'start_date' => '2024-09-10', 'end_date' => '2029-09-10',
'status' => ContractStatus::ACTIVE->value, 'status' => ContractStatus::ACTIVE->value,
'signed_status' => 'Đang chờ ký', 'signed_status' => 'Đang chờ ký',
]); ]);
$contract5 = Contract::create([ $contract5 = Contract::create([
'product_id' => $p2->id, 'customer_id' => $c4->id,
'type' => ContractType::LEASE->value,
'start_date' => '2025-01-05', 'end_date' => '2026-01-05',
'status' => ContractStatus::EXPIRED->value,
'signed_status' => 'Đã ký',
]);
$contract6 = Contract::create([
'product_id' => $p5->id, 'customer_id' => $c5->id, 'product_id' => $p5->id, 'customer_id' => $c5->id,
'type' => ContractType::SALE->value, 'category' => ContractCategory::OWNERSHIP->value,
'type' => ContractType::PURCHASE->value,
'start_date' => '2024-11-01', 'end_date' => null, 'start_date' => '2024-11-01', 'end_date' => null,
'status' => ContractStatus::ACTIVE->value, 'status' => ContractStatus::ACTIVE->value,
'signed_status' => 'Đã ký', 'signed_status' => 'Đã ký',
]); ]);
$contract6 = Contract::create([
'product_id' => $p1->id, 'customer_id' => $c2->id,
'category' => ContractCategory::OWNERSHIP->value,
'type' => ContractType::PURCHASE->value,
'start_date' => '2024-03-20', 'end_date' => '2024-12-31',
'status' => ContractStatus::LIQUIDATED->value,
'signed_status' => 'Đã ký',
]);
// ============================================================ // ============================================================
// 9. HANDOVERS (6 handovers) // 8. HANDOVERS (6 handovers)
// ============================================================ // ============================================================
Handover::create(['product_id' => $p1->id, 'customer_id' => $c1->id, 'handover_date' => '2024-02-15', 'status' => HandoverStatus::HANDED_OVER->value, 'remark' => 'Đã bàn giao đầy đủ chìa khóa, thẻ từ và sổ bảo hành.']); Handover::create(['product_id' => $p1->id, 'customer_id' => $c1->id, 'handover_date' => '2024-02-15', 'status' => HandoverStatus::HANDED_OVER->value, 'remark' => 'Đã bàn giao đầy đủ chìa khóa, thẻ từ và sổ bảo hành.']);
Handover::create(['product_id' => $p1->id, 'customer_id' => $c2->id, 'handover_date' => '2024-04-20', 'status' => HandoverStatus::HANDED_OVER->value, 'remark' => 'Đã bàn giao, khách yêu cầu kiểm tra lại hệ thống nước nóng.']); Handover::create(['product_id' => $p1->id, 'customer_id' => $c2->id, 'handover_date' => '2024-04-20', 'status' => HandoverStatus::HANDED_OVER->value, 'remark' => 'Đã bàn giao, khách yêu cầu kiểm tra lại hệ thống nước nóng.']);
@@ -187,7 +184,7 @@ class AfterSalesSeeder extends Seeder
Handover::create(['product_id' => $p5->id, 'customer_id' => $c5->id, 'handover_date' => '2025-01-15', 'status' => HandoverStatus::HANDED_OVER->value, 'remark' => 'Bàn giao thành công, khách hài lòng với chất lượng.']); Handover::create(['product_id' => $p5->id, 'customer_id' => $c5->id, 'handover_date' => '2025-01-15', 'status' => HandoverStatus::HANDED_OVER->value, 'remark' => 'Bàn giao thành công, khách hài lòng với chất lượng.']);
// ============================================================ // ============================================================
// 10. PRODUCT SERVICES (6 services) // 9. PRODUCT SERVICES (6 services)
// ============================================================ // ============================================================
ProductService::create(['product_id' => $p1->id, 'service_type' => ServiceType::MANAGEMENT_FEE->value, 'status' => 'active', 'actual_collection_date' => '2024-03-01', 'remark' => 'Phí quản lý hàng tháng 5.000.000 VND/căn.']); ProductService::create(['product_id' => $p1->id, 'service_type' => ServiceType::MANAGEMENT_FEE->value, 'status' => 'active', 'actual_collection_date' => '2024-03-01', 'remark' => 'Phí quản lý hàng tháng 5.000.000 VND/căn.']);
ProductService::create(['product_id' => $p1->id, 'service_type' => ServiceType::GRATITUDE->value, 'status' => 'completed', 'actual_collection_date' => '2024-06-15', 'remark' => 'Quà tri ân khách hàng nhân dịp khai trương tiện ích mới.']); ProductService::create(['product_id' => $p1->id, 'service_type' => ServiceType::GRATITUDE->value, 'status' => 'completed', 'actual_collection_date' => '2024-06-15', 'remark' => 'Quà tri ân khách hàng nhân dịp khai trương tiện ích mới.']);
@@ -197,7 +194,7 @@ class AfterSalesSeeder extends Seeder
ProductService::create(['product_id' => $p5->id, 'service_type' => ServiceType::MANAGEMENT_FEE->value, 'status' => 'active', 'actual_collection_date' => '2025-02-01', 'remark' => 'Phí quản lý hàng tháng 3.500.000 VND/căn.']); ProductService::create(['product_id' => $p5->id, 'service_type' => ServiceType::MANAGEMENT_FEE->value, 'status' => 'active', 'actual_collection_date' => '2025-02-01', 'remark' => 'Phí quản lý hàng tháng 3.500.000 VND/căn.']);
// ============================================================ // ============================================================
// 11. FEEDBACK TAGS (6 tags) // 10. FEEDBACK TAGS (6 tags)
// ============================================================ // ============================================================
$tagLeaking = FeedbackTag::create(['name' => 'Rò rỉ', 'slug' => 'leaking', 'color' => '#3b82f6']); $tagLeaking = FeedbackTag::create(['name' => 'Rò rỉ', 'slug' => 'leaking', 'color' => '#3b82f6']);
$tagElectrical = FeedbackTag::create(['name' => 'Điện nước', 'slug' => 'electrical', 'color' => '#f59e0b']); $tagElectrical = FeedbackTag::create(['name' => 'Điện nước', 'slug' => 'electrical', 'color' => '#f59e0b']);
@@ -207,13 +204,12 @@ class AfterSalesSeeder extends Seeder
$tagSuggestion = FeedbackTag::create(['name' => 'Đề xuất', 'slug' => 'suggestion', 'color' => '#06b6d4']); $tagSuggestion = FeedbackTag::create(['name' => 'Đề xuất', 'slug' => 'suggestion', 'color' => '#06b6d4']);
// ============================================================ // ============================================================
// 12. FEEDBACKS (8 feedbacks - various statuses) // 11. FEEDBACKS (8 feedbacks - V2: no customer_product_id, use contract_id)
// ============================================================ // ============================================================
// Feedback 1: Pending - Trần rò rỉ // Feedback 1: Pending - Trần rò rỉ
$cp1 = CustomerProduct::where('customer_id', $c1->id)->where('product_id', $p1->id)->first();
$fb1 = Feedback::create([ $fb1 = Feedback::create([
'customer_id' => $c1->id, 'customer_product_id' => $cp1->id, 'contract_id' => $contract1->id, 'customer_id' => $c1->id, 'contract_id' => $contract1->id,
'feedback_channel_id' => $chEmail->id, 'assigned_to' => $staffA->id, 'feedback_channel_id' => $chEmail->id, 'assigned_to' => $staffA->id,
'current_department_id' => $deptCskh->id, 'current_department_id' => $deptCskh->id,
'title' => 'Trần nhà bị rò rỉ nước mưa', 'title' => 'Trần nhà bị rò rỉ nước mưa',
@@ -222,9 +218,8 @@ class AfterSalesSeeder extends Seeder
]); ]);
// Feedback 2: Processing - Nâng cấp chỗ đậu xe // Feedback 2: Processing - Nâng cấp chỗ đậu xe
$cp2 = CustomerProduct::where('customer_id', $c1->id)->where('product_id', $p2->id)->first();
$fb2 = Feedback::create([ $fb2 = Feedback::create([
'customer_id' => $c1->id, 'customer_product_id' => $cp2->id, 'contract_id' => $contract2->id, 'customer_id' => $c1->id, 'contract_id' => $contract2->id,
'feedback_channel_id' => $chPhone->id, 'assigned_to' => $managerCskh->id, 'feedback_channel_id' => $chPhone->id, 'assigned_to' => $managerCskh->id,
'current_department_id' => $deptCskh->id, 'current_department_id' => $deptCskh->id,
'title' => 'Yêu cầu nâng cấp chỗ đậu xe', 'title' => 'Yêu cầu nâng cấp chỗ đậu xe',
@@ -233,9 +228,8 @@ class AfterSalesSeeder extends Seeder
]); ]);
// Feedback 3: Resolved - Điều hòa hỏng // Feedback 3: Resolved - Điều hòa hỏng
$cp3 = CustomerProduct::where('customer_id', $c2->id)->where('product_id', $p1->id)->first();
$fb3 = Feedback::create([ $fb3 = Feedback::create([
'customer_id' => $c2->id, 'customer_product_id' => $cp3->id, 'contract_id' => $contract3->id, 'customer_id' => $c2->id, 'contract_id' => $contract6->id,
'feedback_channel_id' => $chZalo->id, 'assigned_to' => $staffA->id, 'feedback_channel_id' => $chZalo->id, 'assigned_to' => $staffA->id,
'current_department_id' => $deptKt->id, 'is_escalated' => false, 'current_department_id' => $deptKt->id, 'is_escalated' => false,
'title' => 'Điều hòa phòng ngủ chính không mát', 'title' => 'Điều hòa phòng ngủ chính không mát',
@@ -243,9 +237,9 @@ class AfterSalesSeeder extends Seeder
'status' => 'resolved', 'status' => 'resolved',
]); ]);
// Feedback 4: Pending - Góp ý cải thiện dịch vụ // Feedback 4: Pending - Góp ý cải thiện dịch vụ (general)
$fb4 = Feedback::create([ $fb4 = Feedback::create([
'customer_id' => $c3->id, 'customer_product_id' => null, 'contract_id' => null, 'customer_id' => $c3->id, 'contract_id' => null,
'feedback_channel_id' => $chApp->id, 'assigned_to' => null, 'feedback_channel_id' => $chApp->id, 'assigned_to' => null,
'current_department_id' => $deptCskh->id, 'current_department_id' => $deptCskh->id,
'title' => 'Đề xuất cải thiện dịch vụ vệ sinh', 'title' => 'Đề xuất cải thiện dịch vụ vệ sinh',
@@ -253,10 +247,9 @@ class AfterSalesSeeder extends Seeder
'status' => 'pending', 'status' => 'pending',
]); ]);
// Feedback 5: Closed - Bản lề tủ bếp // Feedback 5: Closed - Bản lề tủ bếp (vẫn ref contract đã expired)
$cp5 = CustomerProduct::where('customer_id', $c4->id)->where('product_id', $p2->id)->first();
$fb5 = Feedback::create([ $fb5 = Feedback::create([
'customer_id' => $c4->id, 'customer_product_id' => $cp5->id, 'contract_id' => $contract5->id, 'customer_id' => $c4->id, 'contract_id' => $contract3->id,
'feedback_channel_id' => $chEmail->id, 'assigned_to' => $staffB->id, 'feedback_channel_id' => $chEmail->id, 'assigned_to' => $staffB->id,
'current_department_id' => $deptKt->id, 'current_department_id' => $deptKt->id,
'title' => 'Bản lề tủ bếp bị gãy', 'title' => 'Bản lề tủ bếp bị gãy',
@@ -265,19 +258,18 @@ class AfterSalesSeeder extends Seeder
]); ]);
// Feedback 6: Processing - Ổ cắm điện hư // Feedback 6: Processing - Ổ cắm điện hư
$cp6 = CustomerProduct::where('customer_id', $c5->id)->where('product_id', $p5->id)->first();
$fb6 = Feedback::create([ $fb6 = Feedback::create([
'customer_id' => $c5->id, 'customer_product_id' => $cp6->id, 'contract_id' => $contract6->id, 'customer_id' => $c5->id, 'contract_id' => $contract5->id,
'feedback_channel_id' => $chPhone->id, 'assigned_to' => $staffA->id, 'feedback_channel_id' => $chPhone->id, 'assigned_to' => $staffA->id,
'current_department_id' => $deptKt->id, 'is_escalated' => true, 'current_department_id' => $deptKt->id, 'is_escalated' => true,
'title' => 'Ổ c插座 điện phòng bếp bị hư, có mùi khét', 'title' => 'Ổ cắm điện phòng bếp bị hư, có mùi khét',
'content' => 'Ổ cắm điện cạnh bồn rửa chén bị hư, phát ra mùi khét khi cắm thiết bị. Đây là vấn đề an toàn, cần xử lý gấp.', 'content' => 'Ổ cắm điện cạnh bồn rửa chén bị hư, phát ra mùi khét khi cắm thiết bị. Đây là vấn đề an toàn, cần xử lý gấp.',
'status' => 'processing', 'status' => 'processing',
]); ]);
// Feedback 7: Resolved - Hợp đồng thuê // Feedback 7: Resolved - Hợp đồng thuê
$fb7 = Feedback::create([ $fb7 = Feedback::create([
'customer_id' => $c4->id, 'customer_product_id' => null, 'contract_id' => $contract5->id, 'customer_id' => $c4->id, 'contract_id' => $contract3->id,
'feedback_channel_id' => $chWalkin->id, 'assigned_to' => $staffB->id, 'feedback_channel_id' => $chWalkin->id, 'assigned_to' => $staffB->id,
'current_department_id' => $deptPhaply->id, 'current_department_id' => $deptPhaply->id,
'title' => 'Hỏi về gia hạn hợp đồng thuê', 'title' => 'Hỏi về gia hạn hợp đồng thuê',
@@ -285,9 +277,9 @@ class AfterSalesSeeder extends Seeder
'status' => 'resolved', 'status' => 'resolved',
]); ]);
// Feedback 8: Pending - Phàn nàn về tiếng ồn // Feedback 8: Pending - Phàn nàn tiếng ồn
$fb8 = Feedback::create([ $fb8 = Feedback::create([
'customer_id' => $c2->id, 'customer_product_id' => $cp3->id, 'contract_id' => $contract3->id, 'customer_id' => $c2->id, 'contract_id' => $contract6->id,
'feedback_channel_id' => $chZalo->id, 'assigned_to' => $staffB->id, 'feedback_channel_id' => $chZalo->id, 'assigned_to' => $staffB->id,
'current_department_id' => $deptCskh->id, 'current_department_id' => $deptCskh->id,
'title' => 'Phàn nàn về tiếng ồn từ tầng trên', 'title' => 'Phàn nàn về tiếng ồn từ tầng trên',
@@ -296,7 +288,7 @@ class AfterSalesSeeder extends Seeder
]); ]);
// ============================================================ // ============================================================
// 13. TAG ATTACHMENTS // 12. TAG ATTACHMENTS
// ============================================================ // ============================================================
$fb1->tags()->attach([$tagLeaking->id, $tagMaintenance->id]); $fb1->tags()->attach([$tagLeaking->id, $tagMaintenance->id]);
$fb2->tags()->attach([$tagSuggestion->id]); $fb2->tags()->attach([$tagSuggestion->id]);
@@ -308,10 +300,8 @@ class AfterSalesSeeder extends Seeder
$fb8->tags()->attach([$tagComplaint->id]); $fb8->tags()->attach([$tagComplaint->id]);
// ============================================================ // ============================================================
// 14. FEEDBACK INTERACTIONS (12 interactions) // 13. FEEDBACK INTERACTIONS
// ============================================================ // ============================================================
// FB1: Tạo mới + ghi chú
FeedbackInteraction::create([ FeedbackInteraction::create([
'feedback_id' => $fb1->id, 'user_id' => $admin->id, 'type' => 'note', 'feedback_id' => $fb1->id, 'user_id' => $admin->id, 'type' => 'note',
'content' => 'Tiếp nhận phản ánh qua Email. Giao cho nhân viên Phạm Thị xử lý.', 'content' => 'Tiếp nhận phản ánh qua Email. Giao cho nhân viên Phạm Thị xử lý.',
@@ -321,28 +311,20 @@ class AfterSalesSeeder extends Seeder
'feedback_id' => $fb1->id, 'user_id' => $staffA->id, 'type' => 'note', 'feedback_id' => $fb1->id, 'user_id' => $staffA->id, 'type' => 'note',
'content' => 'Đã liên hệ khách hàng qua điện thoại. Lên lịch kiểm tra vào thứ Ba tuần sau.', 'content' => 'Đã liên hệ khách hàng qua điện thoại. Lên lịch kiểm tra vào thứ Ba tuần sau.',
]); ]);
// FB2: Phân công
FeedbackInteraction::create([ FeedbackInteraction::create([
'feedback_id' => $fb2->id, 'user_id' => $managerCskh->id, 'type' => 'note', 'feedback_id' => $fb2->id, 'user_id' => $managerCskh->id, 'type' => 'note',
'content' => 'Đã gửi báo giá nâng cấp chỗ đậu xe qua email. Chờ khách xác nhận.', 'content' => 'Đã gửi báo giá nâng cấp chỗ đậu xe qua email. Chờ khách xác nhận.',
]); ]);
// FB3: Xử lý xong
FeedbackInteraction::create([ FeedbackInteraction::create([
'feedback_id' => $fb3->id, 'user_id' => $staffA->id, 'type' => 'status_change', 'feedback_id' => $fb3->id, 'user_id' => $staffA->id, 'type' => 'status_change',
'content' => 'Kỹ thuật viên đã kiểm tra và thay thế block điều hòa ngày 10/06. Khách hàng xác nhận hoạt động bình thường.', 'content' => 'Kỹ thuật viên đã kiểm tra và thay thế block điều hòa ngày 10/06. Khách hàng xác nhận hoạt động bình thường.',
'changes' => ['status' => ['old' => 'processing', 'new' => 'resolved']], 'changes' => ['status' => ['old' => 'processing', 'new' => 'resolved']],
]); ]);
// FB5: Đóng phiếu
FeedbackInteraction::create([ FeedbackInteraction::create([
'feedback_id' => $fb5->id, 'user_id' => $staffB->id, 'type' => 'status_change', 'feedback_id' => $fb5->id, 'user_id' => $staffB->id, 'type' => 'status_change',
'content' => 'Đã thay thế bản lề mới ngày 01/03. Tất cả tủ bếp hoạt động bình thường.', 'content' => 'Đã thay thế bản lề mới ngày 01/03. Tất cả tủ bếp hoạt động bình thường.',
'changes' => ['status' => ['old' => 'processing', 'new' => 'closed']], 'changes' => ['status' => ['old' => 'processing', 'new' => 'closed']],
]); ]);
// FB6: Đang xử lý + ghi chú khẩn cấp
FeedbackInteraction::create([ FeedbackInteraction::create([
'feedback_id' => $fb6->id, 'user_id' => $staffA->id, 'type' => 'note', 'feedback_id' => $fb6->id, 'user_id' => $staffA->id, 'type' => 'note',
'content' => 'Đã cử kỹ thuật viên khẩn cấp đến kiểm tra. Yêu cầu khách không sử dụng ổ cắm cho đến khi sửa xong.', 'content' => 'Đã cử kỹ thuật viên khẩn cấp đến kiểm tra. Yêu cầu khách không sử dụng ổ cắm cho đến khi sửa xong.',
@@ -352,8 +334,6 @@ class AfterSalesSeeder extends Seeder
'content' => 'Kỹ thuật viên đã kiểm tra, phát hiện dây điện bị hở. Đang chờ vật tư thay thế.', 'content' => 'Kỹ thuật viên đã kiểm tra, phát hiện dây điện bị hở. Đang chờ vật tư thay thế.',
'changes' => ['status' => ['old' => 'pending', 'new' => 'processing']], 'changes' => ['status' => ['old' => 'pending', 'new' => 'processing']],
]); ]);
// FB7: Phân công + chuyển phòng ban
FeedbackInteraction::create([ FeedbackInteraction::create([
'feedback_id' => $fb7->id, 'user_id' => $managerCskh->id, 'type' => 'assignment', 'feedback_id' => $fb7->id, 'user_id' => $managerCskh->id, 'type' => 'assignment',
'content' => 'Chuyển yêu cầu gia hạn hợp đồng sang Phòng Pháp lý.', 'content' => 'Chuyển yêu cầu gia hạn hợp đồng sang Phòng Pháp lý.',
@@ -364,15 +344,13 @@ class AfterSalesSeeder extends Seeder
'content' => 'Đã soạn thảo phụ lục hợp đồng gia hạn. Đang chờ khách hàng ký.', 'content' => 'Đã soạn thảo phụ lục hợp đồng gia hạn. Đang chờ khách hàng ký.',
'changes' => ['status' => ['old' => 'processing', 'new' => 'resolved']], 'changes' => ['status' => ['old' => 'processing', 'new' => 'resolved']],
]); ]);
// FB8: Ghi chú
FeedbackInteraction::create([ FeedbackInteraction::create([
'feedback_id' => $fb8->id, 'user_id' => $staffB->id, 'type' => 'note', 'feedback_id' => $fb8->id, 'user_id' => $staffB->id, 'type' => 'note',
'content' => 'Đã liên hệ ban quản lý tòa nhà để xác minh thông tin. BQL cho biết sẽ nhắc nhở cư dân tầng trên.', 'content' => 'Đã liên hệ ban quản lý tòa nhà để xác minh thông tin. BQL cho biết sẽ nhắc nhở cư dân tầng trên.',
]); ]);
// ============================================================ // ============================================================
// 15. TICKET TRANSFER LOGS (2 transfers) // 14. TICKET TRANSFER LOGS
// ============================================================ // ============================================================
TicketTransferLog::create([ TicketTransferLog::create([
'feedback_id' => $fb3->id, 'feedback_id' => $fb3->id,
@@ -390,17 +368,15 @@ class AfterSalesSeeder extends Seeder
]); ]);
// ============================================================ // ============================================================
// 16. FEEDBACK ATTACHMENTS (6 attachments - public disk) // 15. FEEDBACK ATTACHMENTS
// ============================================================ // ============================================================
$disk = Storage::disk('public'); $disk = Storage::disk('public');
// Tạo file mẫu trên public disk
$disk->put('feedback-attachments/bao-cao-kiem-tra-dieu-hoa.pdf', '%PDF-1.4 Mẫu báo cáo kiểm tra điều hòa - Demo'); $disk->put('feedback-attachments/bao-cao-kiem-tra-dieu-hoa.pdf', '%PDF-1.4 Mẫu báo cáo kiểm tra điều hòa - Demo');
$disk->put('feedback-attachments/anh-tran-ro-ri.jpg', str_repeat('x', 1000)); // dummy image $disk->put('feedback-attachments/anh-tran-ro-ri.jpg', str_repeat('x', 1000));
$disk->put('feedback-attachments/anh-ban-le-hong.png', str_repeat('y', 1200)); // dummy image $disk->put('feedback-attachments/anh-ban-le-hong.png', str_repeat('y', 1200));
$disk->put('feedback-attachments/bao-gia-nang-cap.pdf', '%PDF-1.4 Báo giá nâng cấp chỗ đậu xe - Demo'); $disk->put('feedback-attachments/bao-gia-nang-cap.pdf', '%PDF-1.4 Báo giá nâng cấp chỗ đậu xe - Demo');
$disk->put('feedback-attachments/phu-luc-hop-dong.pdf', '%PDF-1.4 Phụ lục hợp đồng gia hạn - Demo'); $disk->put('feedback-attachments/phu-luc-hop-dong.pdf', '%PDF-1.4 Phụ lục hợp đồng gia hạn - Demo');
$disk->put('feedback-attachments/anh-o-cam-hu.jpg', str_repeat('z', 800)); // dummy image $disk->put('feedback-attachments/anh-o-cam-hu.jpg', str_repeat('z', 800));
FeedbackAttachment::create([ FeedbackAttachment::create([
'uuid' => (string) Str::uuid(), 'uuid' => (string) Str::uuid(),

View File

@@ -88,7 +88,11 @@ return [
'end_date' => 'End Date', 'end_date' => 'End Date',
'printed_at' => 'Print Date', 'printed_at' => 'Print Date',
'signed_status' => 'Signed Status', 'signed_status' => 'Signed Status',
'contract_category_section' => 'Contract Classification',
'contract_info' => 'Contract Information', 'contract_info' => 'Contract Information',
'representative_info' => 'Representative Information',
'representative_desc' => 'Person representing the owner (if any)',
'representative' => 'Representative',
'feedback_history' => 'Feedback History', 'feedback_history' => 'Feedback History',
'service_type' => 'Service Type', 'service_type' => 'Service Type',
'tab_all' => 'All', 'tab_all' => 'All',

View File

@@ -32,11 +32,21 @@ return [
'liquidated' => 'Liquidated', 'liquidated' => 'Liquidated',
], ],
// Contract Type // Contract Category
'contract_category' => [
'ownership' => 'Ownership',
'business' => 'Business',
],
'contract_category_label' => 'Contract Category',
// Contract Type (V2)
'contract_type' => [ 'contract_type' => [
'sale' => 'Sale contract', 'deposit' => 'Deposit',
'lease' => 'Lease contract', 'purchase' => 'Purchase',
'bcc' => 'Business cooperation contract (BCC)', 'transfer' => 'Transfer',
'rental' => 'Rental',
'self_business' => 'Self Business',
'bcc' => 'Business Cooperation (BCC)',
], ],
// Labels for Select filters // Labels for Select filters

View File

@@ -60,4 +60,8 @@ return [
'log_export_done' => 'Exported :tables tables, :rows rows', 'log_export_done' => 'Exported :tables tables, :rows rows',
'log_transfer' => ':title transferred from :from to :to', 'log_transfer' => ':title transferred from :from to :to',
'log_close' => 'Ticket closed: :title', 'log_close' => 'Ticket closed: :title',
// Contract validation
'contract_duplicate_title' => 'Product already has active :category contract',
'contract_duplicate_body' => 'Product :product already has an active contract of this category with :customer. Please liquidate the existing contract before creating a new one.',
]; ];

View File

@@ -88,7 +88,11 @@ return [
'end_date' => 'Ngày kết thúc', 'end_date' => 'Ngày kết thúc',
'printed_at' => 'Ngày in HĐ', 'printed_at' => 'Ngày in HĐ',
'signed_status' => 'Tình trạng ký', 'signed_status' => 'Tình trạng ký',
'contract_category_section' => 'Phân loại hợp đồng',
'contract_info' => 'Thông tin hợp đồng', 'contract_info' => 'Thông tin hợp đồng',
'representative_info' => 'Thông tin người đại diện',
'representative_desc' => 'Người đại diện thay mặt chủ sở hữu (nếu có)',
'representative' => 'Người đại diện',
'feedback_history' => 'Lịch sử phản ánh', 'feedback_history' => 'Lịch sử phản ánh',
'service_type' => 'Loại dịch vụ', 'service_type' => 'Loại dịch vụ',
'tab_all' => 'Tất cả', 'tab_all' => 'Tất cả',

View File

@@ -32,11 +32,21 @@ return [
'liquidated' => 'Đã thanh lý', 'liquidated' => 'Đã thanh lý',
], ],
// Contract Type // Contract Category
'contract_category' => [
'ownership' => 'Sở hữu',
'business' => 'Kinh doanh',
],
'contract_category_label' => 'Phân loại HĐ',
// Contract Type (V2)
'contract_type' => [ 'contract_type' => [
'sale' => 'HĐ Mua bán', 'deposit' => 'Đặt cọc',
'lease' => 'HĐ Thuê', 'purchase' => 'Mua bán',
'bcc' => 'HĐ Hợp tác kinh doanh (BCC)', 'transfer' => 'Chuyển nhượng',
'rental' => 'Cho thuê',
'self_business' => 'Tự doanh',
'bcc' => 'Hợp tác KD (BCC)',
], ],
// Labels cho Select filters // Labels cho Select filters

View File

@@ -60,4 +60,8 @@ return [
'log_export_done' => 'Xuất :tables bảng, :rows dòng', 'log_export_done' => 'Xuất :tables bảng, :rows dòng',
'log_transfer' => ':title: chuyển từ :from sang :to', 'log_transfer' => ':title: chuyển từ :from sang :to',
'log_close' => 'Đóng ticket: :title', 'log_close' => 'Đóng ticket: :title',
// Contract validation
'contract_duplicate_title' => 'Căn hộ đã có HĐ :category active',
'contract_duplicate_body' => 'Căn hộ :product đã có HĐ thuộc nhóm này với khách :customer. Vui lòng thanh lý HĐ cũ trước khi tạo mới.',
]; ];