# MSA (Master Service Agreement) Implementation Plan

## Overview
Implement online MSA signing system that integrates with quotation acceptance flow. Customers fill in details, sign digitally, and system generates PDF.

---

## Business Flow

### Quotation Acceptance Flow
```
Customer receives quotation
    ↓
Customer clicks "Accept Quotation"
    ↓
Check Feasibility Result:
    ├─ MEDIUM → Show MSA signing modal
    ├─ HIGH → Auto-approve → Optional MSA later
    └─ LOW → Show alternative products → MSA on accept
    ↓
Customer fills MSA form
    ├─ Company details (pre-filled from profile)
    ├─ Registration number
    ├─ Addresses
    └─ Contact person
    ↓
Customer signs digitally
    ├─ Draw signature
    ├─ Type signature
    └─ Upload signature image
    ↓
System generates PDF
    ├─ Merge customer data
    ├─ Add signatures
    └─ Add timestamps
    ↓
Store MSA document
    ├─ Save to filesystem
    ├─ Link to quotation/order
    └─ Upload to Odoo
    ↓
Send confirmation email
    ├─ Attach signed MSA
    └─ Notify sales team
```

---

## Document Storage Structure

### Recommended Location
```
afinet-portal-backend/
├── storage/
│   └── app/
│       ├── templates/
│       │   ├── msa-template.docx ← Place Word document here
│       │   ├── msa-template.json ← Already exists
│       │   └── msa-template.html ← Convert to HTML template
│       └── msa-documents/
│           └── {customer_id}/
│               └── {quotation_id}/
│                   ├── msa-signed-{timestamp}.pdf
│                   └── msa-metadata.json
```

### Why This Structure?
- ✅ Organized by customer and quotation
- ✅ Easy to find and retrieve
- ✅ Supports multiple MSAs per customer
- ✅ Metadata for tracking versions

---

## Technical Implementation

### Phase 1: Document Template Setup

#### 1.1 Place Word Document
**Location**: `afinet-portal-backend/storage/app/templates/msa-template.docx`

**Action**: Upload your Word document here

#### 1.2 Convert to HTML Template
**Why**: Easier to fill programmatically, better for web display

**Tools**:
- Use Pandoc to convert DOCX → HTML
- Or manually create HTML template with placeholders

**Template Variables**:
```html
{{customer_name}}
{{customer_registration_number}}
{{customer_physical_address}}
{{customer_postal_address}}
{{customer_telephone}}
{{customer_email}}
{{customer_contact_person}}
{{signing_location}}
{{signing_date}}
{{customer_signature_image}}
{{witness_name}}
{{witness_signature_image}}
```

---

### Phase 2: Backend Implementation

#### 2.1 Database Migration
**File**: `database/migrations/2026_02_26_create_msa_documents_table.php`

```php
Schema::create('msa_documents', function (Blueprint $table) {
    $table->id();
    $table->foreignId('customer_id')->constrained()->onDelete('cascade');
    $table->foreignId('quotation_id')->nullable()->constrained()->onDelete('set null');
    $table->foreignId('order_id')->nullable()->constrained('sales_orders')->onDelete('set null');
    $table->string('document_number')->unique(); // MSA-2026-001
    $table->string('version')->default('1.0');
    $table->json('customer_data'); // All filled fields
    $table->string('signature_path'); // Customer signature image
    $table->string('witness_signature_path')->nullable();
    $table->string('pdf_path'); // Generated PDF
    $table->integer('odoo_attachment_id')->nullable();
    $table->enum('status', ['draft', 'signed', 'completed'])->default('draft');
    $table->timestamp('signed_at')->nullable();
    $table->string('ip_address')->nullable();
    $table->string('user_agent')->nullable();
    $table->timestamps();
});
```

#### 2.2 MSA Model
**File**: `app/Models/MsaDocument.php`

```php
class MsaDocument extends Model
{
    protected $fillable = [
        'customer_id', 'quotation_id', 'order_id',
        'document_number', 'version', 'customer_data',
        'signature_path', 'witness_signature_path',
        'pdf_path', 'odoo_attachment_id', 'status',
        'signed_at', 'ip_address', 'user_agent'
    ];

    protected $casts = [
        'customer_data' => 'array',
        'signed_at' => 'datetime',
    ];

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

    public function quotation() {
        return $this->belongsTo(Quotation::class);
    }

    public function order() {
        return $this->belongsTo(SalesOrder::class, 'order_id');
    }

    public function generateDocumentNumber() {
        $year = date('Y');
        $count = self::whereYear('created_at', $year)->count() + 1;
        return "MSA-{$year}-" . str_pad($count, 4, '0', STR_PAD_LEFT);
    }
}
```

