# Smart Mining Business Management & ERP System
## Complete Laravel 12 Development Plan

> **Purpose:** This file is the master implementation plan for building the Smart Mining Business Management & ERP System described in the project specification.
>
> **Primary stack:** Laravel 12 + PHP 8.3+ + MySQL 8+ + Sanctum + Spatie Permission + Filament + REST API.
>
> **Development strategy:** Build the ERP foundation and business modules first, then expose stable business services through APIs, and finally add AI/voice capabilities on top of the authorized business layer.

---

# 1. Project Goals

Build a production-ready Mining ERP that connects:

**Mining Sites → Production → Material → Dumpers → Dumping Points → Stock → Trucks → Factories → Deliveries → Sales → Payments → Expenses → Inventory → Fuel → Machinery → Employees → Accounting → Reports → AI**

The system must be:

- Secure
- Responsive
- Mobile-friendly
- PWA-ready
- API-first
- English/Urdu bilingual
- Urdu RTL capable
- Role/permission controlled
- Auditable
- Scalable
- Testable
- Suitable for desktop, tablet and mobile browsers

The owner should be able to understand the complete business position from a mobile device.

---

# 2. Technology Stack

## Backend

- PHP 8.3+
- Laravel 12
- MySQL 8+
- Laravel Sanctum
- Spatie Laravel Permission
- Laravel Queues
- Laravel Scheduler
- Laravel Notifications
- Laravel Filesystem
- Laravel API Resources
- Laravel Form Requests
- Laravel Policies
- Laravel Events/Listeners
- Laravel Cache

## Admin Panel

- Filament
- Free/open-source Material Design inspired visual language
- Responsive UI
- Dashboard widgets
- Tables
- Filters
- Forms
- Charts
- Actions
- Bulk actions
- Export functionality

Do not use a paid admin theme.

## Frontend

Admin:

- Filament
- Livewire
- Alpine.js where useful
- Tailwind where required by Filament

Future public/mobile frontend:

- REST API under `/api/v1`
- PWA-ready architecture

## Authentication

- Web/admin authentication
- Sanctum API tokens

## Reports

- PDF
- Excel
- CSV
- Print

## AI

Use a provider abstraction:

```text
AiProviderInterface
├── OpenAiProvider
└── MockAiProvider
```

AI must never directly access unrestricted database queries.

---

# 3. Architecture Principles

## 3.1 Domain-Oriented Structure

Organize business logic into clear domains.

Recommended structure:

```text
app/
├── Actions/
├── Enums/
├── Events/
├── Exceptions/
├── Http/
│   ├── Controllers/
│   │   └── Api/
│   │       └── V1/
│   ├── Requests/
│   └── Resources/
├── Models/
├── Notifications/
├── Policies/
├── Services/
│   ├── Accounting/
│   ├── AI/
│   ├── Inventory/
│   ├── Operations/
│   ├── Reporting/
│   ├── Stock/
│   └── Transport/
└── Support/
```

Do not create a giant controller.

Business logic must live in services/actions rather than Blade or Filament resources.

---

# 4. Required Core Modules

1. Dashboard
2. Authentication
3. Users
4. Roles
5. Permissions
6. Mining Sites
7. Materials
8. Machines
9. Machine Hours
10. Operators
11. Maintenance
12. Drivers
13. Dumpers
14. Trucks
15. Dumping Points
16. Production
17. Trips
18. Challans
19. Stock
20. Stock Movements
21. Factories
22. Customers
23. Suppliers
24. Deliveries
25. Sales
26. Payments
27. Expenses
28. Fuel
29. Inventory
30. Employees
31. Salaries
32. Cash Accounts
33. Bank Accounts
34. Chart of Accounts
35. General Ledger
36. Receivables
37. Payables
38. Approvals
39. Audit Logs
40. Notifications
41. Documents/Attachments
42. Reports
43. Settings
44. Backups
45. AI Assistant
46. Voice Entries

---

# 5. Database Plan

## 5.1 Authentication and Access

Tables:

```text
users
roles
permissions
model_has_roles
model_has_permissions
role_has_permissions
```

User fields:

```text
id
name
email
phone
password
preferred_locale
status
site_id nullable
email_verified_at
remember_token
timestamps
soft_deletes where appropriate
```

---

# 6. Mining Operations Tables

## mining_sites

Fields:

```text
id
name
code
location
license_information
owner_company
start_date
status
site_manager_id nullable
notes
production_target
monthly_production_target
timestamps
soft_deletes
```

## materials

```text
id
name
code
unit
description
status
timestamps
soft_deletes
```

Units:

```text
ton
cubic_meter
truck_load
dumper_load
```

---

# 7. Machinery Tables

## machines

```text
id
name
machine_id
registration_number
model
manufacturer
purchase_date
purchase_price
status
site_id
operator_id nullable
current_hour_meter
last_service_date
next_service_date
fuel_consumption
notes
timestamps
soft_deletes
```

Machine types:

```text
excavator
loader
backhoe
bulldozer
crusher
generator
water_tanker
other
```

