Skip to content

Commit

Permalink
Merge branch 'master' into aggregations
Browse files Browse the repository at this point in the history
  • Loading branch information
madbob committed Aug 4, 2024
2 parents bba0d4b + c70b4ca commit efaac73
Show file tree
Hide file tree
Showing 48 changed files with 580 additions and 167 deletions.
2 changes: 2 additions & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
github: madbob
custom: 'https://www.paypal.me/m4db0b'
5 changes: 5 additions & 0 deletions code/app/Booking.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ public function payment(): BelongsTo
return $this->belongsTo(Movement::class);
}

public function receipts(): BelongsToMany
{
return $this->belongsToMany('App\Receipt');
}

/*
Con questo scope si caricano le relazioni utilizzate per il calcolo dei
modificatori.
Expand Down
22 changes: 17 additions & 5 deletions code/app/Console/Commands/CloseOrders.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Carbon\Carbon;

use App\Jobs\NotifyClosedOrder;
use App\Order;
Expand All @@ -14,22 +15,33 @@ class CloseOrders extends Command

public function handle()
{
$orders = Order::withoutGlobalScopes()->where('status', 'open')->where('end', '<', date('Y-m-d'))->get();
$closed = [];
$today = Carbon::today()->format('Y-m-d');
$orders = Order::withoutGlobalScopes()->where('status', 'open')->where('end', '<', $today)->get();
$notifications = [];

foreach($orders as $order) {
try {
$order->status = 'closed';
$order->save();
$closed[] = $order->id;

foreach($order->aggregate->gas as $gas) {
if (isset($notifications[$gas->id]) == false) {
$notifications[$gas->id] = [];
}

$notifications[$gas->id][] = $order->id;
}
}
catch(\Exception $e) {
\Log::error('Errore in chiusura automatica ordine: ' . $e->getMessage());
}
}

if (empty($closed) == false) {
NotifyClosedOrder::dispatch($closed);
$hub = app()->make('GlobalScopeHub');

foreach($notifications as $gas_id => $orders) {
$hub->setGas($gas_id);
NotifyClosedOrder::dispatch($orders);
}
}
}
5 changes: 4 additions & 1 deletion code/app/Console/Commands/RemindOrders.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,12 @@ public function handle()
}
}

$hub = app()->make('GlobalScopeHub');

foreach($notifications as $gas_id => $orders) {
Log::info('Invio promemoria per ordini ' . join(', ', $orders));
NotifyRemindOrder::dispatch($gas_id, $orders);
$hub->setGas($gas_id);
NotifyRemindOrder::dispatch($orders);
}

$gas = Gas::all();
Expand Down
14 changes: 14 additions & 0 deletions code/app/Formatters/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,20 @@ private static function columnsByType($ret, $type)
return $obj->member_since;
},
];

$ret['birthplace'] = (object) [
'name' => _i('Luogo di Nascita'),
'format' => function($obj, $context) {
return $obj->birthplace;
},
];

$ret['birthday'] = (object) [
'name' => _i('Data di Nascita'),
'format' => function($obj, $context) {
return $obj->birthday;
},
];
}

return $ret;
Expand Down
13 changes: 13 additions & 0 deletions code/app/Helpers/Components.php
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,19 @@ function formatMainFormButtons($component, $params)
}

$params['buttons'] = $buttons;

if (isset($params['appendNodes']) == false) {
$params['appendNodes'] = [];
}

$params['appendNodes'][] = sprintf('<div class="fixed-bottom bg-danger p-2 bottom-helper" hidden>
<div class="row justify-content-end align-items-center">
<div class="col-auto text-white">%s</div>
<div class="col-auto">
<button class="btn btn-success" type="submit">%s</button>
</div>
</div>
</div>', _i('Ricorda di cliccare il tasto "Salva" quando hai finito!'), _i('Salva'));
}

unset($params['attributes']['other_buttons'], $params['attributes']['nodelete'], $params['attributes']['nosave']);
Expand Down
78 changes: 43 additions & 35 deletions code/app/Http/Controllers/MailController.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,41 +56,6 @@ private function registerBounce($event, $email, $message)
}
}

public function postStatusSES(Request $request)
{
if (env('MAIL_MAILER') == 'ses') {
$message = Message::fromRawPostData();
$validator = new MessageValidator();

try {
$validator->validate($message);
}
catch (InvalidSnsMessageException $e) {
Log::error('SNS Message Validation Error: ' . $e->getMessage());
abort(404);
}

if ($message['Type'] === 'SubscriptionConfirmation') {
Http::get($message['SubscribeURL']);
}
else if ($message['Type'] === 'Notification') {
$data = json_decode($message['Message']);
$event = $data->notificationType;

if ($event == 'Bounce') {
try {
$email = $data->bounce->bouncedRecipients[0]->emailAddress;
$message = $data->bounce->bouncedRecipients[0]->diagnosticCode ?? '???';
$this->registerBounce($event, $email, $message);
}
catch(\Exception $e) {
Log::error('Notifica SNS illeggibile: ' . $e->getMessage() . ' - ' . print_r($data, true));
}
}
}
}
}

public function postStatusSendinblue(Request $request)
{
if (env('MAIL_MAILER') == 'sendinblue') {
Expand Down Expand Up @@ -120,4 +85,47 @@ public function postStatusSendinblue(Request $request)
}
}
}

public function postStatusScaleway(Request $request)
{
if (env('MAIL_MAILER') == 'scaleway') {
$api_endpoint = 'https://api.scaleway.com/transactional-email/v1alpha1/regions/fr-par/webhooks';

$message = Message::fromRawPostData();
$validator = new MessageValidator();

try {
$validator->validate($message);
}
catch (InvalidSnsMessageException $e) {
Log::error('SNS Message Validation Error: ' . $e->getMessage());
abort(404);
}

try {
$body = json_decode($request->getContent());

if ($body) {
/*
Per automatizzare la procedura di conferma della
registrazione del webhook
*/
if (isset($body->SubscribeURL)) {
@file_get_contents($body->SubscribeURL);
return;
}
else {
$payload = json_decode($body->Message);
$event = $payload->type;
$email = $payload->email_to;
$message = $payload->email_error;
$this->registerBounce($event, $email, $message);
}
}
}
catch(\Exception $e) {
Log::error('Notifica Scaleway illeggibile: ' . $e->getMessage() . ' - ' . print_r($request->all(), true));
}
}
}
}
23 changes: 12 additions & 11 deletions code/app/Http/Controllers/MovementsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,19 +95,20 @@ private function exportMain($format, $movements)
$filename = sanitizeFilename(_i('Esportazione movimenti GAS %s.%s', [date('d/m/Y'), $format]));

if ($format == 'csv') {
$headers = [_i('Data Registrazione'), _i('Data Movimento'), _i('Tipo'), _i('Pagamento'), _i('Pagante'), _i('Pagato'), _i('Valore'), _i('Note')];
$headers = [_i('Data Registrazione'), _i('Data Movimento'), _i('Tipo'), _i('Pagamento'), _i('Identificativo'), _i('Pagante'), _i('Pagato'), _i('Valore'), _i('Note')];

return output_csv($filename, $headers, $movements, function($mov) {
$row = [];
$row[] = $mov->registration_date;
$row[] = $mov->date;
$row[] = $mov->printableType();
$row[] = $mov->printablePayment();
$row[] = $mov->sender ? $mov->sender->printableName() : '';
$row[] = $mov->target ? $mov->target->printableName() : '';
$row[] = printablePrice($mov->amount);
$row[] = $mov->notes;
return $row;
$row = [];
$row[] = $mov->registration_date;
$row[] = $mov->date;
$row[] = $mov->printableType();
$row[] = $mov->printablePayment();
$row[] = $mov->identifier;
$row[] = $mov->sender ? $mov->sender->printableName() : '';
$row[] = $mov->target ? $mov->target->printableName() : '';
$row[] = printablePrice($mov->amount);
$row[] = $mov->notes;
return $row;
});
}
else if ($format == 'pdf') {
Expand Down
6 changes: 6 additions & 0 deletions code/app/Http/Controllers/OrdersController.php
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,12 @@ private function oldOrders($user)
return easyFilterOrders($supplier_id, '1970-01-01', date('Y-m-d', strtotime('-1 years')), ['open', 'closed']);
}

public function noDestroyNotice(Request $request, $id)
{
$order = $this->service->show($id, true);
return view('order.partials.nodestroy', ['order' => $order]);
}

/*
Questa funzione è usata per aggiornare manualmente le quantità
di un certo prodotto all'interno di un ordine
Expand Down
35 changes: 22 additions & 13 deletions code/app/Http/Controllers/ReceiptsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,21 @@ public function __construct(ReceiptsService $service)
]);
}

private function filterByUser($request)
{
return $request->input('user_id', '0');
}

public function index(Request $request)
{
$past = date('Y-m-d', strtotime('-1 months'));
$future = date('Y-m-d', strtotime('+10 years'));
$receipts = $this->service->list($past, $future, 0);
$user_id = $this->filterByUser($request);
$receipts = $this->service->list($past, $future, 0, $user_id);

return view('receipt.index', [
'receipts' => $receipts,
'user_id' => $user_id,
]);
}

Expand All @@ -40,7 +48,7 @@ public function show(Request $request, $id)
if ($user->can('movements.admin', $user->gas)) {
return view('receipt.edit', ['receipt' => $receipt]);
}
else if ($user->can('movements.view', $user->gas)) {
else if ($user->can('movements.view', $user->gas) || $receipt->user->id == $user->id) {
return view('receipt.show', ['receipt' => $receipt]);
}
else {
Expand All @@ -50,7 +58,7 @@ public function show(Request $request, $id)

private function testAccess($user, $receipt)
{
if ($user->can('movements.admin', $user->gas) || $user->can('movements.view', $user->gas) || $receipt->user_id == $user->id) {
if ($user->can('movements.admin', $user->gas) || $user->can('movements.view', $user->gas) || $receipt->user->id == $user->id) {
return true;
}
else {
Expand Down Expand Up @@ -120,14 +128,14 @@ private function outputCSV($elements)

private function send($elements): void
{
foreach($elements as $receipt) {
if ($receipt->mailed == false) {
try {
$this->sendByMail($receipt);
}
catch(\Exception $e) {
\Log::error('Errore in inoltro ricevuta: ' . $e->getMessage());
}
$to_send = $elements->filter(fn($r) => $r->mailed == false);

foreach($to_send as $receipt) {
try {
$this->sendByMail($receipt);
}
catch(\Exception $e) {
\Log::error('Errore in inoltro ricevuta: ' . $e->getMessage());
}
}
}
Expand All @@ -136,8 +144,9 @@ public function search(Request $request)
{
$start = decodeDate($request->input('startdate'));
$end = decodeDate($request->input('enddate'));
$supplier_id = $request->input('supplier_id');
$elements = $this->service->list($start, $end, $supplier_id);
$supplier_id = $request->input('supplier_id', '0');
$user_id = $this->filterByUser($request);
$elements = $this->service->list($start, $end, $supplier_id, $user_id);

$format = $request->input('format', 'none');

Expand Down
17 changes: 17 additions & 0 deletions code/app/Http/Controllers/UsersController.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,18 @@ public function index(Request $request)
return $this->easyExecute(function() use ($request) {
$user = $request->user();
$users = $this->service->list('', $user->can('users.admin', $user->gas));

/*
Il grosso collo di bottiglia nell'enumerazione degli utenti è
il recupero sullo stato del saldo di ciascuno, da cui dipendono
poi icone e filtri.
Qui pre-carico il saldo corrente di ognuno, premesso che nella
funzione CreditableTrait::currentBalance() verifico che
effettivamente esista o se è necessario allocare un nuovo saldo
corrente
*/
$users->loadMissing(['balances' => fn($query) => $query->where('current', true)]);

return view('pages.users', ['users' => $users]);
});
}
Expand Down Expand Up @@ -94,6 +106,11 @@ public function export(Request $request)
$headers = UserFormatter::getHeaders($fields);
$users = $this->service->list('', true);

if ($request->input('exportables') == 'selected') {
$selected = $request->input('users', []);
$users = $users->filter(fn($u) => in_array($u->id, $selected));
}

return output_csv(_i('utenti.csv'), $headers, $users, function($user) use ($fields) {
return UserFormatter::format($user, $fields);
});
Expand Down
8 changes: 7 additions & 1 deletion code/app/Jobs/NotifyNewOrder.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,13 @@ public function handle()
{
$order = Order::find($this->order_id);

if (is_null($order) || is_null($order->first_notify) == false) {
if (is_null($order)) {
\Log::warning('Richiesta notifica creazione ordine non esistente');
return;
}

if (is_null($order->first_notify) == false) {
\Log::warning('Richiesta notifica creazione ordine già inoltrata');
return;
}

Expand Down
Loading

0 comments on commit efaac73

Please sign in to comment.