#### 2.3 MSA Service
**File**: `app/Services/MsaService.php`

```php
class MsaService
{
    public function createDraft($customerId, $quotationId = null) {
        // Create draft MSA with pre-filled customer data
    }

    public function fillTemplate($msaId, $customerData) {
        // Fill HTML template with customer data
    }

    public function saveSignature($msaId, $signatureData) {
        // Save signature image
    }

    public function generatePdf($msaId) {
        // Generate PDF from HTML using DomPDF or similar
    }

    public function uploadToOdoo($msaId) {
        // Upload signed PDF to Odoo
    }

    public function sendConfirmationEmail($msaId) {
        // Send email with signed MSA
    }

    public function completeSigning($msaId, $ipAddress, $userAgent) {
        // Mark as signed and complete
    }
}
```

#### 2.4 MSA Controller
**File**: `app/Http/Controllers/API/MsaController.php`

```php
class MsaController extends Controller
{
    public function initiate(Request $request) {
        // POST /api/msa/initiate
        // Create draft MSA for quotation acceptance
    }

    public function getTemplate($msaId) {
        // GET /api/msa/{id}/template
        // Return HTML template with pre-filled data
    }

    public function saveData(Request $request, $msaId) {
        // PUT /api/msa/{id}/data
        // Save customer-filled data
    }

    public function uploadSignature(Request $request, $msaId) {
        // POST /api/msa/{id}/signature
        // Upload signature image
    }

    public function preview($msaId) {
        // GET /api/msa/{id}/preview
        // Return preview of filled MSA
    }

    public function sign(Request $request, $msaId) {
        // POST /api/msa/{id}/sign
        // Finalize and generate PDF
    }

    public function download($msaId) {
        // GET /api/msa/{id}/download
        // Download signed PDF
    }
}
```

---

### Phase 3: Frontend Implementation

#### 3.1 MSA Signing Modal Component
**File**: `afinet-portal/src/components/modals/msa-signing-modal.jsx`

**Features**:
- Multi-step form (3 steps)
- Step 1: Review MSA terms
- Step 2: Fill customer details
- Step 3: Sign digitally
- Progress indicator
- Signature pad (canvas)
- Preview before signing

#### 3.2 Signature Pad Component
**File**: `afinet-portal/src/components/forms/signature-pad.jsx`

**Features**:
- Canvas for drawing signature
- Clear button
- Undo button
- Save as image
- Alternative: Type signature (converts to image)
- Alternative: Upload signature image

#### 3.3 Integration with Quotation Page
**File**: `afinet-portal/src/app/(portal)/quotations/[id]/page.js`

**Changes**:
- Add "Accept Quotation" button
- Check feasibility result
- Show MSA modal for MEDIUM feasibility
- Handle MSA signing flow
- Show success message after signing

---

### Phase 4: PDF Generation

#### 4.1 Install Dependencies
```bash
composer require barryvdh/laravel-dompdf
```

#### 4.2 PDF Template
**File**: `resources/views/pdf/msa-document.blade.php`

**Features**:
- Professional layout
- AFINET branding
- Customer details section
- All MSA clauses
- Signature section with images
- Footer with document number and date

---

### Phase 5: Digital Signature Integration

#### Option A: Canvas Signature (Recommended)
**Library**: `react-signature-canvas`
```bash
npm install react-signature-canvas
```

**Pros**:
- ✅ Free
- ✅ Easy to implement
- ✅ Works offline
- ✅ Good UX

#### Option B: Third-Party API
**Options**:
- DocuSign API
- HelloSign API
- Adobe Sign API

**Pros**:
- ✅ Legally binding
- ✅ Audit trail
- ✅ Professional

**Cons**:
- ❌ Costs money
- ❌ External dependency

**Recommendation**: Start with Canvas, upgrade to API if needed

---

## API Endpoints