## machine_hours

```text
id
machine_id
date
opening_hour_meter
closing_hour_meter
total_hours
operator_id nullable
site_id
remarks
created_by
timestamps
```

Rule:

```text
closing_hour_meter >= opening_hour_meter
```

`total_hours` must be calculated server-side.

## machine_maintenance

```text
id
machine_id
date
problem
work_performed
parts_used
labour_cost
total_cost
technician
next_service_date
next_service_hour
status
created_by
timestamps
```

---

# 8. Transport Tables

## drivers

```text
id
name
cnic
phone
address
joining_date
salary
payment_method
status
emergency_contact
notes
timestamps
soft_deletes
```

## vehicles

Generic vehicle table if useful:

```text
id
type
registration_number
name
capacity
driver_id nullable
site_id nullable
status
notes
timestamps
soft_deletes
```

## dumpers

```text
id
dumper_number
registration_number
owner
driver_id nullable
capacity
material_id nullable
site_id nullable
status
maintenance_status
notes
timestamps
soft_deletes
```

## trucks

```text
id
truck_number
registration_number
driver_id nullable
capacity
status
notes
timestamps
soft_deletes
```

---

# 9. Dumping Points

## dumping_points

```text
id
site_id
name
location
capacity
material_id
status
notes
timestamps
soft_deletes
```

Current stock must be derived from stock movements rather than manually edited.

---

# 10. Production

## production

```text
id
date
site_id
material_id
machine_id
operator_id
quantity
unit
working_hours
shift
dumping_point_id
remarks
created_by
timestamps
soft_deletes
```

Reports:

- Daily production
- Weekly production
- Monthly production
- Site-wise production
- Machine-wise production
- Material-wise production

---

# 11. Trips

## trips

```text
id
trip_number
date
driver_id
vehicle_id
site_id
loading_point
dumping_point_id nullable
material_id
quantity
trip_count
start_time
end_time
challan_number nullable
remarks
status
created_by
timestamps
soft_deletes
```

Rules:

- Quantity cannot be negative.
- Trip count cannot be negative.
- Vehicle must exist.
- Driver must exist.
- Prevent conflicting trips where practical.
- Authorized users only may edit/delete trips.

---

# 12. Challans

## challans

```text
id
challan_number
date
driver_id
vehicle_id
material_id
quantity
loading_point
destination
factory_id nullable
authorized_person
status
created_by
timestamps
```

Rules:

- Challan number unique.
- Quantity positive.
- Authorized users only may void/cancel.
- Financially relevant changes must be audited.

Features:

- View
- Print
- PDF
- Download
- Attachments

---

# 13. Stock Architecture

Material flow:

```text
MINING SITE
    ↓
PRODUCTION
    ↓
SMALL DUMPER
    ↓
DUMPING POINT
    ↓
STOCK
    ↓
LARGE TRUCK
    ↓
FACTORY
    ↓
DELIVERY
```

## stock

```text
id
site_id
location_type
location_id
material_id
quantity
timestamps
```

## stock_movements

```text
id
material_id
site_id
location_type
location_id
movement_type
quantity
reference_type
reference_id
remarks
created_by
timestamps
```

Movement types:

```text
opening
production
transfer_in
transfer_out
dispatch
delivery
adjustment
```

Never modify stock directly without recording a movement.

All stock-changing operations must use a transaction.

---

# 14. Factories

## factories

```text
id
name
contact_person
phone
email
address
rate
material_id nullable
payment_terms
credit_limit
opening_balance
status
timestamps
soft_deletes
```

Factory account must show:

- Material delivered
- Quantity
- Rate
- Total
- Payments
- Outstanding
- Payment history

---

# 15. Customers

## customers

```text
id
name
contact_person
phone
email
address
opening_balance
credit_limit
status
timestamps
soft_deletes
```

Customer ledger:

```text
Opening Balance
Sales/Debit
Payments/Credit
Adjustments
Closing Balance
```

---

# 16. Suppliers

## suppliers

```text
id
name
contact_person
phone
email
address
opening_balance
status
notes
timestamps
soft_deletes
```

Supplier ledger must track:

- Purchases
- Payments
- Outstanding
- Payment history

---

# 17. Deliveries

## deliveries

```text
id
delivery_number
date
factory_id nullable
customer_id nullable
material_id
quantity
rate
total
vehicle_id nullable
driver_id nullable
challan_id nullable
site_id
status
created_by
timestamps
soft_deletes
```

Formula:

```text
total = quantity × rate
```

On confirmed delivery:

1. Validate stock.
2. Create delivery.
3. Create sale.
4. Reduce stock.
5. Create receivable.
6. Create ledger transaction.

All six operations must occur inside one database transaction.

---

# 18. Sales

## sales

```text
id
sale_number
date
factory_id nullable
customer_id nullable
delivery_id nullable
subtotal
discount
total
paid_amount
outstanding_amount
status
created_by
timestamps
soft_deletes
```

Never trust frontend totals.

Calculate totals on the backend.

---

# 19. Payments

## payments

```text
id
date
party_type
party_id
amount
payment_method
cash_account_id nullable
bank_account_id nullable
reference
notes
attachment
status
created_by
approved_by nullable
timestamps
```

Payment must:

- Update account
- Create ledger entry
- Update receivable/payable

Use database transactions.

---

# 20. Expenses

## expense_categories

```text
id
name
code
status
timestamps
```

Categories:

```text
Fuel
Diesel
Petrol
Machinery Repair
Spare Parts
Driver Payments
Labour
Salaries
Food
Transport
Electricity
Office
Site Expenses
Maintenance
Government Fees
Taxes
Miscellaneous
```

## expenses

```text
id
date
category_id
amount
paid_from_type
paid_from_id
site_id nullable
description
attachment nullable
status
created_by
approved_by nullable
timestamps
soft_deletes
```

---

# 21. Fuel

## fuel_transactions

```text
id
date
fuel_type
machine_id nullable
vehicle_id nullable
quantity
rate
total_cost
supplier_id nullable
meter_reading nullable
hour_reading nullable
driver_id nullable
operator_id nullable
site_id
remarks
created_by
timestamps
```

Reports:

- Fuel per machine
- Fuel per vehicle
- Fuel per trip
- Fuel per ton
- Monthly fuel cost
- Fuel stock

---

# 22. Inventory

## inventory_items

```text
id
name
sku
category
unit
current_stock
minimum_stock
maximum_stock
status
timestamps
soft_deletes
```

Inventory operations:

- Stock In
- Stock Out
- Purchase
- Consumption
- Transfer
- Adjustment

## inventory_transactions

```text
id
inventory_item_id
type
quantity
unit_cost
total_cost
source_type nullable
source_id nullable
destination_type nullable
destination_id nullable
remarks
created_by
timestamps
```

Low-stock alerts must be generated automatically.

---

# 23. Employees

## employees

```text
id
name
contact
role
joining_date
salary
payment_method
status
notes
timestamps
soft_deletes
```

Future-ready support:

- Attendance
- Advances
- Deductions
- Salary payments

---

# 24. Accounting

Implement a basic reliable accounting layer.

## accounts

```text
id
code
name
type
parent_id nullable
status
timestamps
```

Account types:

```text
asset
liability
equity
income
expense
```

## ledger_entries

```text
id
account_id
transaction_date
reference_type
reference_id
description
debit
credit
created_by
timestamps
```

Implement:

- Chart of Accounts
- General Ledger
- Customer Ledger
- Factory Ledger
- Supplier Ledger
- Cash Book
- Bank Book
- Receivables
- Payables
- Journal Entries
- Trial Balance
- Profit & Loss

Use double-entry accounting where applicable.

Financial posting must be centralized in accounting services.

---

# 25. Cash Accounts

## cash_accounts

```text
id
name
opening_balance
current_balance
status
timestamps
```

Examples:

```text
Main Cash
Site Cash
Office Cash
```

Operations:

- Receipt
- Payment
- Transfer
- Adjustment

---

# 26. Bank Accounts

## bank_accounts

```text
id
name
bank_name
account_number
opening_balance
current_balance
status
timestamps
```

Operations:

- Deposit
- Withdrawal
- Transfer
- Payment
- Receipt
- Bank Charge

---

# 27. Approval System

## approval_requests

```text
id
requestable_type
requestable_id
requested_by
approved_by nullable
status
reason nullable
approved_at nullable
rejected_at nullable
timestamps
```

Statuses:

```text
draft
pending
approved
rejected
posted
```

Transactions that may require approval:

- Expenses
- Stock adjustments
- Payments
- Material dispatch
- Purchases
- Salaries
- Credit sales

---

# 28. Audit Logs

## audit_logs

```text
id
user_id
action
auditable_type
auditable_id
old_values
new_values
ip_address
user_agent
created_at
```

Record:

- Create
- Update
- Delete/void
- Approve
- Reject
- Login
- Logout
- Important permission changes

Financial records should preferably be reversed/voided instead of physically deleted.

---

# 29. Attachments

Create reusable attachment architecture.

## attachments

```text
id
attachable_type
attachable_id
disk
path
original_name
mime_type
size
uploaded_by
timestamps
```

Examples:

- Fuel receipts
- Purchase invoices
- Challans
- Payment receipts
- Machine documents
- Vehicle documents
- Licenses
- Agreements

Private documents must not be publicly accessible.

---

# 30. Vehicle and License Documents

Create a document/expiry system.

Track:

- Registration
- Insurance
- Fitness
- License
- Other documents

Alerts:

- 30 days before expiry
- 15 days before expiry
- 7 days before expiry

---

# 31. User Roles

Initial roles:

```text
super_admin
admin
accountant
site_manager
supervisor
driver
data_entry_operator
store_keeper
factory_customer
```

## Super Admin

Full access.

## Admin

Almost full access except critical system-level restrictions.

## Accountant

Access:

- Accounts
- Customers
- Suppliers
- Payments
- Expenses
- Reports

