creditHistoryService = \Yii::$app->logic->getCreditHistoryContainer()->getService(); } public function updateCredit($creditHistory) { $userProducer = Yii::$app->logic->getUserProducerContainer()->getRepository()->getOne($creditHistory->id_user, $creditHistory->id_producer); if ($userProducer) { $oldCredit = $userProducer->credit; $this->deductCredit($userProducer, $creditHistory); $this->initMeanPaymentOrder($creditHistory); $this->sendCreditLimitReminder($userProducer, $creditHistory, $oldCredit); } } public function deductCredit($userProducer, $creditHistory) { if ($this->creditHistoryService->isTypeCredit($creditHistory)) { $userProducer->credit += $creditHistory->amount; } elseif ($this->creditHistoryService->isTypeDebit($creditHistory)) { $userProducer->credit -= $creditHistory->amount; } $userProducer->save(); } public function initMeanPaymentOrder($creditHistory) { // set mean payment if ($creditHistory->id_order && $creditHistory->id_order > 0) { $order = Order::searchOne(['id' => (int)$creditHistory->id_order]); if ($order) { $paymentStatus = $order->getPaymentStatus(); if ($paymentStatus == Order::PAYMENT_PAID || $paymentStatus == Order::PAYMENT_SURPLUS) { $order->mean_payment = MeanPayment::CREDIT; $order->save(); } } } } public function sendCreditLimitReminder($userProducer, $creditHistory, $oldCredit) { $userRepository = Yii::$app->logic->getUserContainer()->getRepository(); $producerRepository = Yii::$app->logic->getProducerContainer()->getRepository(); $newCredit = $userProducer->credit; if ($this->isCreditLimitCrossed($oldCredit, $newCredit)) { $user = $userRepository->getOneById($creditHistory->id_user); $producer = $producerRepository->getOneById($creditHistory->id_producer); Yii::$app->mailer->compose( [ 'html' => 'creditLimitReminder-html', 'text' => 'creditLimitReminder-text' ], [ 'user' => $user, 'producer' => $producer, 'credit' => $newCredit ] ) ->setTo($user->email) ->setFrom(['contact@opendistrib.net' => 'Opendistrib']) ->setSubject('[Opendistrib] Seuil limite de crédit dépassé') ->send(); } } public function isCreditLimitCrossed($oldCredit, $newCredit) { $creditLimitReminder = Producer::getConfig('credit_limit_reminder'); return !is_null($creditLimitReminder) && $oldCredit > $creditLimitReminder && $newCredit <= $creditLimitReminder; } }