### MSA Management
```
POST   /api/msa/initiate                 - Create draft MSA
GET    /api/msa/{id}                     - Get MSA details
GET    /api/msa/{id}/template            - Get HTML template
PUT    /api/msa/{id}/data                - Update customer data
POST   /api/msa/{id}/signature           - Upload signature
GET    /api/msa/{id}/preview             - Preview MSA
POST   /api/msa/{id}/sign                - Finalize and sign
GET    /api/msa/{id}/download            - Download PDF
GET    /api/msa/customer/{customerId}    - List customer MSAs
```

---

## Integration Points

### 1. Quotation Acceptance
**When**: Customer clicks "Accept Quotation"
**Action**: 
- Check feasibility result
- If MEDIUM → Show MSA modal
- If HIGH → Auto-approve (optional MSA later)
- If LOW → Show alternatives

### 2. Order Creation
**When**: MSA is signed
**Action**:
- Create sales order
- Link MSA to order
- Update quotation status
- Send confirmation email

### 3. Odoo Sync
**When**: MSA is signed
**Action**:
- Upload PDF to Odoo
- Link to res.partner
- Link to sale.order
- Update partner notes

---

## Security Considerations

### 1. Signature Verification
- Store IP address
- Store user agent
- Store timestamp
- Store customer ID
- Hash signature data

### 2. Document Integrity
- Generate checksum of PDF
- Store in database
- Verify on download
- Prevent tampering

### 3. Access Control
- Only customer can sign their MSA
- Only signed MSAs can be downloaded
- Admin can view all MSAs
- Audit trail for all actions

---

## Email Notifications

### 1. Customer Email
**Subject**: "MSA Signed Successfully - AFINET"
**Content**:
- Confirmation message
- MSA document number
- Signed date
- Download link
- Attached PDF

### 2. Sales Team Email
**Subject**: "New MSA Signed - [Customer Name]"
**Content**:
- Customer details
- Quotation reference
- MSA document number
- Link to view in portal
- Attached PDF

---

## Testing Checklist

### Backend
- [ ] MSA draft creation
- [ ] Template filling
- [ ] Signature upload
- [ ] PDF generation
- [ ] Odoo sync
- [ ] Email sending

### Frontend
- [ ] Modal opens correctly
- [ ] Form validation
- [ ] Signature pad works
- [ ] Preview displays correctly
- [ ] Signing completes
- [ ] Download works

### Integration
- [ ] Quotation acceptance triggers MSA
- [ ] MSA links to order
- [ ] Feasibility routing works
- [ ] Email notifications sent
- [ ] Odoo sync successful

---

## Timeline Estimate

### Phase 1: Setup (2 hours)
- Place Word document
- Convert to HTML template
- Update JSON config

### Phase 2: Backend (6 hours)
- Database migration
- Models and relationships
- Service layer
- Controller and routes
- PDF generation

### Phase 3: Frontend (8 hours)
- MSA modal component
- Signature pad component
- Form validation
- Integration with quotations
- Preview functionality

### Phase 4: Integration (4 hours)
- Quotation acceptance flow
- Odoo sync
- Email notifications
- Testing

**Total**: ~20 hours (2-3 days)

---

## Next Steps

### Immediate Actions:
1. **Place your Word document** in `afinet-portal-backend/storage/app/templates/msa-template.docx`
2. **Confirm approach**: Canvas signature or API?
3. **Review MSA template**: Any custom fields needed?
4. **Start implementation**: Begin with Phase 1

### Questions to Answer:
1. Do you want witness signature required?
2. Should MSA be required for all quotations or only MEDIUM feasibility?
3. Do you need version control for MSA templates?
4. Should customers be able to download unsigned MSA for review?

---

## File Locations Summary

```
Backend:
├── storage/app/templates/
│   ├── msa-template.docx ← PLACE YOUR WORD DOC HERE
│   ├── msa-template.json ← Already exists
│   └── msa-template.html ← Create from DOCX
├── app/Models/MsaDocument.php
├── app/Services/MsaService.php
├── app/Http/Controllers/API/MsaController.php
├── database/migrations/*_create_msa_documents_table.php
└── resources/views/pdf/msa-document.blade.php

Frontend:
├── src/components/modals/msa-signing-modal.jsx
├── src/components/forms/signature-pad.jsx
└── src/app/(portal)/quotations/[id]/page.js (update)
```

---

**Ready to start?** Let me know and I'll begin implementing!