No system administration.

## Site Manager

Access:

- Production
- Machines
- Drivers
- Dumpers
- Trips
- Site inventory

## Supervisor

Access:

- Machine hours
- Production
- Trips
- Drivers

## Driver

Access:

- Own profile
- Own trips
- Assigned vehicle
- Trip entry

## Data Entry Operator

Can create permitted operational records.

Cannot delete critical records.

## Store Keeper

Access:

- Inventory
- Fuel
- Spare parts
- Stock operations

## Factory/Customer

Restricted access:

- Deliveries
- Challans
- Statements
- Outstanding

---

# 32. Permission Naming

Use consistent granular permissions.

Examples:

```text
dashboard.view

users.view
users.create
users.update
users.delete

sites.view
sites.create
sites.update
sites.delete

production.view
production.create
production.update
production.delete
production.approve
production.export

machine_hours.view
machine_hours.create
machine_hours.update

trips.view
trips.create
trips.update
trips.delete
trips.approve

expenses.view
expenses.create
expenses.update
expenses.delete
expenses.approve

payments.view
payments.create
payments.update
payments.approve

inventory.view
inventory.create
inventory.update
inventory.adjust
inventory.approve

reports.view
reports.export

accounting.view
accounting.create
accounting.update

settings.manage
backups.manage
audit_logs.view

ai.use
ai.execute
ai.financial_execute
ai.reports
```

---

# 33. Admin Panel Navigation

## Dashboard

- Overview
- Owner Dashboard

## OPERATIONS

- Mining Sites
- Materials
- Production
- Machines
- Machine Hours
- Maintenance
- Dumping Points
- Material Stock

## TRANSPORT

- Drivers
- Dumpers
- Trucks
- Trips
- Challans

## SALES

- Factories
- Customers
- Deliveries
- Sales
- Payments

## PURCHASING & EXPENSES

- Suppliers
- Expenses
- Expense Categories
- Fuel

## INVENTORY

- Inventory Items
- Stock In
- Stock Out
- Transfers
- Adjustments

## HR

- Employees
- Salaries
- Attendance

## ACCOUNTS

- Chart of Accounts
- General Ledger
- Cash Accounts
- Bank Accounts
- Receivables
- Payables

## REPORTS

- Daily Report
- Production Report
- Transport Report
- Fuel Report
- Inventory Report
- Sales Report
- Customer Ledger
- Factory Ledger
- Supplier Ledger
- Cash Book
- Profit & Loss
- Cost Per Ton

## AI

- AI Assistant
- Conversations
- Voice Entries

## SYSTEM

- Users
- Roles
- Permissions
- Approvals
- Audit Logs
- Notifications
- Attachments
- Settings
- Backups

---

# 34. Dashboard

Dashboard must use real database data.

Cards:

- Today's Production
- Today's Excavation
- Machine Hours
- Dumper Trips
- Truck Trips
- Material Moved
- Factory Deliveries
- Today's Sales
- Today's Expenses
- Cash Balance
- Bank Balance
- Receivables
- Payables
- Fuel Consumed
- Active Machines
- Machines Under Maintenance

Charts:

- Daily Production
- Monthly Production
- Factory Deliveries
- Customer Sales
- Expense Analysis
- Fuel Consumption
- Machine Utilization
- Dumper Performance

Filters:

- Date
- Site
- Material
- Factory
- Customer

No hardcoded numbers.

---

# 35. Owner Dashboard

Special owner view:

- Total Production
- Total Sales
- Total Expenses
- Estimated Profit
- Factory Balances
- Customer Balances
- Cash
- Bank
- Stock
- Fuel
- Machines
- Drivers
- Outstanding Payments

The owner should be able to access this from mobile.

---

# 36. API Architecture

Base URL:

```text
/api/v1
```

Authentication:

```text
POST /api/v1/auth/login
POST /api/v1/auth/logout
GET  /api/v1/auth/me
```

Modules:

```text
/api/v1/dashboard
/api/v1/sites
/api/v1/materials
/api/v1/machines
/api/v1/machine-hours
/api/v1/production
/api/v1/dumping-points
/api/v1/drivers
/api/v1/dumpers
/api/v1/trucks
/api/v1/trips
/api/v1/challans
/api/v1/factories
/api/v1/customers
/api/v1/suppliers
/api/v1/deliveries
/api/v1/sales
/api/v1/payments
/api/v1/expenses
/api/v1/fuel
/api/v1/inventory
/api/v1/maintenance
/api/v1/employees
/api/v1/accounts
/api/v1/ledger
/api/v1/reports
/api/v1/notifications
/api/v1/ai
```

Every API endpoint must:

- Authenticate
- Authorize
- Validate
- Return consistent JSON
- Support pagination
- Support filtering
- Support sorting
- Return correct HTTP status codes

---

# 37. API Response Standard

Success:

```json
{
    "success": true,
    "message": "Operation successful",
    "data": {},
    "meta": {}
}
```

Validation:

```json
{
    "success": false,
    "message": "Validation failed",
    "errors": {}
}
```

Not authorized:

```json
{
    "success": false,
    "message": "You are not authorized to perform this action."
}
```

---

# 38. Authentication

Web:

- Filament authentication

API:

- Sanctum

Requirements:

- Secure password hashing
- Rate limiting
- Login protection
- Token revocation
- Authorization policies
- Optional 2FA-ready architecture

API user endpoints:

```text
POST /auth/login
POST /auth/logout
GET /auth/me
```

---

# 39. Localization

Locales:

```text
en
ur
```

Translation structure:

```text
lang/
├── en/
│   ├── auth.php
│   ├── common.php
│   ├── dashboard.php
│   ├── operations.php
│   ├── accounting.php
│   ├── reports.php
│   └── validation.php
└── ur/
    ├── auth.php
    ├── common.php
    ├── dashboard.php
    ├── operations.php
    ├── accounting.php
    ├── reports.php
    └── validation.php
```

When Urdu is selected:

- Enable RTL.
- Support RTL navigation.
- Support RTL forms.
- Support RTL tables where appropriate.
- Maintain correct number/currency display.

Store preferred locale per user.

---

# 40. Notifications

Create Laravel Notifications for:

- Low inventory
- Low fuel
- Maintenance due
- Payment due
- Customer outstanding
- Supplier outstanding
- Production target missed
- Backup failure
- Pending approval
- Vehicle document expiry

Channels can initially include:

- Database
- Mail

Future:

- SMS
- WhatsApp
- Push notifications

---

# 41. Scheduled Jobs

Use Laravel Scheduler.

Jobs:

```text
GenerateDailyReport
SendDailyReportEmail
CheckMaintenanceDue
CheckVehicleDocumentExpiry
CheckPaymentDue
CheckLowInventory
CheckLowFuel
CheckPendingApprovals
CheckBackupStatus
```

Schedules should be configurable where practical.

---

# 42. Daily Report

Daily report:

- Production
- Machine Hours
- Dumper Trips
- Truck Trips
- Factory Deliveries
- Sales
- Expenses
- Fuel Consumption
- Cash Received
- Cash Spent
- Outstanding Payments
- Stock Movement

---

# 43. Monthly Report

Monthly report:

- Total Excavation
- Total Production
- Total Material Moved
- Factory Deliveries
- Dumper Trips
- Truck Trips
- Machine Hours
- Sales
- Expenses
- Fuel
- Outstanding
- Estimated Profit

---

# 44. Profit & Loss

Revenue:

- Factory Sales
- Customer Sales
- Other Income

Expenses:

- Fuel
- Salaries
- Drivers
- Machinery
- Repairs
- Transportation
- Purchases
- Site Expenses
- Administrative Expenses

Show:

- Gross Profit
- Net Profit
- Profit Margin

All figures must come from accounting/business transactions.

---

# 45. Cost Per Ton

Formula:

```text
Total Operational Cost / Total Production
```

Also calculate:

```text
Fuel Cost Per Ton
Machine Cost Per Ton
Transportation Cost Per Ton
Labour Cost Per Ton
Total Cost Per Ton
```

---

# 46. Business KPIs

Dashboard KPIs:

- Production/day
- Production/month
- Revenue/month
- Expense/month
- Profit/month
- Cost/ton
- Machine utilization
- Trips/day
- Tons/trip
- Fuel/working hour
- Fuel/ton
- Outstanding receivables
- Outstanding payables

---

# 47. Search and Filtering

Major modules must support:

- Search
- Date filter
- Site filter
- Driver filter
- Vehicle filter
- Factory filter
- Customer filter
- Material filter
- User filter
- Status filter

Tables must support:

- Sorting
- Pagination
- Export

---

# 48. AI Architecture

AI is implemented only after the core ERP business logic is stable.

Architecture:

```text
USER INPUT
    ↓
Speech/Text
    ↓
AI Provider
    ↓
Intent Detection
    ↓
Structured Command
    ↓
Permission Check
    ↓
Validation
    ↓
Confirmation
    ↓
Business Service
    ↓
Database
    ↓
Response
```

AI must never receive unrestricted database access.

AI must call approved application services.

---

# 49. AI Provider Interface

Create:

```php
interface AiProviderInterface
{
    public function understand(string $input, array $context = []): AiCommand;
}
```

Possible providers:

```text
OpenAiProvider
MockAiProvider
```

Configuration:

```text
AI_PROVIDER=
AI_API_KEY=
AI_MODEL=
```

Never hardcode API keys.

---

# 50. AI Commands

Example:

User:

```text
آج احمد کے ڈمپر نے 5 چکر لگائے
```

Extract:

```text
driver = Ahmed
trips = 5
date = today
```

Then:

1. Find driver.
2. Check user permission.
3. Validate vehicle/trip.
4. Build command.
5. Ask confirmation if required.
6. Call TripService.
7. Save audit record.
8. Return result.

---

# 51. AI Business Questions

Examples:

