2021-10-04 16:24:39 +00:00
< ? php
namespace App\Traits ;
2022-03-30 10:32:40 +00:00
use App\Events\InsuranceEvent ;
2022-02-08 08:36:06 +00:00
use App\Exceptions\AppException ;
2022-01-28 18:53:04 +00:00
use App\HealthCareSheetType ;
2022-03-30 10:32:40 +00:00
use App\InsuranceInvoiceState ;
2022-02-08 08:36:06 +00:00
use App\InsuranceState ;
2021-11-09 08:30:31 +00:00
use App\InsuranceSubscriptionAffiliation ;
use App\InsuranceSubscriptionState ;
2022-02-08 08:36:06 +00:00
use App\Models\AgentPlus ;
2021-10-27 12:48:07 +00:00
use App\Models\CountriesCurrency ;
2021-10-19 14:35:01 +00:00
use App\Models\Country ;
2021-11-12 05:08:03 +00:00
use App\Models\NhHavingRight ;
2022-01-25 23:16:26 +00:00
use App\Models\NhHealthCareSheet ;
use App\Models\NhInfosHealthCareSheets ;
2021-11-09 08:30:31 +00:00
use App\Models\NhInsurance ;
use App\Models\NhInsurancesHavingRight ;
2022-03-29 19:20:43 +00:00
use App\Models\NhInsurancesInvoice ;
2022-05-02 07:03:42 +00:00
use App\Models\NhInsurancesPayment ;
2021-11-09 08:30:31 +00:00
use App\Models\NhInsurancesSubscription ;
2022-05-02 07:03:42 +00:00
use App\Models\NhInvoice ;
2021-11-09 08:30:31 +00:00
use App\Models\NhMonthsPricesGrid ;
2022-02-17 14:05:47 +00:00
use App\Models\NhNetworksConfig ;
2022-02-08 08:36:06 +00:00
use App\Models\User ;
2021-10-19 14:35:01 +00:00
use Brick\Money\Context\AutoContext ;
use Brick\Money\Money ;
2022-03-30 10:32:40 +00:00
use Carbon\Carbon ;
2021-11-04 17:07:15 +00:00
use DateTime ;
use DateTimeZone ;
2022-02-08 08:36:06 +00:00
use Exception ;
2021-11-09 08:30:31 +00:00
use Illuminate\Database\Eloquent\Collection ;
use Illuminate\Http\Request ;
2021-10-21 12:07:35 +00:00
use Illuminate\Http\UploadedFile ;
2021-10-19 14:35:01 +00:00
use Illuminate\Support\Facades\DB ;
2022-03-30 10:32:40 +00:00
use Illuminate\Support\Facades\Event ;
2022-01-28 18:53:04 +00:00
use Illuminate\Support\Facades\Log ;
2021-10-29 15:52:10 +00:00
use Illuminate\Support\Facades\Storage ;
2021-10-25 13:56:42 +00:00
use Illuminate\Support\Str ;
2022-02-17 14:05:47 +00:00
use stdClass ;
2022-05-02 07:03:42 +00:00
use function Clue\StreamFilter\fun ;
2021-10-19 14:35:01 +00:00
2021-10-04 16:24:39 +00:00
trait Helper
{
2022-03-28 23:49:57 +00:00
public function addDaysToDateTime ( $datetime , $days )
{
return DateTime :: createFromFormat ( 'Y-m-d H:i:s' , $datetime ) -> modify ( '+' . $days . 'days' );
}
public function addMonthsToDateTime ( $datetime , $months )
{
return DateTime :: createFromFormat ( 'Y-m-d H:i:s' , $datetime ) -> modify ( '+' . $months . 'months' );
}
2021-11-09 08:30:31 +00:00
public function getNetworkCurrency ( $networkId )
{
$currency = collect ( DB :: select ( ' SELECT cu . code FROM networks n INNER JOIN countries c ON c . id = n . country_id INNER JOIN currencies cu ON cu . id = c . idCurrency
WHERE n . id = : id ', [' id ' => $networkId ])) -> first ();
return isset ( $currency ) ? $currency -> code : 'XAF' ;
}
2021-10-19 14:35:01 +00:00
public function toMoneyWithNetwork ( $amount , $id_network )
{
$currency = collect ( DB :: select ( ' SELECT cu . code FROM networks n INNER JOIN countries c ON c . id = n . country_id INNER JOIN currencies cu ON cu . id = c . idCurrency
WHERE n . id = : id ', [' id ' => $id_network ])) -> first ();
$money = Money :: of ( round ( $amount , 2 ), $currency ? $currency -> code : 'XAF' , new AutoContext ());
return $money -> formatTo ( app () -> getLocale ());
}
public function toMoney ( $amount , $id_country )
{
$country = Country :: findOrFail ( $id_country );
$money = Money :: of ( round ( $amount , 2 ), $country -> currency -> code , new AutoContext ());
return $money -> formatTo ( app () -> getLocale ());
}
public function toMoneyWithCurrencyCode ( $amount , $currency_code )
{
$money = Money :: of ( round ( $amount , 2 ), $currency_code , new AutoContext ());
return $money -> formatTo ( app () -> getLocale ());
}
2021-10-04 16:24:39 +00:00
2021-10-21 12:07:35 +00:00
public function uploadImage ( UploadedFile $file , $imageCode , $folderName )
{
$original_filename = $file -> getClientOriginalName ();
$original_filename_arr = explode ( '.' , $original_filename );
$file_ext = end ( $original_filename_arr );
2021-10-25 13:56:42 +00:00
$image = $imageCode . '-' . Str :: uuid () . '.' . $file_ext ;
2021-10-21 12:07:35 +00:00
//Check if the directory already exists.
$directoryName = './' . $folderName ;
if ( ! is_dir ( $directoryName )) {
//Directory does not exist, so lets create it.
mkdir ( $directoryName , 0755 );
}
2021-11-09 08:30:31 +00:00
$compressedImage = compressImage ( $file , './' . $folderName . '/' . $image , 70 );
2021-10-21 12:07:35 +00:00
if ( $compressedImage ) {
return $image ;
} else {
return $this -> errorResponse ( trans ( 'errors.compression_failed' ));
}
}
2021-10-27 12:48:07 +00:00
// Obtenir l'heure en fonction du pays de l'utilisateur
public function getCurrentTime ( $id_country )
{
$country = CountriesCurrency :: find ( $id_country );
$country_code = isset ( $country ) ? $country -> code_country : 'GA' ;
2021-12-22 09:01:55 +00:00
$timezone = DateTimeZone :: listIdentifiers ( DateTimeZone :: PER_COUNTRY , $country_code );
$date = ( sizeof ( $timezone ) > 0 ) ? new DateTime ( 'now' , new DateTimeZone ( $timezone [ 0 ])) : new DateTime ();
2021-10-27 12:48:07 +00:00
return $date -> format ( 'Y-m-d H:i:s' );
}
// Obtenir l'heure en fonction du code du pays de l'utilisateur
public function getCurrentTimeByCountryCode ( $country_code = 'GA' )
{
2021-11-04 17:07:15 +00:00
$timezone = DateTimeZone :: listIdentifiers ( DateTimeZone :: PER_COUNTRY , $country_code );
2021-12-22 09:01:55 +00:00
$date = ( sizeof ( $timezone ) > 0 ) ? new DateTime ( 'now' , new DateTimeZone ( $timezone [ 0 ])) : new DateTime ();
2021-10-27 12:48:07 +00:00
return $date -> format ( 'Y-m-d H:i:s' );
}
2021-11-09 08:30:31 +00:00
// Caculer le montant de la prime d'un ayant droit ou beneficiaire
2021-11-12 05:08:03 +00:00
public function calculateBeneficiaryBonusAmount ( NhHavingRight $beneficiary , Collection $yearsPricesGrid ,
NhMonthsPricesGrid $monthPrice )
2021-11-09 08:30:31 +00:00
{
$bonus = 0 ;
if ( $beneficiary -> affiliation == 'CHILD' ) {
$age = date_diff ( date_create ( $beneficiary -> birthdate ), date_create ( 'now' )) -> y ;
$levels = $yearsPricesGrid -> filter ( function ( $level ) use ( $age ) {
return $level -> min_age <= $age && $level -> max_age >= $age ;
});
foreach ( $levels as $level ) {
2022-03-28 23:49:57 +00:00
$bonus += round ((( 100 + $level -> markup_percentage ) * $monthPrice -> min_amount / 100 ));
2021-11-09 08:30:31 +00:00
}
} else {
$bonus = $monthPrice -> min_amount ;
}
return $bonus ;
}
public function storeBeneficiariesAndGetBonus ( NhInsurancesSubscription $subscription , Request $request ,
2022-01-28 18:53:04 +00:00
$networkConfig , NhMonthsPricesGrid $monthPrice , string $datetime )
2021-11-09 08:30:31 +00:00
{
$subscription -> state = InsuranceSubscriptionState :: UNDER_VALIDATION ;
$beneficiariesBonus = 0 ;
2021-11-19 16:07:42 +00:00
foreach ( $request -> input ( 'beneficiaries' , []) as $b ) {
2021-11-12 05:08:03 +00:00
$beneficiary = new NhHavingRight ( $b );
2021-11-09 08:30:31 +00:00
$beneficiary -> bonus_amount = $this -> calculateBeneficiaryBonusAmount ( $beneficiary , $networkConfig -> yearsPricesGrid , $monthPrice );
$beneficiariesBonus += $beneficiary -> bonus_amount ;
if ( $beneficiary -> affiliation == InsuranceSubscriptionAffiliation :: CHILD ) {
$beneficiary -> marriage_certificate_doc = null ;
$beneficiary -> id_document_type = null ;
$beneficiary -> id_document_back = null ;
$beneficiary -> id_document_front = null ;
} else {
$beneficiary -> justice_doc = null ;
$beneficiary -> birthdate_proof_doc = null ;
$beneficiary -> birthdate_proof = null ;
}
$beneficiary -> created_at = $beneficiary -> updated_at = $datetime ;
$beneficiary -> save ();
2021-11-12 05:08:03 +00:00
NhInsurancesHavingRight :: create ([
'insurance_subscription_id' => $subscription -> id ,
'having_right_id' => $beneficiary -> id ,
]);
2021-11-09 08:30:31 +00:00
}
return $beneficiariesBonus ;
}
public function generateSubscriptionID () : string
{
do {
$code = generateTransactionCode ();
$codeCorrect = NhInsurancesSubscription :: where ( 'insurance_subscription_id' , $code ) -> count () < 0 ;
} while ( $codeCorrect );
return $code ;
}
2022-01-25 23:16:26 +00:00
public function generateInvoiceID ( $agent_code )
{
return date ( 'd' ) . '/' . date ( 'm' ) . '/' . date ( 'Y' ) . '/' . $agent_code ;
}
2022-02-08 08:36:06 +00:00
/**
* @ throws AppException
*/
public function insuranceVerification ( NhInsurance $insurance )
{
if ( $insurance -> state != InsuranceState :: PAID ) {
throw new AppException ( __ ( 'errors.insurance_expired' , [ 'state' => mb_strtolower ( trans ( 'states.' . $insurance -> state ), 'UTF-8' )]), 400 );
}
}
/**
* @ throws AppException
*/
public function latestSubscriptionVerification ( $network_id , $user_id )
{
$latestSubscription = NhInsurancesSubscription :: where ( 'network_id' , $network_id ) -> where ( 'user_id' , $user_id )
-> whereIn ( 'state' , [ InsuranceSubscriptionState :: UNDER_VALIDATION , InsuranceSubscriptionState :: AWAITING_FURTHER_INFORMATION ]) -> orderBy ( 'created_at' , 'DESC' ) -> first ();
if ( isset ( $latestSubscription )) {
throw new AppException ( trans ( 'errors.subscription_cannot_be_submitted' , [ 'state' => mb_strtolower ( trans ( 'states.' . $latestSubscription -> state ), 'UTF-8' )]));
}
}
/**
* @ throws AppException
*/
2022-04-14 14:21:57 +00:00
public function userIdentificationVerification ( User $user )
2022-02-08 08:36:06 +00:00
{
if ( ! isset ( $user -> identification ) || $user -> identification -> status == 0 )
throw new AppException ( trans ( 'errors.user_identification_required' ));
2022-04-14 14:21:57 +00:00
// if (!checkPassword($password, $user->encrypted_password, $user->salt))
// throw new AppException(trans('messages.incorrect_user_password'));
2022-02-08 08:36:06 +00:00
}
/**
* @ throws AppException
*/
public function agentCredentialsVerification ( $network_agent_id , $password )
{
$agent = AgentPlus :: where ( 'network_agent_id' , $network_agent_id ) -> first ();
if ( ! checkPassword ( $password , $agent -> encrypted_password , $agent -> salt ))
throw new AppException ( trans ( 'messages.incorrect_user_password' ));
}
2022-02-17 14:05:47 +00:00
public function calculateInsuranceAmounts ( NhHealthCareSheet $sheet )
{
$insuranceAmount = 0 ;
$insuredAmount = 0 ;
if ( $sheet -> type == HealthCareSheetType :: CONSULTATION ) {
$sum = current ( DB :: select ( " SELECT SUM(moderator_ticket) as moderator_ticket , SUM(insurance_amount) as insurance_amount FROM nh_performances p INNER JOIN
nh_health_care_sheets_performances hp ON p . id = hp . performance_id WHERE hp . sheet_id = : sheet_id LIMIT 1 " , ['sheet_id' => $sheet->id ]));
if ( isset ( $sum )) {
$insuredAmount += $sum -> moderator_ticket ;
$insuranceAmount += $sum -> insurance_amount ;
}
} else {
$sum = current ( DB :: select ( " SELECT SUM(insured_paid_amount) as insured_paid_amount , SUM(insurer_paid_amount) as insurer_paid_amount FROM nh_medical_prescriptions p INNER JOIN
nh_health_care_sheets_prescriptions hp ON p . id = hp . prescription_id WHERE hp . sheet_id = : sheet_id LIMIT 1 " , ['sheet_id' => $sheet->id ]));
if ( isset ( $sum )) {
$insuredAmount += $sum -> insured_paid_amount ;
$insuranceAmount += $sum -> insurer_paid_amount ;
}
$sum = current ( DB :: select ( " SELECT SUM(insured_paid_amount) as insured_paid_amount , SUM(insurer_paid_amount) as insurer_paid_amount FROM nh_exams e INNER JOIN
nh_health_care_sheets_exams he ON e . id = he . exam_id WHERE he . sheet_id = : sheet_id LIMIT 1 " , ['sheet_id' => $sheet->id ]));
if ( isset ( $sum )) {
$insuredAmount += $sum -> insured_paid_amount ;
$insuranceAmount += $sum -> insurer_paid_amount ;
}
}
$sheet -> insurance_amount = $insuranceAmount ;
$sheet -> insured_amount = $insuredAmount ;
$sheet -> save ();
}
2022-03-28 23:49:57 +00:00
public function generateSheetID () : string
{
do {
$code = generateTransactionCode ();
$codeCorrect = NhHealthCareSheet :: where ( 'health_care_sheet_id' , $code ) -> count () < 0 ;
} while ( $codeCorrect );
return $code ;
}
public function getConfigInsuranceParts ( NhNetworksConfig $nhConfig , $care_condition ) : stdClass
{
$insuredPart = 0 ;
$insurerPart = 0 ;
switch ( $care_condition ) {
case 'CURRENT_AFFECTION' :
$insurerPart = $nhConfig -> current_affection_percentage_insurer / 100 ;
$insuredPart = $nhConfig -> current_affection_percentage_insured / 100 ;
break ;
case 'LONG_TERM_AFFECTION' :
$insurerPart = $nhConfig -> long_term_affection_percentage_insurer / 100 ;
$insuredPart = $nhConfig -> long_term_affection_percentage_insured / 100 ;
break ;
case 'EXONERATION' :
$insurerPart = $nhConfig -> exoneration_percentage_insurer / 100 ;
$insuredPart = $nhConfig -> exoneration_percentage_insured / 100 ;
break ;
}
$result = new stdClass ();
$result -> insured_part = $insuredPart ;
$result -> insurer_part = $insurerPart ;
return $result ;
}
/**
* @ throws AppException
*/
// Verification de la limite de couverture
public function verifyInsuranceCoverageAmount ( NhNetworksConfig $nhConfig , NhInsurance $insurance , NhHealthCareSheet $sheet , NhHavingRight $beneficiary = null ,
2022-03-30 10:32:40 +00:00
$currency_code = 'XAF' , $currentInsuranceAmount = 0 ) // Current Insurance Amount en cas de mise à jour de la feuille de soins pour ne pas prendre en compte la couverture deja affecté
2022-03-28 23:49:57 +00:00
{
$insurance_coverage_amount = isset ( $beneficiary ) ? $beneficiary -> insurance_coverage_amount : $insurance -> insurance_coverage_amount ;
$insurance_amount = $sheet -> insurance_amount ;
$monthPrice = $insurance -> monthsGrid ;
if ( ! isset ( $monthPrice ))
throw new AppException ( trans ( 'errors.month_price_grid_not_found' ));
if ( ! $nhConfig -> family_coverage_sharing ) {
$total_insurance_amount = $insurance_coverage_amount + $insurance_amount - $currentInsuranceAmount ;
if ( $total_insurance_amount > $monthPrice -> max_insurance_coverage_amount ) {
DB :: rollBack ();
throw new AppException ( trans ( 'errors.insurance_coverage_amount_exceeded' , [
'consumption' => $this -> toMoneyWithCurrencyCode ( $insurance_coverage_amount , $currency_code ),
'remaining' => $this -> toMoneyWithCurrencyCode ( $monthPrice -> max_insurance_coverage_amount - $insurance_coverage_amount , $currency_code ),
]));
}
} else {
// Montant de l'assurance deja consomé à date
$family_consumed_amount = $insurance -> insurance_coverage_amount ;
foreach ( $insurance -> beneficiaries as $b ) {
$family_consumed_amount += $b -> insurance_coverage_amount ;
}
$total_insurance_amount = $family_consumed_amount + $insurance_amount - $currentInsuranceAmount ;
$family_limit_amount = $monthPrice -> max_insurance_coverage_amount * ( $insurance -> number_of_beneficiaries + 1 );
if ( $total_insurance_amount > $family_limit_amount ) {
DB :: rollBack ();
throw new AppException ( trans ( 'errors.insurance_coverage_amount_exceeded' , [
'consumption' => $this -> toMoneyWithCurrencyCode ( $family_consumed_amount , $currency_code ),
'remaining' => $this -> toMoneyWithCurrencyCode ( $family_limit_amount - $family_consumed_amount , $currency_code ),
]));
}
}
}
public function updateInsuranceCoverageAmount ( NhHealthCareSheet $sheet , NhInsurance $insurance , $datetime ,
2022-03-30 10:32:40 +00:00
NhHavingRight $beneficiary = null , $currentInsuranceAmount = 0 ) : void
2022-03-28 23:49:57 +00:00
{ // Current Insurance Amount en cas de mise à jour de la feuille de soins pour ne pas prendre en compte la couverture deja affecté)
$sheet -> insurance_consumed_at = $datetime ;
if ( ! empty ( $beneficiary )) {
$beneficiary -> insurance_coverage_amount += ( $sheet -> insurance_amount - $currentInsuranceAmount );
$beneficiary -> save ();
} else {
$insurance -> insurance_coverage_amount += ( $sheet -> insurance_amount - $currentInsuranceAmount );
$insurance -> save ();
}
$sheet -> save ();
}
2022-03-29 19:20:43 +00:00
public function generateInsuranceInvoiceID () : string
{
do {
2022-04-01 16:10:44 +00:00
$code = generateTransactionCode ( 8 );
2022-03-29 19:20:43 +00:00
$codeCorrect = NhInsurancesInvoice :: where ( 'invoice_id' , $code ) -> count () < 0 ;
} while ( $codeCorrect );
return $code ;
}
2022-05-02 07:03:42 +00:00
public function generateID ( $table , $column , $length = 12 ) : string
{
do {
$code = generateTransactionCode ( $length );
$codeCorrect = count ( DB :: select ( " SELECT * FROM $table WHERE $column = :code " , [ 'code' => $code ])) < 0 ;
} while ( $codeCorrect );
return $code ;
}
2022-03-30 10:32:40 +00:00
// Generer les factures des assurances à payer
2022-05-02 07:03:42 +00:00
// public function generateInsurancesInvoices(): void
// {
// $insurances = NhInsurance::with('monthsGrid')->whereIn('state', [InsuranceState::UNDER_ACTIVATION, InsuranceState::UNDER_ADDING_BENEFICIARY, InsuranceState::UNDER_RENEW,
// InsuranceState::PARTIALLY_PAID, InsuranceState::SUSPENDED])
// ->whereColumn('paid_deadlines', '<', 'deadlines')->get();
//
// foreach ($insurances as $i) {
// $lastInvoice = NhInsurancesInvoice::where('insurance_id', $i->id)->orderBy('id', 'DESC')->first();
// if (isset($lastInvoice) && $lastInvoice->deadline_number < $i->deadlines) {
// if (in_array($i->monthsGrid->payment_period, ['DAILY', 'MONTHLY'])) {
// // Si le paiement est mensuel, se rassurer que cela fait deja 1 mois
// if ($i->monthsGrid->payment_period == 'MONTHLY' && $lastInvoice->created_at->diff(date('Y-m-d'))->m < 1) {
// continue;
// }
//
// $networkConfig = NhNetworksConfig::where('network_id', $i->network_id)->first();
// if (!isset($networkConfig) || $networkConfig->configWallet->type != 'ilink_sante') {
// Log::error("Insurance Invoice generated " . trans('errors.nano_health_not_activated'));
// continue;
// }
//
// $current_deadline_number = $lastInvoice->deadline_number + 1;
// $invoice = NhInsurancesInvoice::create([
// 'invoice_id' => $this->generateInsuranceInvoiceID(),
// 'insurance_id' => $i->id,
// 'subscription_id' => $lastInvoice->subscription_id ?? null,
// 'amount' => $current_deadline_number == $i->deadlines ? $i->amount_last_payment : $i->amount_per_split,
// 'next_payment_deadline' => Carbon::now()->addDays(10), // 1 semaines + 3 jours
// 'next_payment_reminder' => Carbon::now()->addDays(7),
// 'state' => InsuranceInvoiceState::UNPAID,
// 'reason' => $lastInvoice->reason,
// 'deadline_number' => $current_deadline_number
// ]);
// $currency = $this->getNetworkCurrency($invoice->insurance->network_id);
// // Envoyer le mail
// Event::dispatch(new InsuranceEvent($invoice->insurance, trans('messages.insurance_invoice_generated_title'),
// trans('messages.insurance_invoice_generated_mail', ['name' => $invoice->insurance->user->lastname, 'insured_id' => $invoice->insurance->insured_id,
// 'bonus_amount' => $this->toMoneyWithCurrencyCode($invoice->insurance->bonus_amount, $currency), 'total_bonus_amount' => $this->toMoneyWithCurrencyCode($invoice->insurance->total_bonus_amount, $currency), 'number_of_beneficiaries' => $invoice->insurance->number_of_beneficiaries,
// 'gender' => trans('states.' . $invoice->insurance->user->identification->gender), 'insurance_name' => $invoice->insurance->network->name, 'months' => $invoice->insurance->monthsGrid->number_of_months, 'invoice_id' => $invoice->invoice_id,
// 'amount' => $this->toMoneyWithCurrencyCode($invoice->amount, $currency), 'remains_deadlines' => $invoice->insurance->deadlines - $invoice->insurance->paid_deadlines - 1,
// 'payment_period' => trans('states.' . $invoice->insurance->monthsGrid->payment_period), 'reason' => trans('states.' . $invoice->reason), 'title' => trans('messages.insurance_invoice_generated_mail_title', ['deadline' => $current_deadline_number]), 'object' => trans('messages.the_invoice'),
// 'deadlines' => $invoice->insurance->deadlines, 'amount_per_split' => $this->toMoneyWithCurrencyCode($invoice->insurance->amount_per_split, $currency), 'amount_last_payment' => $this->toMoneyWithCurrencyCode($invoice->insurance->amount_last_payment, $currency),
// 'waiting_days' => empty($invoice->insurance->monthsGrid->waiting_period_days) ? trans('messages.none') : trans('messages.n_days', ['n' => $invoice->insurance->monthsGrid->waiting_period_days]),
// 'start_at' => $invoice->insurance->start_at
// ])));
// }
// }
// }
// }
// Mettre a jour les factures chaque jour
public function updateInsurancesInvoices () : void
2022-03-30 10:32:40 +00:00
{
2022-05-02 07:03:42 +00:00
$invoices = NhInsurancesInvoice :: whereHas ( 'insurance' ) -> with ([ 'insurance.monthsGrid' ]) -> where ( 'state' , InsuranceInvoiceState :: UNPAID )
-> whereDate ( 'next_payment_reminder' , date ( 'Y-m-d' )) -> get ();
foreach ( $invoices as $invoice ) {
if ( in_array ( $invoice -> insurance -> monthsGrid -> payment_period , [ 'DAILY' , 'MONTHLY' ])) {
// Si le paiement est mensuel, se rassurer que cela fait deja 1 mois
if ( $invoice -> monthsGrid -> payment_period == 'MONTHLY' && date_create ( $invoice -> next_payment_deadline ) -> diff ( new DateTime ()) -> m < 1 ) {
continue ;
2022-03-30 10:32:40 +00:00
}
2022-05-02 07:03:42 +00:00
$networkConfig = NhNetworksConfig :: where ( 'network_id' , $invoice -> insurance -> network_id ) -> first ();
if ( ! isset ( $networkConfig ) || $networkConfig -> configWallet -> type != 'ilink_sante' ) {
continue ;
}
$deadline = $invoice -> next_payment_deadline ;
$invoice -> next_payment_deadlines_to_paid ++ ;
$invoice -> next_payment_deadline = $this -> addDaysToDateTime ( $deadline , $networkConfig -> reminder_delay_days + $networkConfig -> suspension_delay_days_after_reminder ); // 1 semaines + 3 jours
$invoice -> next_payment_reminder = $this -> addDaysToDateTime ( $deadline , $networkConfig -> reminder_delay_days );
$invoice -> save ();
2022-03-30 10:32:40 +00:00
}
}
}
public function reminderInsurancesInvoices () : void
{
$invoices = NhInsurancesInvoice :: with ([ 'insurance' ]) -> where ( 'state' , InsuranceInvoiceState :: UNPAID )
2022-05-02 07:03:42 +00:00
-> whereDate ( 'next_payment_reminder' , date ( 'Y-m-d' )) -> get ();
2022-03-30 10:32:40 +00:00
foreach ( $invoices as $invoice ) {
// Reminders
$currency = $this -> getNetworkCurrency ( $invoice -> insurance -> network_id );
2022-05-02 07:03:42 +00:00
$total_paid_amount = NhInsurancesPayment :: where ( 'invoice_id' , $invoice -> id ) -> sum ( 'amount' );
2022-03-30 10:32:40 +00:00
Event :: dispatch ( new InsuranceEvent ( $invoice -> insurance , trans ( 'messages.insurance_payment_reminder' ),
2022-04-01 16:10:44 +00:00
trans ( 'messages.insurance_invoice_generated_mail' , [ 'name' => $invoice -> insurance -> user -> lastname , 'insured_id' => $invoice -> insurance -> insured_id ,
2022-03-30 10:32:40 +00:00
'bonus_amount' => $this -> toMoneyWithCurrencyCode ( $invoice -> insurance -> bonus_amount , $currency ), 'total_bonus_amount' => $this -> toMoneyWithCurrencyCode ( $invoice -> insurance -> total_bonus_amount , $currency ), 'number_of_beneficiaries' => $invoice -> insurance -> number_of_beneficiaries ,
'gender' => trans ( 'states.' . $invoice -> insurance -> user -> identification -> gender ), 'insurance_name' => $invoice -> insurance -> network -> name , 'months' => $invoice -> insurance -> monthsGrid -> number_of_months , 'invoice_id' => $invoice -> invoice_id ,
2022-05-02 07:03:42 +00:00
'amount' => $this -> toMoneyWithCurrencyCode ( $invoice -> amount , $currency ), 'object' => trans ( 'messages.the_payment' ),
2022-04-01 16:10:44 +00:00
'payment_period' => trans ( 'states.' . $invoice -> insurance -> monthsGrid -> payment_period ), 'reason' => trans ( 'states.' . $invoice -> reason ), 'title' => trans ( 'messages.insurance_payment_reminder_title' , [ 'invoice_id' => $invoice -> invoice_id , 'n_reminder' => 7 , 'n_suspension' => 3 ]),
2022-05-02 07:03:42 +00:00
'paid_amount' => $this -> toMoneyWithCurrencyCode ( $total_paid_amount , $currency ), 'remains_amount' => $this -> toMoneyWithCurrencyCode ( $invoice -> amount - $total_paid_amount , $currency ),
2022-03-31 11:57:44 +00:00
'waiting_days' => empty ( $invoice -> insurance -> monthsGrid -> waiting_period_days ) ? trans ( 'messages.none' ) : trans ( 'messages.n_days' , [ 'n' => $invoice -> insurance -> monthsGrid -> waiting_period_days ]),
'start_at' => $invoice -> insurance -> start_at
])));
2022-03-30 10:32:40 +00:00
}
2022-05-02 07:03:42 +00:00
$invoices = NhInsurancesInvoice :: whereHas ( 'insurance' , function ( $q ) {
return $q -> whereNotIn ( 'state' , [ InsuranceState :: STOPPED , InsuranceState :: EXPIRED ]);
}) -> with ([ 'insurance' ]) -> where ( 'state' , InsuranceInvoiceState :: UNPAID )
-> whereDate ( 'next_payment_deadline' , Carbon :: now () -> subDay ()) -> get ();
2022-03-30 10:32:40 +00:00
2022-03-31 11:57:44 +00:00
foreach ( $invoices as $invoice ) {
$invoice -> insurance -> update ([
'state' => InsuranceState :: SUSPENDED
]);
}
2022-03-30 10:32:40 +00:00
foreach ( $invoices as $invoice ) {
// Reminders
$currency = $this -> getNetworkCurrency ( $invoice -> insurance -> network_id );
2022-05-02 07:03:42 +00:00
$total_paid_amount = NhInsurancesPayment :: where ( 'invoice_id' , $invoice -> id ) -> sum ( 'amount' );
2022-03-30 10:32:40 +00:00
Event :: dispatch ( new InsuranceEvent ( $invoice -> insurance , trans ( 'messages.insurance_payment_suspended' ),
trans ( 'messages.insurance_paid_mail' , [ 'name' => $invoice -> insurance -> user -> lastname , 'insured_id' => $invoice -> insurance -> insured_id ,
'bonus_amount' => $this -> toMoneyWithCurrencyCode ( $invoice -> insurance -> bonus_amount , $currency ), 'total_bonus_amount' => $this -> toMoneyWithCurrencyCode ( $invoice -> insurance -> total_bonus_amount , $currency ), 'number_of_beneficiaries' => $invoice -> insurance -> number_of_beneficiaries ,
'gender' => trans ( 'states.' . $invoice -> insurance -> user -> identification -> gender ), 'insurance_name' => $invoice -> insurance -> network -> name , 'months' => $invoice -> insurance -> monthsGrid -> number_of_months , 'invoice_id' => $invoice -> invoice_id ,
2022-05-02 07:03:42 +00:00
'amount' => $this -> toMoneyWithCurrencyCode ( $invoice -> amount , $currency ),
2022-03-31 11:57:44 +00:00
'payment_period' => trans ( 'states.' . $invoice -> insurance -> monthsGrid -> payment_period ), 'reason' => trans ( 'states.' . $invoice -> reason ), 'title' => trans ( 'messages.insurance_payment_suspended_title' ),
2022-05-02 07:03:42 +00:00
'paid_amount' => $this -> toMoneyWithCurrencyCode ( $total_paid_amount , $currency ), 'remains_amount' => $this -> toMoneyWithCurrencyCode ( $invoice -> amount - $total_paid_amount , $currency ),
2022-03-31 11:57:44 +00:00
'waiting_days' => empty ( $invoice -> insurance -> monthsGrid -> waiting_period_days ) ? trans ( 'messages.none' ) : trans ( 'messages.n_days' , [ 'n' => $invoice -> insurance -> monthsGrid -> waiting_period_days ]),
'start_at' => $invoice -> insurance -> start_at
])));
2022-03-30 10:32:40 +00:00
}
}
2022-03-29 19:20:43 +00:00
2021-10-04 16:24:39 +00:00
}