Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Discount Management and Application to Billing System #283

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions app/Http/Controllers/DiscountController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@


<?php

namespace App\Http\Controllers;

use App\Models\Discount;
use Illuminate\Http\Request;

class DiscountController extends Controller
{
public function index()
{
$discounts = Discount::paginate(10);
return view('discounts.index', compact('discounts'));
}

public function create()
{
return view('discounts.create');
}

public function store(Request $request)
{
$validated = $request->validate([
'code' => 'required|unique:discounts',
'name' => 'required|string',
'description' => 'nullable|string',
'type' => 'required|in:percentage,fixed',
'value' => 'required|numeric|min:0',
'currency' => 'required_if:type,fixed',
'start_date' => 'required|date',
'end_date' => 'required|date|after:start_date',
'max_uses' => 'nullable|integer|min:1',
]);

Discount::create($validated);

return redirect()->route('discounts.index')
->with('success', 'Discount created successfully');
}

public function edit(Discount $discount)
{
return view('discounts.edit', compact('discount'));
}

public function update(Request $request, Discount $discount)
{
$validated = $request->validate([
'name' => 'required|string',
'description' => 'nullable|string',
'type' => 'required|in:percentage,fixed',
'value' => 'required|numeric|min:0',
'currency' => 'required_if:type,fixed',
'start_date' => 'required|date',
'end_date' => 'required|date|after:start_date',
'max_uses' => 'nullable|integer|min:1',
'is_active' => 'boolean'
]);

$discount->update($validated);

return redirect()->route('discounts.index')
->with('success', 'Discount updated successfully');
}

public function destroy(Discount $discount)
{
$discount->delete();
return redirect()->route('discounts.index')
->with('success', 'Discount deleted successfully');
}

public function validateCode(Request $request)
{
$code = $request->input('code');
$discount = Discount::where('code', $code)->first();

if (!$discount || !$discount->isValid()) {
return response()->json(['valid' => false]);
}

return response()->json(['valid' => true, 'discount' => $discount]);
}
}
48 changes: 48 additions & 0 deletions app/Models/Discount.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Traits\HasTeam;

class Discount extends Model
{
use HasFactory;
use HasTeam;

protected $fillable = [
'code',
'name',
'description',
'type', // percentage or fixed
'value',
'currency',
'start_date',
'end_date',
'max_uses',
'used_count',
'is_active'
];

protected $casts = [
'start_date' => 'datetime',
'end_date' => 'datetime',
'is_active' => 'boolean'
];

public function invoices()
{
return $this->hasMany(Invoice::class);
}

public function isValid()
{
return $this->is_active &&
$this->start_date <= now() &&
$this->end_date >= now() &&
($this->max_uses === null || $this->used_count < $this->max_uses);
}
}
21 changes: 21 additions & 0 deletions app/Models/Invoice.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,16 @@ class Invoice extends Model
'total_amount',
'currency',
'status',
'discount_id',
'discount_amount',
'invoice_template_id',
];

protected $casts = [
'issue_date' => 'datetime',
'due_date' => 'datetime',
];

public function currency()
{
return $this->belongsTo(Currency::class, 'currency', 'code');
Expand All @@ -35,6 +42,20 @@ public function customer()
return $this->belongsTo(Customer::class);
}

public function discount()
{
return $this->belongsTo(Discount::class);
}

public function getSubtotalAttribute()
{
return $this->items->sum('total_price');
}

public function getFinalTotalAttribute()
{
return $this->subtotal - ($this->discount_amount ?? 0);
}
public function template()
{
return $this->belongsTo(InvoiceTemplate::class, 'invoice_template_id');
Expand Down
43 changes: 43 additions & 0 deletions app/Services/BillingService.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,49 @@ public function convertCurrency($amount, $fromCurrency, $toCurrency)
return $this->currencyService->convert($amount, $fromCurrency, $toCurrency);
}

public function applyDiscount(Invoice $invoice, string $discountCode)
{
$discount = Discount::where('code', $discountCode)
->where('is_active', true)
->first();

if (!$discount || !$discount->isValid()) {
return ['success' => false, 'message' => 'Invalid or expired discount code'];
}

$discountAmount = $this->calculateDiscountAmount($invoice, $discount);

$invoice->update([
'discount_id' => $discount->id,
'discount_amount' => $discountAmount,
'total_amount' => $invoice->subtotal - $discountAmount
]);

$discount->increment('used_count');

return ['success' => true, 'discount_amount' => $discountAmount];
}

private function calculateDiscountAmount(Invoice $invoice, Discount $discount)
{
if ($discount->type === 'percentage') {
return $invoice->subtotal * ($discount->value / 100);
}

if ($discount->type === 'fixed') {
if ($discount->currency !== $invoice->currency) {
return $this->convertCurrency(
$discount->value,
$discount->currency,
$invoice->currency
);
}
return $discount->value;
}

return 0;
}

public function generateInvoice(Subscription $subscription)
{
$customer = $subscription->customer;
Expand Down
43 changes: 43 additions & 0 deletions database/migrations/2024_01_10_000000_create_discounts_table.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
public function up()
{
Schema::create('discounts', function (Blueprint $table) {
$table->id();
$table->string('code')->unique();
$table->string('name');
$table->text('description')->nullable();
$table->enum('type', ['percentage', 'fixed']);
$table->decimal('value', 10, 2);
$table->string('currency')->nullable();
$table->timestamp('start_date');
$table->timestamp('end_date');
$table->integer('max_uses')->nullable();
$table->integer('used_count')->default(0);
$table->boolean('is_active')->default(true);
$table->timestamps();
});

Schema::table('invoices', function (Blueprint $table) {
$table->foreignId('discount_id')->nullable()->constrained()->onDelete('set null');
$table->decimal('discount_amount', 10, 2)->nullable();
});
}

public function down()
{
Schema::table('invoices', function (Blueprint $table) {
$table->dropForeign(['discount_id']);
$table->dropColumn(['discount_id', 'discount_amount']);
});
Schema::dropIfExists('discounts');
}
};
Loading