/** * Process invoice and insert necessary commissions for it */ public function processPayment(Invoice $invoice, InvoicePayment $payment) { $user = $invoice->getUser(); if (empty($user->aff_id)) { return; } // no affiliate id registered $aff = $this->getDi()->userTable->load($user->aff_id, false); if (!$aff || !$aff->is_affiliate) { return; } // affiliate not found // try to load second tier affiliate if ($aff->aff_id) { $aff2 = $this->getDi()->userTable->load($aff->aff_id, false); } else { $aff2 = null; } $isFirst = !$payment || $payment->isFirst(); $amount = $payment ? $payment->amount : 0; $date = $payment ? $payment->dattm : 'now'; // now calculate commissions foreach ($invoice->getItems() as $item) { $comm = $this->getDi()->affCommissionRecord; $comm->date = sqlDate($date); $comm->record_type = AffCommission::COMMISSION; $comm->invoice_id = $invoice->invoice_id; $comm->invoice_payment_id = $payment ? $payment->pk() : null; $comm->receipt_id = $payment ? $payment->receipt_id : null; $comm->product_id = $item->item_id; $comm->is_first = $isFirst; $comm->_setPayment($payment); $comm->_setInvoice($invoice); $comm2 = clone $comm; $topay = $this->calculate($invoice, $item, $aff, $isFirst ? 0 : 1, 0, $amount, $date); if ($topay) { $comm->aff_id = $aff->pk(); $comm->amount = $topay; $comm->tier = 0; $comm->_setAff($aff); $comm->insert(); } if ($aff2) { $topay2 = $this->calculate($invoice, $item, $aff, $isFirst ? 0 : 1, 1, $topay, $date); if ($topay2) { $comm2->aff_id = $aff2->pk(); $comm2->amount = $topay2; $comm2->tier = 1; $comm->_setAff($aff2); $comm2->insert(); } } } }