```text
اس مہینے کتنی production ہوئی؟
سب سے زیادہ trips کس driver نے کیے؟
کون سی factory کے پیسے outstanding ہیں؟
اس مہینے fuel پر کتنا خرچ ہوا؟
آج کی total expenses کتنی ہیں؟
کون سی machine service کے لیے due ہے؟
ABC Factory کا balance کیا ہے؟
اس مہینے estimated profit کتنا ہے؟
```

AI answers must be generated from authorized application queries.

Never invent database values.

---

# 52. AI Financial Safety

Financial commands must require confirmation.

Examples:

- Payment
- Expense
- Salary
- Customer balance adjustment
- Factory invoice
- Stock adjustment
- Delete/void

Example:

```text
یہ مالیاتی entry ہے:
Diesel Expense = Rs. 25,000

کیا آپ confirm کرتے ہیں؟
```

Only after confirmation execute.

---

# 53. Voice Architecture

## voice_entries

```text
id
user_id
audio_path
transcription
language
intent
structured_command
status
executed_at
result
error
timestamps
```

Workflow:

```text
Voice
↓
Speech-to-Text
↓
Transcription
↓
AI
↓
Intent
↓
Permission
↓
Validation
↓
Confirmation
↓
Business Service
↓
Database
```

Support:

- Urdu
- English
- Mixed Urdu/English

---

# 54. PWA / Offline Readiness

The mining site may have poor connectivity.

Prepare architecture for:

```text
Mobile Browser
↓
Local Temporary Storage
↓
Pending Sync
↓
Server
↓
Conflict Validation
↓
Synced
```

Sync statuses:

```text
pending
syncing
synced
failed
```

Prevent duplicate records using client-generated idempotency keys.

Offline support should initially focus on operational entries.

Financial offline operations should be treated more cautiously and preferably require connectivity.

---

# 55. Backup Architecture

Backup frequency:

- Daily
- Weekly
- Monthly

Track:

```text
backup status
last successful backup
next backup
backup size
```

Support:

- Local backup
- Cloud backup
- Authorized restore

Never expose backup files publicly.

---

# 56. Security Requirements

Required:

- HTTPS in production
- Secure password hashing
- CSRF protection
- XSS protection
- SQL injection protection
- Authentication
- Authorization
- API token security
- Rate limiting
- Login attempt protection
- Input validation
- File validation
- Private document storage
- Audit logs
- Soft deletes
- Transactional financial operations
- Secure environment variables

Never commit secrets.

---

# 57. Business Integrity Rules

## Machine Hours

```text
closing >= opening
```

## Quantities

```text
quantity > 0
```

## Challans

```text
challan_number unique
```

## Vehicles

```text
registration_number unique
```

## Stock

No negative stock unless explicitly configured.

## Financial Records

Do not silently modify posted transactions.

Use:

```text
reversal
adjustment
void
audit
```

## Delivery

Must atomically update:

```text
delivery
sale
stock
receivable
ledger
```

## Permissions

All operations must respect the logged-in user's permissions.

---

# 58. Testing Strategy

Use:

- PHPUnit/Pest according to project configuration
- Feature tests
- Unit tests
- API tests
- Authorization tests
- Database tests

Test:

### Authentication

- Login
- Logout
- Invalid credentials
- Token authorization

### Authorization

- Role access
- Permission access
- Site restrictions
- Financial restrictions

### Production

- Create
- Update
- Validation
- Reporting

### Machine Hours

- Valid hours
- Invalid closing hours

### Trips

- Valid trip
- Duplicate/conflicting trip
- Authorization

### Stock

- Production stock
- Transfer
- Dispatch
- Delivery
- Negative stock prevention

### Sales

- Correct total
- Receivable creation

### Payments

- Correct ledger
- Correct balance

### Expenses

- Approval
- Posting
- Audit

### Accounting

- Debit/credit
- Ledger
- Trial balance
- Profit & Loss

### AI

- Authorized question
- Unauthorized question
- Operational command
- Financial confirmation
- Invalid command

---

# 59. Seeders

Create development seeders.

Initial:

```text
Roles
Permissions
Admin
Sample Sites
Materials
Machines
Drivers
Dumpers
Trucks
Factories
Customers
Suppliers
Expense Categories
Inventory Categories
Chart of Accounts
```

Clearly mark seed data as development data.

---

# 60. Development Phases

## PHASE 0 — Project Bootstrap

Tasks:

- Create Laravel 12 project
- Configure environment
- Configure MySQL
- Install Sanctum
- Install Spatie Permission
- Install Filament
- Configure storage
- Configure queues
- Configure scheduler
- Configure localization
- Configure testing

Deliverable:

A clean Laravel 12 foundation.

---

# 61. PHASE 1 — Authentication and Admin Foundation

Implement:

- Admin login
- Users
- Roles
- Permissions
- Sanctum
- API login
- API logout
- API current user
- Filament panel
- Material-inspired styling
- English/Urdu foundation
- RTL foundation
- Base dashboard
- Admin seeder

Tests:

- Login
- Logout
- Role access
- Permission access
- API authentication

---

