Commit c90ed983 authored by Mahmoud Aglan's avatar Mahmoud Aglan

Fix fee calculation: use payments table (gross income - refunds)

Instead of reading invoices.total_amount, now queries the payments table:
- Sums inbound/confirmed payments (gross income)
- Subtracts inbound/refunded payments (refunds)
- Applies plan.platform_fee_percent on the net feeable amount
Co-Authored-By: 's avatarClaude Opus 4.6 <noreply@anthropic.com>
parent 4200c04a
......@@ -32,25 +32,33 @@ public function pullFeesForDate(Instance $instance, string $date): ?PlatformFee
config(["database.connections.instance_{$instance->id}" => $config]);
$result = DB::connection("instance_{$instance->id}")
->table('invoices')
->whereDate('created_at', $date)
->where('status', '!=', 'cancelled')
->selectRaw('COUNT(*) as count, COALESCE(SUM(total_amount), 0) as total')
$conn = DB::connection("instance_{$instance->id}");
$result = $conn->table('payments')
->whereNull('deleted_at')
->where('direction', 'inbound')
->whereDate('payment_date', $date)
->selectRaw("
COUNT(*) FILTER (WHERE status = 'confirmed') as inbound_count,
COALESCE(SUM(amount) FILTER (WHERE status = 'confirmed'), 0) as inbound_total,
COALESCE(SUM(amount) FILTER (WHERE status = 'refunded'), 0) as refunded_total
")
->first();
DB::disconnect("instance_{$instance->id}");
$totalAmount = (int) $result->total;
$grossIncome = (int) $result->inbound_total;
$refunds = (int) $result->refunded_total;
$feeableAmount = max(0, $grossIncome - $refunds);
$feePercent = $instance->plan->platform_fee_percent ?? 0;
$feeAmount = (int) round($totalAmount * $feePercent / 100);
$feeAmount = (int) round($feeableAmount * $feePercent / 100);
return PlatformFee::updateOrCreate(
['instance_id' => $instance->id, 'date' => $date, 'source' => 'pull'],
[
'total_transactions_amount' => $totalAmount,
'total_transactions_amount' => $feeableAmount,
'fee_amount' => $feeAmount,
'transaction_count' => (int) $result->count,
'transaction_count' => (int) $result->inbound_count,
'verified' => true,
]
);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment