242 lines
8.9 KiB
PHP
Executable File
242 lines
8.9 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
|
|
use App\BillingPeriodType;
|
|
use App\InsuranceSubscriptionState;
|
|
use App\Models\AgentPlus;
|
|
use App\Models\CountriesCurrency;
|
|
use App\Models\Network;
|
|
use App\Models\NhHealthCareSheet;
|
|
use App\Models\NhInsurance;
|
|
use App\Models\NhInvoice;
|
|
use App\Models\NhNetworksConfig;
|
|
use App\Models\User;
|
|
use App\Models\WalletsUser;
|
|
use App\Traits\ApiResponser;
|
|
use App\Traits\Helper;
|
|
use Barryvdh\DomPDF\Facade as PDF;
|
|
use DateTime;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Http\Response;
|
|
use Illuminate\Support\Facades\Date;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\File;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Facades\Mail;
|
|
use Moment\Moment;
|
|
use Propaganistas\LaravelPhone\PhoneNumber;
|
|
use stdClass;
|
|
|
|
class InvoiceController extends Controller
|
|
{
|
|
|
|
|
|
/**
|
|
* @OA\Get(
|
|
* path="/insured",
|
|
* summary="Rechercher un assuré (par reseau , par nom ou par numero de telephone)",
|
|
* tags={"Assurés"},
|
|
* security={{"api_key":{}}},
|
|
* @OA\Parameter(
|
|
* parameter="network_id",
|
|
* name="network_id",
|
|
* description="ID du reseau",
|
|
* @OA\Schema(
|
|
* type="integer"
|
|
* ),
|
|
* in="query",
|
|
* required=true
|
|
* ),
|
|
* @OA\Parameter(
|
|
* parameter="insured_id",
|
|
* name="insured_id",
|
|
* description="Numero d'assuré",
|
|
* @OA\Schema(
|
|
* type="string"
|
|
* ),
|
|
* in="query",
|
|
* required=false
|
|
* ),
|
|
* @OA\Parameter(
|
|
* parameter="name",
|
|
* name="name",
|
|
* description="Nom de l'utilisateur",
|
|
* @OA\Schema(
|
|
* type="string"
|
|
* ),
|
|
* in="query",
|
|
* required=false
|
|
* ),
|
|
* @OA\Parameter(
|
|
* parameter="phone",
|
|
* name="phone",
|
|
* description="Telephone de l'utilisateur",
|
|
* @OA\Schema(
|
|
* type="string"
|
|
* ),
|
|
* in="query",
|
|
* required=false
|
|
* ),
|
|
* @OA\Response(
|
|
* response=200,
|
|
* description="OK",
|
|
* @OA\JsonContent(
|
|
* ref="#/components/schemas/ApiResponse",
|
|
* example = {
|
|
* "status" : 200,
|
|
* "response" : {{"id":4,"network_id":250,"user_id":349,"insured_id":"GJKS8ZGBEJTL","number_of_months":3,"bonus_amount":"150000.00",
|
|
* "number_of_beneficiaries":2,"total_bonus_amount":"495000.00","start_at":"2021-11-11T21:54:02.000000Z","end_at":"2022-02-11T21:54:02.000000Z",
|
|
* "state":"PAID","created_at":"2021-11-11T20:54:02.000000Z","updated_at":"2021-11-11T20:54:02.000000Z","user":{"id":349,
|
|
* "firstname":null,"lastname":"Tom Di","phone":"+237690716648","email":"ddoubletom@gmail.com"},"network":{"id":250,"name":"Cnamgs-pharmacies"}}},
|
|
* "error":null
|
|
* }
|
|
* )
|
|
* )
|
|
* )
|
|
*/
|
|
// Generer les factures periodiquement pour chaque agent
|
|
public function generateInvoice(Request $request)
|
|
{
|
|
$this->validate($request, [
|
|
'network_agent_id' => 'required|integer|exists:networks_agents,id'
|
|
]);
|
|
$network_agent_id = $request->input('network_agent_id');
|
|
$agent = AgentPlus::where('network_agent_id', $network_agent_id)->first();
|
|
$hyper = AgentPlus::where('network_id', $agent->network_id)->where('category', 'hyper')->first();
|
|
$config = NhNetworksConfig::where('network_id', $agent->network_id)->first();
|
|
if (!isset($config)) {
|
|
return $this->errorResponse("Le nano sante n'est pas actif pour ce reseau");
|
|
}
|
|
|
|
// executer le script chaque Dimanche a minuit
|
|
$start_at = new DateTime();
|
|
switch ($config->provider_billing_period) {
|
|
case BillingPeriodType::WEEKLY:
|
|
$start_at->modify('-7 days');
|
|
break;
|
|
case BillingPeriodType::BIMONTHLY:
|
|
$start_at->modify('-14 days');
|
|
break;
|
|
case BillingPeriodType::MONTHLY:
|
|
$start_at->modify('-28 days');
|
|
break;
|
|
default:
|
|
$start_at = new DateTime();
|
|
}
|
|
|
|
$end_at = new DateTime();
|
|
|
|
|
|
$invoice_id = $this->generateInvoiceID($agent->code_membre);
|
|
$country = CountriesCurrency::findOrFail($agent->country_id);
|
|
$datetime = $this->getCurrentTimeByCountryCode($country->code_country);
|
|
|
|
$totalInsurerAmount = 0;
|
|
$totalInsuredAmount = 0;
|
|
$sheets = NhHealthCareSheet::with(['insurance'])->where('network_agent_id', $network_agent_id)->where('state', InsuranceSubscriptionState::ACCEPTED)
|
|
->where('created_at', '>=', $start_at)->where('created_at', '<=', $end_at)->get();
|
|
|
|
if (sizeof($sheets) == 0) {
|
|
return $this->errorResponse("Aucune feuille de soins acceptée");
|
|
}
|
|
|
|
foreach ($sheets as $sheet) {
|
|
$insurerAmount = 0;
|
|
$insuredAmount = 0;
|
|
|
|
foreach ($sheet->performances as $p) {
|
|
$insurerAmount += ($p->moderator_ticket ?? 0);
|
|
$insuredAmount += ($p->insurance_amount ?? 0);
|
|
}
|
|
|
|
foreach ($sheet->performances as $p) {
|
|
$insurerAmount += ($p->insured_paid_amount ?? 0);
|
|
$insuredAmount += ($p->insurer_paid_amount ?? 0);
|
|
}
|
|
|
|
foreach ($sheet->performances as $p) {
|
|
$insurerAmount += ($p->insured_paid_amount ?? 0);
|
|
$insuredAmount += ($p->insurer_paid_amount ?? 0);
|
|
}
|
|
|
|
$sheet->insurer_amount = $insurerAmount;
|
|
$sheet->insured_amount = $insuredAmount;
|
|
|
|
$totalInsuredAmount += $insuredAmount;
|
|
$totalInsurerAmount += $insurerAmount;
|
|
|
|
$sheet->date = $sheet->created_at->format('d/m/Y');
|
|
}
|
|
|
|
try {
|
|
DB::beginTransaction();
|
|
|
|
$directoryName = '/invoices/';
|
|
$filename = $start_at->format('dmY') . '_' . $end_at->format('dmY') . '_' . $agent->code_membre . '.pdf';
|
|
|
|
$invoice = NhInvoice::create([
|
|
'invoice_id' => $invoice_id,
|
|
'network_agent_id' => $agent->network_agent_id,
|
|
'amount' => $totalInsuredAmount + $totalInsurerAmount,
|
|
'insured_amount' => $totalInsuredAmount,
|
|
'insurer_amount' => $totalInsurerAmount,
|
|
'period_start_at' => $start_at,
|
|
'period_end_at' => $end_at,
|
|
'file_url' => config('services.app_url') . $directoryName . $filename,
|
|
'created_at' => $datetime,
|
|
'updated_at' => $datetime
|
|
]);
|
|
|
|
$invoice->amount = $this->toMoneyWithCurrencyCode($invoice->amount, $country->currency_code);
|
|
$invoice->insured_amount = $this->toMoneyWithCurrencyCode($invoice->insured_amount, $country->currency_code);
|
|
$invoice->insurer_amount = $this->toMoneyWithCurrencyCode($invoice->insurer_amount, $country->currency_code);
|
|
$invoice->home_visit_fees = $this->toMoneyWithCurrencyCode($invoice->home_visit_fees, $country->currency_code);
|
|
|
|
$ids = array_map(function ($r) {
|
|
return $r['id'];
|
|
}, $sheets->toArray());
|
|
|
|
DB::update("UPDATE nh_health_care_sheets SET state = :state_ , invoice_id = :id WHERE id IN (" . implode(',', $ids) . ")",
|
|
['id' => $invoice->id, 'state_' => InsuranceSubscriptionState::INVOICE_ISSUED]);
|
|
|
|
$invoice->sheets = $sheets;
|
|
$invoice->agent = $agent;
|
|
$invoice->hyper = $hyper;
|
|
$invoice->period = $start_at->format('d/m/Y') . ' ' . trans('messages.to') . ' ' . $end_at->format('d/m/Y');
|
|
|
|
//Check if the directory already exists.
|
|
if (!is_dir(public_path($directoryName))) {
|
|
//Directory does not exist, so lets create it.
|
|
mkdir($directoryName, 0755);
|
|
}
|
|
|
|
$title = trans('messages.invoice') . ' ' . $invoice->period;
|
|
$message = "";
|
|
|
|
$file = PDF::loadView('emails.invoice', $invoice->toArray())->setPaper('a4', 'landscape')->setWarnings(false)->save(public_path($directoryName . $filename));
|
|
|
|
DB::commit();
|
|
$recipients = [preg_replace("/\s+/", "", $hyper->email)]; // Supprimer les espaces dans le mail
|
|
Mail::mailer('smtp')->raw($message, function ($message) use ($recipients, $title, $file) {
|
|
$message->subject($title)
|
|
->to($recipients)
|
|
->attachData($file->output(), $title . '.pdf');
|
|
});
|
|
|
|
} catch (\Throwable $t) {
|
|
DB::rollBack();
|
|
Log::error('-------- Mail not sent -----------');
|
|
Log::error($t->getMessage() . " :\n" . $t->getTraceAsString());
|
|
}
|
|
|
|
return $this->successResponse("Invoice generated");
|
|
}
|
|
|
|
private function generateInvoiceID($agent_code)
|
|
{
|
|
return date('d') . '/' . date('m') . '/' . date('Y') . '/' . $agent_code;
|
|
}
|
|
}
|