# RELAMS Module : Invoice

## 1. Overview

Invoice is originally Order, a module responsible for storing sales record. now we need to rename everything attach to it into Invoice

## 2. General Rules:
- Naming is camelcase
- Use plural in namings where it is plural
- use itenary to ensure null and other data types yield result/display empty if false
- returning Json format is ["status": true, "data": [], "message": "Data fetched successfully"]

## 3. Current Orders Module Structure Analysis

### Existing Components:
- **Model**: `Order.php` (app/Models/)
- **Controller**: `OrderController.php` (app/Http/Controllers/V1/Web/)
- **Views**: `orders/` directory (resources/views/)
- **Routes**: Grouped under 'orders' prefix in web.php
- **Database**: `orders` table with related `order_items` table

### Key Functionality:
- Order creation and management
- Cart functionality for order items
- Payment processing integration
- PDF invoice generation
- Order status management (Active, Processing, Completed)
- Export functionality (Excel/PDF)
- Commission allocation
- Order cancellation with reasons

## 4. Invoice Module Transformation Plan

### Phase 1: Database Migration ✅ COMPLETED
#### 4.1 Rename Tables ✅
- Rename `orders` table to `invoices` ✅
- Rename `order_items` table to `invoice_items` ✅
- Update foreign key constraints accordingly ✅

#### 4.2 Update Column Names ✅
- Renamed `order_code` to `invoice_number` ✅
- Updated `order_id` to `invoice_id` in related tables ✅
- Updated Payment table `order_id` to `invoice_id` ✅

### Phase 2: Model Updates
#### 4.1 Invoice Model Enhancement
```php
// app/Models/Invoice.php
class Invoice extends Model
{
    protected $fillable = [
        'user_id',           // sales agent/representative
        'agent_id',          // agent handling the sale
        'customer_id',       // customer reference
        'customer_name',     // customer name
        'customer_phone',    // customer phone
        'customer_state',    // customer state
        'customer_address',  // customer address
        'invoice_number',    // unique invoice number (renamed from order_code)
        'payment_plan',      // payment plan type
        'tenure',           // payment tenure
        'start_date',       // invoice start date
        'due_date',         // payment due date
        'deposit_amount',   // initial deposit
        'installment_amount', // installment amount
        'amount',           // total amount
        'discount',         // discount applied
        'quantity',         // quantity of items
        'total',            // final total
        'balance',          // remaining balance
        'payment_status',   // payment status
        'status',           // invoice status
        'created_by',       // user who created
        'updated_by',       // user who updated
        'canceled_by',      // user who canceled
        'canceled_at',      // cancellation timestamp
        'canceled_reason',  // cancellation reason
        'commission_allocated' // commission status
    ];

    // Relationships
    public function items()
    {
        return $this->hasMany(InvoiceItem::class);
    }

    public function customer()
    {
        return $this->belongsTo(Customer::class);
    }

    public function agent()
    {
        return $this->belongsTo(Agent::class);
    }

    public function handledBy()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function payments()
    {
        return $this->hasMany(Payment::class, 'invoice_number', 'invoice_number');
    }
}
```

#### 4.2 InvoiceItem Model
```php
// app/Models/InvoiceItem.php
class InvoiceItem extends Model
{
    protected $fillable = [
        'invoice_id',       // renamed from order_id
        'invoice_number',   // renamed from order_code
        'property_id',          // property reference
        'quantity',
        'unit_price',
        'total_price',
        'description'
    ];

    public function invoice()
    {
        return $this->belongsTo(Invoice::class);
    }

    public function property()
    {
        return $this->belongsTo(Property::class);
    }
}
```

### Phase 3: Controller Transformation
#### 4.1 Rename Controller
- Rename `OrderController.php` to `InvoiceController.php`

#### 4.2 Update Class References
- Change all `Order` model references to `Invoice`
- Change all `OrderItem` references to `InvoiceItem`
- Update route names from `orders.*` to `invoices.*`

#### 4.3 Update Method Names (if needed)
- Consider renaming methods to reflect invoice terminology:
  - `invoicePDF()` stays the same
  - `paymentsPDF()` could become `paymentHistoryPDF()`

### Phase 4: Views Transformation
#### 4.1 Directory Rename
- Rename `resources/views/orders/` to `resources/views/invoices/`

#### 4.2 File Updates
Update all view files to:
- Change model references from `Order` to `Invoice`
- Change route references from `orders.*` to `invoices.*`
- Update form actions and links
- Update variable names where appropriate

#### 4.3 Template Content Updates
- Change "Order" text to "Invoice" in headings
- Update status labels if needed
- Update form labels and field names
- Update PDF templates to reflect invoice terminology

