Appearance
Auto Invoice Generation
Overview
Auto Invoice Generation is an automated system that creates invoices for subscribers on a specific day of each month. Instead of manually creating invoices for recurring services, the system runs in the background (via cron job) and automatically generates invoices based on package settings.
WHAT IS AUTO INVOICE GENERATION?
Auto Invoice Generation is an automated billing system that:
- Runs Daily - Checks for packages requiring invoices
- Date-Based Triggering - Generates invoices on specific day of month
- Automatic Creation - Creates invoices without manual intervention
- Duplicate Prevention - Skips if invoice already exists
- Scalable Processing - Handles thousands of subscribers efficiently
Perfect for: Monthly billing, recurring services, subscription management, hands-free invoicing!
📋 Table of Contents
- How Auto Invoice Works
- Configuration Requirements
- Eligibility Criteria
- Invoice Generation Process
- Duplicate Prevention
- Fee Calculation
- What Gets Generated
- What Gets Skipped
- Cron Job Setup
- Performance & Scalability
- Best Practices
How Auto Invoice Works
The Complete Flow
Every Day:
1. Check Date → 2. Find Packages with Auto Invoice Enabled →
3. Match Day of Month → 4. Find Active Subscribers →
5. Check for Duplicates → 6. Calculate Fees → 7. Generate Invoice →
8. Log ResultsDate-Based Triggering
Auto Invoice generates invoices when:
- Package has
auto_invoice_generate_status= 1 (Enabled) - Package has
auto_invoice_dateset (1-31) - Today's day matches the
auto_invoice_date
Example:
Package: Premium 10Mbps
Auto Invoice Status: Enabled
Auto Invoice Date: 5 (5th of every month)
Process:
- Jan 5: Generates invoices ✅
- Jan 6: Skips (day mismatch) ❌
- Feb 5: Generates invoices ✅
- Feb 6: Skips (day mismatch) ❌Cron Job Schedule
Runs Daily:
0 0 * * * php /path/to/artisan command:autoinvoiceWhy Daily?
- Checks every day for matching date
- Generates invoices on correct day
- Ensures no invoices are missed
- Simple and reliable
Configuration Requirements
Package Level Configuration
1. Enable Auto Invoice Generation
- Go to Package Settings
- Set "Auto Invoice Generate Status" = Enabled (1)
- This enables automatic invoice generation for this package
2. Set Auto Invoice Date
- Set "Auto Invoice Date" = Day of month (1-31)
- This determines when invoices are generated
- Example: 5 = 5th of every month
Important:
- Both settings must be configured
- If
auto_invoice_dateis empty, package is skipped - If
auto_invoice_generate_statusis disabled, package is skipped
Example Configurations
Monthly Billing on 1st:
Package: Basic 5Mbps
Auto Invoice Generate Status: Enabled (1)
Auto Invoice Date: 1
Result: Invoices generated on 1st of every monthMonthly Billing on 15th:
Package: Premium 10Mbps
Auto Invoice Generate Status: Enabled (1)
Auto Invoice Date: 15
Result: Invoices generated on 15th of every monthEnd of Month Billing:
Package: Corporate 50Mbps
Auto Invoice Generate Status: Enabled (1)
Auto Invoice Date: 28
Result: Invoices generated on 28th of every month
Note: Safe for all months (Feb has 28 days)Eligibility Criteria
Package Must Have
1. Auto Invoice Enabled
auto_invoice_generate_status= 1- Package-level setting
- Enables automatic invoice generation
2. Auto Invoice Date Set
auto_invoice_date= 1-31- Day of month when invoices are generated
- Must be set (not empty)
3. Date Match
- Today's day must match
auto_invoice_date - Example: If
auto_invoice_date= 5, only runs on 5th
Subscriber Must Have
1. Active Profile
profile_status= 2 (Active)- Only active subscribers get invoices
2. Assigned to Package
package_idmatches the package being processed- Subscriber must be on this package
3. Has Salesperson
salespersonDatamust exist- Required for invoice generation
4. Has Package Data
packageDatamust exist- Required for fee calculation
5. No Duplicate Invoice
- No invoice exists for this period
- Checked based on package duration
Invoice Generation Process
Step 1: Find Packages
Query:
Find all packages where:
- auto_invoice_generate_status = 1 (Enabled)Result: List of packages with auto invoice enabled
Step 2: Check Date Match
For Each Package:
1. Get today's day number (1-31)
2. Get package's auto_invoice_date (1-31)
3. Compare:
- If match: Continue processing
- If no match: Skip packageExample:
Today: Jan 5, 2025 (day = 5)
Package A: auto_invoice_date = 5 → Process ✅
Package B: auto_invoice_date = 10 → Skip ❌
Package C: auto_invoice_date = 15 → Skip ❌Step 3: Find Subscribers
For Each Matching Package:
Find all subscribers where:
- profile_status = 2 (Active)
- package_id = current packageChunked Processing:
- Processes 100 subscribers per batch
- Prevents memory overflow
- Handles unlimited subscribers
Step 4: Check for Duplicates
Duplicate Check Logic:
Check if invoice exists where:
- package_id = current package
- subscriber_id = current subscriber
- invoice_generated_source = 2 (System/Auto)
- created_at between [from_date, to_date]Date Range Calculation:
Based on package duration:
- Duration Type 1 (Year): from = today - X years
- Duration Type 2 (Month): from = today - X months
- Duration Type 3 (Week): from = today - X weeks
- Duration Type 4 (Day): from = today - X days
- to = today (end of day)Example:
Package: 1 Month Duration
Today: Jan 5, 2025
From: Dec 5, 2024 00:00:00
To: Jan 5, 2025 23:59:59
Check: Does invoice exist between these dates?
- Yes: Skip subscriber ❌
- No: Generate invoice ✅Step 5: Validate Relationships
Required Data:
- Subscriber data
- Package data
- Salesperson data
If Any Missing:
- Skip subscriber
- Log error
- Continue to next
Step 6: Calculate Fees
Uses Standard Activation Calculation:
preActivationCalculation() calculates:
- Package base price
- Extra fees (VAT, tax)
- Subscriber discount
- Expiration dates
- Pro-rated pricing (if applicable)
- Salesperson profitValidation:
- Discount must not exceed profit
- If discount > profit: Skip subscriber, log error
Step 7: Generate Invoice
Invoice Creation:
newInvoice() creates:
- Invoice record
- Package details
- Fee breakdown
- Expiration dates
- Generated source: 2 (System/Auto)Invoice Status:
- Default: Active (1) or Due (6)
- Not automatically paid
- Requires manual payment or auto-renewal
Step 8: Log Results
Success Log:
- Invoice ID
- Subscriber ID and username
- Package ID and name
- Billing amount
- Discount amount
- Pro-rated flag
Error Log:
- Subscriber ID
- Package ID
- Error message
- File and line number
Duplicate Prevention
How Duplicates are Prevented
1. Date Range Check
Checks if invoice already exists within package duration periodExample: 1 Month Package
Today: Jan 5, 2025
Package Duration: 1 month
Check Period: Dec 5, 2024 to Jan 5, 2025
If invoice exists in this period: Skip ✅
If no invoice exists: Generate ✅Example: 1 Year Package
Today: Jan 5, 2025
Package Duration: 1 year
Check Period: Jan 5, 2024 to Jan 5, 2025
If invoice exists in this period: Skip ✅
If no invoice exists: Generate ✅Why This Works
Prevents Multiple Invoices:
- Only one invoice per package duration
- Safe to run daily
- No duplicate invoices
Example Scenario:
Day 1 (Jan 5): Generate invoice ✅
Day 2 (Jan 6): Skip (day mismatch) ❌
Day 3 (Jan 7): Skip (day mismatch) ❌
...
Day 31 (Feb 5): Check for duplicate
- Invoice exists from Jan 5 (within 1 month)
- Skip (duplicate) ❌
Day 62 (Mar 5): Check for duplicate
- Invoice from Jan 5 is outside 1 month period
- Generate new invoice ✅Fee Calculation
Standard Activation Calculation
Uses Same Logic as Manual Activation:
- Package base price
- Extra fees (VAT, tax, etc.)
- Subscriber discount
- Pro-rated pricing (if applicable)
Example: Standard Package
Package Price: 1000 BDT
Extra Fees (VAT 15%): 150 BDT
Subscriber Discount: 100 BDT
Total: 1000 + 150 - 100 = 1050 BDTExample: Pro-Rated Package
Package Price: 1000 BDT/month
Fixed Expiry Day: 1st of month
Today: Jan 15
Remaining Days: 16 days
Pro-Rated Price: (1000 / 30) × 16 = 533.33 BDT
Extra Fees (VAT 15%): 80 BDT
Total: 533.33 + 80 = 613.33 BDTDiscount Validation
Rule: Discount cannot exceed salesperson profit
Example:
Package Price: 1000 BDT
Salesperson Cost: 900 BDT
Salesperson Profit: 100 BDT
Subscriber Discount: 150 BDT
Validation: 150 > 100 ❌
Result: Skip subscriber, log errorWhy:
- Prevents negative profit
- Protects business margins
- Ensures profitability
What Gets Generated
Invoice Details
Invoice Record:
- Subscriber ID
- Package ID
- Salesperson ID
- Invoice amount
- Discount amount
- Extra fees
- Expiration start date
- Expiration end date
- Generated source: 2 (System/Auto)
- Invoice status: Active (1) or Due (6)
Not Generated:
- Payment record (invoice is DUE)
- Ledger entries (no payment yet)
- Activation record (invoice only)
Why Invoice Only:
- Auto invoice creates billing record
- Payment happens separately (manual or auto-renewal)
- Activation happens after payment
What Gets Skipped
Package-Level Skipping
1. Auto Invoice Disabled
auto_invoice_generate_status ≠ 1
→ Package skipped entirely2. No Auto Invoice Date
auto_invoice_date is empty or null
→ Package skipped entirely3. Day Mismatch
Today's day ≠ auto_invoice_date
→ Package skipped for todaySubscriber-Level Skipping
1. Inactive Subscriber
profile_status ≠ 2 (Active)
→ Subscriber skipped2. Duplicate Invoice Exists
Invoice already exists for this period
→ Subscriber skipped
Log: "Invoice Already Exists"3. Missing Required Data
No package data or salesperson data
→ Subscriber skipped
Log: "Missing Required Data"4. Insufficient Profit Margin
Subscriber discount > salesperson profit
→ Subscriber skipped
Log: "Insufficient Profit Margin For Subscriber Discount"5. Invoice Generation Failed
System error during invoice creation
→ Subscriber skipped
Log: Error detailsCron Job Setup
Add to Crontab
Daily at Midnight:
bash
0 0 * * * cd /path/to/zal-ultra && php artisan command:autoinvoice >> /dev/null 2>&1Daily at 1 AM:
bash
0 1 * * * cd /path/to/zal-ultra && php artisan command:autoinvoice >> /dev/null 2>&1Daily at 6 AM:
bash
0 6 * * * cd /path/to/zal-ultra && php artisan command:autoinvoice >> /dev/null 2>&1Verify Cron Setup
Check Crontab:
bash
crontab -lTest Manually:
bash
cd /path/to/zal-ultra
php artisan command:autoinvoiceCheck Logs:
bash
tail -f storage/logs/laravel.log | grep "Auto Invoice"Recommended Schedule
Best Practice: Run Daily at Off-Peak Hours
0 2 * * * php artisan command:autoinvoiceWhy 2 AM:
- Low traffic time
- Minimal system load
- Invoices ready by morning
- Staff can review during business hours
Performance & Scalability
Chunked Processing
How It Works:
- Processes 100 subscribers per chunk
- Frees memory after each chunk
- Prevents memory overflow
- Handles unlimited subscribers
Example:
10,000 subscribers found
→ 100 chunks of 100 each
→ ~5 seconds per chunk
→ Total: ~8 minutesEager Loading
Optimized Queries:
- Pre-loads package data
- Pre-loads salesperson data
- Eliminates N+1 queries
- Reduces database calls by 90%+
Performance Metrics
Typical Performance:
1,000 subscribers: ~1 minute
10,000 subscribers: ~10 minutes
100,000 subscribers: ~1.5 hoursFactors Affecting Speed:
- Server CPU and RAM
- Database performance
- Number of packages
- Duplicate check complexity
Best Practices
For Admins
1. Configure Auto Invoice Strategically
✅ Enable for recurring services
✅ Set appropriate invoice date
✅ Test with small group first
❌ Don't enable for one-time services
❌ Don't set date > 28 (Feb issues)2. Choose Invoice Date Wisely
✅ 1st of month: Standard billing cycle
✅ 5th of month: After salary day
✅ 15th of month: Mid-month billing
✅ 28th of month: Safe for all months
❌ 29-31: May skip in February3. Monitor Auto Invoice Logs
✅ Check daily for errors
✅ Review skipped subscribers
✅ Verify invoice generation
✅ Track success rate4. Set Up Proper Cron Schedule
✅ Run daily at off-peak hours
✅ Monitor cron execution
✅ Check system logs
✅ Verify invoices generatedFor Resellers
1. Review Generated Invoices
✅ Check invoices daily
✅ Verify amounts correct
✅ Follow up on payments
✅ Track due invoices2. Maintain Subscriber Data
✅ Keep salesperson assigned
✅ Ensure package assigned
✅ Update subscriber status
✅ Fix data issues promptly3. Monitor Discount Settings
✅ Ensure discount ≤ profit
✅ Review discount policies
✅ Adjust if needed
✅ Avoid excessive discountsFor Subscribers
1. Expect Invoices on Schedule
✅ Know your invoice date
✅ Check for new invoices
✅ Pay before due date
✅ Contact ISP if issues2. Maintain Active Status
✅ Keep account active
✅ Avoid suspension
✅ Ensure service continuityCommon Scenarios
Scenario 1: Monthly Billing on 1st
Configuration:
Package: Premium 10Mbps
Price: 1500 BDT/month
Auto Invoice Status: Enabled
Auto Invoice Date: 1Process:
Jan 1: Generate invoices for all subscribers ✅
Jan 2-31: Skip (day mismatch) ❌
Feb 1: Generate invoices for all subscribers ✅
Feb 2-28: Skip (day mismatch) ❌
Mar 1: Generate invoices for all subscribers ✅Result:
- Invoices generated on 1st of every month
- Subscribers get consistent billing date
- Easy to track and manage
Scenario 2: Mid-Month Billing on 15th
Configuration:
Package: Basic 5Mbps
Price: 1000 BDT/month
Auto Invoice Status: Enabled
Auto Invoice Date: 15Process:
Jan 15: Generate invoices ✅
Jan 16-31: Skip ❌
Feb 1-14: Skip ❌
Feb 15: Generate invoices ✅Result:
- Invoices generated on 15th of every month
- Good for post-salary billing
- Consistent billing cycle
Scenario 3: End-of-Month Billing
Configuration:
Package: Corporate 50Mbps
Price: 5000 BDT/month
Auto Invoice Status: Enabled
Auto Invoice Date: 28Process:
Jan 28: Generate invoices ✅
Jan 29-31: Skip ❌
Feb 1-27: Skip ❌
Feb 28: Generate invoices ✅
Mar 1-27: Skip ❌
Mar 28: Generate invoices ✅Result:
- Invoices generated on 28th (safe for all months)
- Consistent end-of-month billing
- No February issues
Summary
Auto Invoice Generation is a powerful automated billing system that:
✅ Automated Processing:
- Runs daily via cron
- Date-based triggering
- No manual intervention
- Handles thousands of subscribers
✅ Smart Duplicate Prevention:
- Checks existing invoices
- Based on package duration
- Safe to run daily
- No duplicate invoices
✅ Standard Fee Calculation:
- Uses activation calculation logic
- Pro-rated pricing support
- Discount validation
- Extra fees included
✅ Scalable Performance:
- Chunked processing (100 per batch)
- Eager loading
- Memory management
- Handles 100,000+ subscribers
✅ Comprehensive Logging:
- Success tracking
- Error logging
- Statistics reporting
- Easy troubleshooting
Key Benefits:
- Reduces manual work by 100%
- Consistent billing dates
- No missed invoices
- Automatic and reliable
- Scalable to any size
Perfect for ISPs wanting hands-free monthly billing with automatic invoice generation on specific dates!