# 62. PHASE 2 — Mining Operations Foundation

Implement:

- Mining Sites
- Materials
- Machines
- Operators
- Machine Hours
- Maintenance

Tests:

- Relationships
- Machine-hour validation
- Site authorization
- Maintenance rules

---

# 63. PHASE 3 — Transport Operations

Implement:

- Drivers
- Vehicles
- Dumpers
- Trucks
- Dumping Points
- Trips
- Challans
- Production

Tests:

- Trip validation
- Duplicate challans
- Duplicate registrations
- Driver/vehicle relationships
- Production calculations

---

# 64. PHASE 4 — Stock and Sales

Implement:

- Stock
- Stock Movements
- Factories
- Customers
- Deliveries
- Sales
- Receivables

Critical transaction:

```text
Delivery
→ Sale
→ Stock reduction
→ Receivable
→ Ledger
```

Must be atomic.

---

# 65. PHASE 5 — Suppliers, Expenses, Fuel and Inventory

Implement:

- Suppliers
- Expenses
- Expense Categories
- Fuel
- Inventory
- Stock In
- Stock Out
- Transfers
- Adjustments
- Low-stock alerts

---

# 66. PHASE 6 — HR and Accounting

Implement:

- Employees
- Salaries
- Cash Accounts
- Bank Accounts
- Chart of Accounts
- General Ledger
- Customer Ledger
- Supplier Ledger
- Factory Ledger
- Receivables
- Payables
- Journal Entries
- Trial Balance
- Profit & Loss

---

# 67. PHASE 7 — Approval, Audit and Notifications

Implement:

- Approval Requests
- Approval workflows
- Audit logs
- Notifications
- Vehicle expiry
- Maintenance alerts
- Low-stock alerts
- Payment alerts

---

# 68. PHASE 8 — Reports

Implement:

- Daily Report
- Monthly Report
- Production Report
- Machine Hours
- Machine Utilization
- Driver Trips
- Dumper Trips
- Truck Trips
- Material Movement
- Factory Deliveries
- Sales
- Customer Ledger
- Factory Ledger
- Supplier Ledger
- Cash Book
- Bank Book
- Inventory
- Fuel
- Receivables
- Payables
- Profit & Loss
- Cost Per Ton

Exports:

- PDF
- Excel
- CSV
- Print

---

# 69. PHASE 9 — REST API Completion

Implement complete `/api/v1` coverage.

For each module:

- Routes
- Controller
- Request
- Resource
- Policy
- Service
- Pagination
- Filtering
- Sorting
- Validation
- Authorization
- Tests

Prepare API documentation.

---

# 70. PHASE 10 — AI Business Agent

Implement:

- AI provider abstraction
- AI configuration
- Conversations
- Commands
- Intent detection
- Structured commands
- Permission checking
- Confirmation workflow
- Business-service execution
- AI audit logs
- Authorized business queries
- AI reports

Do not give AI direct unrestricted database access.

---

# 71. PHASE 11 — Voice

Implement:

- Voice upload/recording architecture
- Speech-to-text abstraction
- Urdu
- English
- Mixed language
- Transcription
- AI command extraction
- Confirmation
- Execution
- Audit

---

# 72. PHASE 12 — PWA / Offline

Implement:

- Installable PWA
- Mobile dashboard
- Quick Entry
- Offline operational entries
- Local queue
- Sync
- Retry
- Idempotency
- Conflict handling
- Sync status

---

# 73. PHASE 13 — Automation

Implement:

- Daily report generation
- Daily email
- Maintenance notifications
- Payment notifications
- Low inventory notifications
- Low fuel notifications
- Document expiry
- Backup monitoring

---

# 74. PHASE 14 — Security Hardening

Perform:

- Authorization review
- API rate-limit review
- File upload review
- SQL injection review
- XSS review
- CSRF review
- Mass assignment review
- Sensitive data review
- Audit review
- Financial transaction review
- Secret/environment review
- Production configuration review

---

# 75. PHASE 15 — Final Testing

Run:

```bash
php artisan test
```

Also run:

```bash
php artisan migrate:fresh --seed
```

Verify:

- Admin login
- API login
- Permissions
- All CRUD modules
- Reports
- Accounting
- Stock
- Deliveries
- Payments
- Notifications
- AI
- Voice
- PWA
- Backup

Fix every test failure before release.

---

# 76. Cursor Development Workflow

Cursor must follow this process for every phase.

## Step 1

Inspect current project.

## Step 2

Review already implemented modules.

## Step 3

Create migrations.

## Step 4

Create/update models.

## Step 5

Create relationships.

## Step 6

Create enums.

## Step 7

Create services/actions.

## Step 8

Create policies.

## Step 9

Create Form Requests.

## Step 10

Create API Resources.

## Step 11

Create API Controllers.

## Step 12

Create API routes.

## Step 13

Create Filament Resources.

## Step 14

Create filters/search/sorting.

## Step 15

Create translations.

## Step 16

Create tests.

## Step 17

Run migrations.

## Step 18

