Skip to content

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

  1. How Auto Invoice Works
  2. Configuration Requirements
  3. Eligibility Criteria
  4. Invoice Generation Process
  5. Duplicate Prevention
  6. Fee Calculation
  7. What Gets Generated
  8. What Gets Skipped
  9. Cron Job Setup
  10. Performance & Scalability
  11. 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 Results

Date-Based Triggering

Auto Invoice generates invoices when:

  • Package has auto_invoice_generate_status = 1 (Enabled)
  • Package has auto_invoice_date set (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:autoinvoice

Why 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_date is empty, package is skipped
  • If auto_invoice_generate_status is 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 month

Monthly Billing on 15th:

Package: Premium 10Mbps
Auto Invoice Generate Status: Enabled (1)
Auto Invoice Date: 15
Result: Invoices generated on 15th of every month

End 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_id matches the package being processed
  • Subscriber must be on this package

3. Has Salesperson

  • salespersonData must exist
  • Required for invoice generation

4. Has Package Data

  • packageData must 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 package

Example:

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 package

Chunked 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 profit

Validation:

  • 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 period

Example: 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 BDT

Example: 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 BDT

Discount 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 error

Why:

  • 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 entirely

2. No Auto Invoice Date

auto_invoice_date is empty or null
→ Package skipped entirely

3. Day Mismatch

Today's day ≠ auto_invoice_date
→ Package skipped for today

Subscriber-Level Skipping

1. Inactive Subscriber

profile_status ≠ 2 (Active)
→ Subscriber skipped

2. 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 details

Cron Job Setup

Add to Crontab

Daily at Midnight:

bash
0 0 * * * cd /path/to/zal-ultra && php artisan command:autoinvoice >> /dev/null 2>&1

Daily at 1 AM:

bash
0 1 * * * cd /path/to/zal-ultra && php artisan command:autoinvoice >> /dev/null 2>&1

Daily at 6 AM:

bash
0 6 * * * cd /path/to/zal-ultra && php artisan command:autoinvoice >> /dev/null 2>&1

Verify Cron Setup

Check Crontab:

bash
crontab -l

Test Manually:

bash
cd /path/to/zal-ultra
php artisan command:autoinvoice

Check Logs:

bash
tail -f storage/logs/laravel.log | grep "Auto Invoice"

Best Practice: Run Daily at Off-Peak Hours

0 2 * * * php artisan command:autoinvoice

Why 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 minutes

Eager 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 hours

Factors 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 February

3. Monitor Auto Invoice Logs

✅ Check daily for errors
✅ Review skipped subscribers
✅ Verify invoice generation
✅ Track success rate

4. Set Up Proper Cron Schedule

✅ Run daily at off-peak hours
✅ Monitor cron execution
✅ Check system logs
✅ Verify invoices generated

For Resellers

1. Review Generated Invoices

✅ Check invoices daily
✅ Verify amounts correct
✅ Follow up on payments
✅ Track due invoices

2. Maintain Subscriber Data

✅ Keep salesperson assigned
✅ Ensure package assigned
✅ Update subscriber status
✅ Fix data issues promptly

3. Monitor Discount Settings

✅ Ensure discount ≤ profit
✅ Review discount policies
✅ Adjust if needed
✅ Avoid excessive discounts

For Subscribers

1. Expect Invoices on Schedule

✅ Know your invoice date
✅ Check for new invoices
✅ Pay before due date
✅ Contact ISP if issues

2. Maintain Active Status

✅ Keep account active
✅ Avoid suspension
✅ Ensure service continuity

Common Scenarios

Scenario 1: Monthly Billing on 1st

Configuration:

Package: Premium 10Mbps
Price: 1500 BDT/month
Auto Invoice Status: Enabled
Auto Invoice Date: 1

Process:

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: 15

Process:

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: 28

Process:

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!

www.onezeroart.com