### Phase 5: Routes Update
#### 5.1 Route Group Rename
```php
// Change from:
Route::group(['prefix' => 'orders'], function () {
// To:
Route::group(['prefix' => 'invoices'], function () {
```

#### 5.2 Route Name Updates
- `orders.*` → `invoices.*`
- `orders.invoice.pdf` → `invoices.pdf` (or similar)
- `orders.payments.pdf` → `invoices.payments.pdf`

### Phase 6: Business Logic Updates
#### 6.1 Status Management
Current order statuses: Active, Processing, Completed
Consider invoice statuses: Draft, Sent, Paid, Overdue, Cancelled

#### 6.2 Invoice Number Generation
- Update invoice number generation logic
- Ensure uniqueness across the system
- Consider format: INV-YYYY-NNNN

#### 6.3 PDF Generation
- Update PDF templates to use "Invoice" terminology
- Update header information
- Update field labels

### Phase 7: Database Migration Script
#### 7.1 Create Migration
```php
// Rename orders table to invoices
Schema::rename('orders', 'invoices');

// Rename order_items table to invoice_items
Schema::rename('order_items', 'invoice_items');

// Update foreign key column names
Schema::table('invoice_items', function (Blueprint $table) {
    $table->renameColumn('order_id', 'invoice_id');
    $table->renameColumn('plot_id', 'property_id');
    $table->renameColumn('order_code', 'invoice_number');
});

// Update any other related tables
```

#### 7.2 Data Migration
- Update any references in related tables
- Update activity logs
- Update payment references

### Phase 8: Testing & Validation
#### 8.1 Functional Testing
- Test all CRUD operations
- Test PDF generation
- Test export functionality
- Test payment integration

#### 8.2 Data Integrity
- Verify all relationships work
- Check foreign key constraints
- Validate data migration

### Phase 9: Deployment Plan
#### 9.1 Pre-deployment
- Backup database
- Test migration on staging environment
- Update documentation

#### 9.2 Deployment Steps
1. Run database migration
2. Deploy code changes
3. Update any hardcoded references
4. Clear caches
5. Test functionality

#### 9.3 Rollback Plan
- Database backup restoration
- Code rollback procedures
- Data consistency checks

## 5. Implementation Checklist

### Database & Models ✅
- [x] Create database migration script ✅
- [x] Update Invoice model with proper fillable and relationships ✅
- [x] Create/update InvoiceItem model ✅
- [x] Test model relationships ✅

### Controller & Routes ✅
- [x] Rename OrderController to InvoiceController ✅
- [x] Update all model references ✅
- [x] Update route definitions ✅
- [x] Test all routes are accessible ✅

### Views & Templates ✅
- [x] Rename orders directory to invoices ✅
- [x] Update all view files with new references ✅
- [x] Update PDF templates ✅
- [x] Test all views render correctly ✅

### Business Logic ✅
- [x] Update status management ✅
- [x] Update invoice number generation ✅
- [x] Update PDF generation logic ✅
- [x] Test payment integration ✅

### Testing
- [ ] Unit tests for models
- [ ] Feature tests for CRUD operations
- [ ] Integration tests for payments
- [ ] PDF generation tests

### Documentation
- [ ] Update API documentation
- [ ] Update user guides
- [ ] Update inline code comments

## 6. Risk Assessment

### High Risk
- Data loss during table rename
- Broken relationships after migration
- Payment integration failures

### Medium Risk
- PDF generation issues
- Route conflicts
- View rendering problems

### Low Risk
- Naming inconsistencies
- Minor UI/UX issues
- Performance impacts

## 7. Success Criteria

- [ ] All invoice CRUD operations work
- [ ] PDF generation functions correctly
- [ ] Payment integration maintained
- [ ] Export functionality works
- [ ] No data loss during migration
- [ ] All relationships intact
- [ ] User interface consistent
- [ ] All tests pass

## 8. Timeline Estimate

- **Phase 1-2 (Database & Models)**: 2-3 days
- **Phase 3 (Controller)**: 1-2 days
- **Phase 4 (Views)**: 2-3 days
- **Phase 5 (Routes)**: 0.5 days
- **Phase 6-7 (Business Logic & Migration)**: 2-3 days
- **Phase 8 (Testing)**: 1-2 days
- **Phase 9 (Deployment)**: 0.5 days

**Total Estimate**: 9-14 days

## 9. Next Steps

1. Review and approve this transformation plan
2. Create detailed task breakdown
3. Set up development environment for testing
4. Begin with database migration script development
5. Implement changes in order of dependencies