Run tests.

## Step 19

Fix errors.

## Step 20

Verify manually.

## Step 21

Document completed work.

Do not move to the next phase until the current phase is stable.

---

# 77. Cursor Rules

Create a project-level `AGENTS.md` or Cursor rules file containing:

```text
You are working on a Laravel 12 production ERP.

Never invent database fields when the specification already defines them.

Never hardcode business values.

Never put business logic in Blade.

Never put business logic directly inside Filament resources if it belongs in a reusable service.

Never bypass Policies.

Never bypass Spatie permissions.

Never trust frontend calculations.

Never modify financial records without an auditable transaction.

Never give AI unrestricted database access.

Never expose private attachments publicly.

Always use database transactions for multi-record financial/stock operations.

Always validate server-side.

Always write tests for important business rules.

Always preserve existing working code.

Before changing an existing module, inspect its current implementation.

Do not implement future phases unless explicitly instructed.

Run tests after meaningful changes.

Do not leave TODO placeholders where actual implementation is required.
```

---

# 78. Initial Laravel Commands

Create project:

```bash
composer create-project laravel/laravel mining-erp "^12.0"

cd mining-erp

php artisan key:generate
```

Install API:

```bash
php artisan install:api
```

Install permissions:

```bash
composer require spatie/laravel-permission

php artisan vendor:publish \
    --provider="Spatie\Permission\PermissionServiceProvider"
```

Install Filament according to the current Laravel 12-compatible Filament release documentation.

Storage:

```bash
php artisan storage:link
```

Run:

```bash
php artisan migrate
```

---

# 79. Recommended Environment Variables

```env
APP_NAME="Smart Mining ERP"
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mining_erp
DB_USERNAME=root
DB_PASSWORD=

QUEUE_CONNECTION=database
CACHE_STORE=database

FILESYSTEM_DISK=local

MAIL_MAILER=log

AI_PROVIDER=mock
AI_API_KEY=
AI_MODEL=
```

Production secrets must never be committed.

---

# 80. Definition of Done

A module is complete only when:

- Migration exists
- Model exists
- Relationships exist
- Validation exists
- Authorization exists
- Permissions exist
- Service/business logic exists
- Filament UI exists
- API exists where applicable
- Filters/search exist
- Translation exists
- Tests exist
- Database constraints exist
- Error handling exists
- Audit requirements are implemented
- Tests pass

A phase is complete only when all of its modules meet this definition.

---

# 81. Final Acceptance Criteria

The complete system must allow the business owner to answer:

1. How much material was produced?
2. How much material is currently available?
3. Where is the material?
4. How many trips were completed?
5. Which driver completed them?
6. Which machine worked how many hours?
7. How much fuel was consumed?
8. How much material was delivered to each factory?
9. How much has each factory/customer paid?
10. How much is outstanding?
11. How much did the business spend?
12. How much stock is available?
13. Which machines need maintenance?
14. What was today's production?
15. What was this month's production?
16. What is the estimated profit?
17. What needs attention today?

All answers must be generated from real system data.

---

# 82. Final Business Flow

The completed system must connect:

```text
EXCAVATION
    ↓
PRODUCTION
    ↓
SMALL DUMPER
    ↓
DUMPING POINT
    ↓
STOCK
    ↓
LARGE TRUCK
    ↓
FACTORY
    ↓
DELIVERY
    ↓
INVOICE / SALE
    ↓
CUSTOMER / FACTORY ACCOUNT
    ↓
PAYMENT
    ↓
LEDGER
    ↓
PROFIT & LOSS
```

Supporting systems:

```text
MACHINERY
DRIVERS
EMPLOYEES
FUEL
INVENTORY
MAINTENANCE
SUPPLIERS
EXPENSES
CASH
BANK
REPORTS
AUDIT
NOTIFICATIONS
AI
VOICE
```

---

# 83. Future Features

Architecture should remain extensible for:

- WhatsApp notifications
- SMS
- GPS tracking
- Live vehicle location
- Geofencing
- Digital weighing scale
- Weighbridge integration
- Barcode/QR
- Biometric attendance
- Advanced accounting
- Tax reports
- Customer portal
- Factory portal
- Native Android
- Native iOS
- Advanced AI analytics
- Predictive maintenance
- Production forecasting

These should not be implemented in the initial ERP foundation unless explicitly requested.

---

# 84. Final Development Principle

Build the system as a real ERP, not a collection of CRUD forms.

Every important business operation must have:

```text
Database
    ↓
Model
    ↓
Validation
    ↓
Authorization
    ↓
Business Service
    ↓
Transaction
    ↓
Audit
    ↓
API
    ↓
Admin UI
    ↓
Reports
```

AI and voice must sit above this business layer rather than replacing it.

The final product should be a secure, professional, bilingual, mobile-friendly:

**SMART MINING BUSINESS MANAGEMENT & ERP SYSTEM**

with:

**Operations + Production + Transport + Stock + Sales + Accounts + Inventory + Fuel + Machinery + HR + Reports + AI Voice Agent**
