Skip to content

Commit

Permalink
Add command that sends outstanding appliance debts
Browse files Browse the repository at this point in the history
  • Loading branch information
alchalade committed Feb 1, 2024
1 parent 1277cfd commit 5af307a
Show file tree
Hide file tree
Showing 13 changed files with 203 additions and 119 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace app\Console\Commands;

use App\Services\ApplianceRateService;
use MPM\OutstandingDebts\OutstandingDebtsExportService;

class MailApplianceDebtsCommand extends AbstractSharedCommand
{
protected $signature = 'mail:appliance-debts';

protected $description = 'Send mail to customers with appliance debts';


public function handle(ApplianceRateService $applianceRateService, OutstandingDebtsExportService $outstandingDebtsExportService): void
{
$applianceDebtHavingCustomerCount = $applianceRateService->queryOutstandingDebtsByApplianceRates()->count();
// do not send mail if there is no customer with appliance debt
if ($applianceDebtHavingCustomerCount > 0) {
$outstandingDebtsExportService->sendApplianceDebtsAsEmail();
}
}
}
3 changes: 3 additions & 0 deletions Website/htdocs/mpmanager/app/Console/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace App\Console;

use app\Console\Commands\MailApplianceDebtsCommand;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Inensus\CalinMeter\Console\Commands\InstallPackage as InstallCalinMeterPackage;
Expand Down Expand Up @@ -68,6 +69,8 @@ protected function schedule(Schedule $schedule)
$schedule->command('dummy:create-data 25 --company-id=11 --type=transaction')->dailyAt('00:00');
$schedule->command('dummy:create-data 2 --company-id=11 --type=ticket')->dailyAt('00:00');
$schedule->command('asset-rate:check')->dailyAt('00:00');
// will run on the last day of the month
$schedule->command(MailApplianceDebtsCommand::class)->weeklyOn(1, '6:00');
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,34 +1,24 @@
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Services\ApplianceRateService;
use Illuminate\Http\Request;
use MPM\OutstandingDebts\Export\OutstandingDebtsExportService;
use Carbon\CarbonImmutable;
use MPM\OutstandingDebts\OutstandingDebtsExportService;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class OutstandingDebtsExportController
{
private string $path = __DIR__ . '/../../modules/OutstandingDebts/Export';

public function __construct(
private OutstandingDebtsExportService $outstandingDebtsExportService,
private ApplianceRateService $applianceRateService
) {
}

public function download(
Request $request,
) {
$data = $this->applianceRateService->getOutstandingDebtsByApplianceRates();
$this->outstandingDebtsExportService->createSpreadSheetFromTemplate($this->outstandingDebtsExportService->getTemplatePath());
$currency = $this->applianceRateService->getCurrencyFromMainSettings();
$this->outstandingDebtsExportService->setCurrency($currency);
$this->outstandingDebtsExportService->setOutstandingDebtsData($data);
$this->outstandingDebtsExportService->setExportingData();
$this->outstandingDebtsExportService->writeOutstandingDebtsData();
$this->outstandingDebtsExportService->saveSpreadSheet($this->path);
public function download(): BinaryFileResponse
{
$path = $this->outstandingDebtsExportService->createReport(CarbonImmutable::now());

return response()->download($this->path . '/' .
$this->outstandingDebtsExportService->getRecentlyCreatedSpreadSheetId() . '.xlsx');
return response()->download($path);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
use Illuminate\Http\Request;
use MPM\Transaction\Export\TransactionExportService;
use MPM\Transaction\TransactionService;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class TransactionExportController
{
private string $path = __DIR__ . '/../../modules/Transaction/Export';
public function __construct(
private TransactionService $transactionService,
private TransactionExportService $transactionExportService
Expand All @@ -17,7 +17,7 @@ public function __construct(

public function download(
Request $request,
) {
): BinaryFileResponse {
$type = $request->get('deviceType') ?: 'meter';
$serialNumber = $request->get('serial_number');
$tariffId = $request->get('tariff');
Expand All @@ -40,17 +40,15 @@ public function download(
$status,
$fromDate,
$toDate,
null
);
$this->transactionExportService->createSpreadSheetFromTemplate($this->transactionExportService->getTemplatePath());
$this->transactionExportService->setCurrency($currency);
$this->transactionExportService->setTimeZone($timeZone);
$this->transactionExportService->setTransactionData($data);
$this->transactionExportService->setExportingData();
$this->transactionExportService->writeTransactionData();
$this->transactionExportService->saveSpreadSheet($this->path);
$path = $this->transactionExportService->saveSpreadSheet();

return response()->download($this->path . '/' .
$this->transactionExportService->getRecentlyCreatedSpreadSheetId() . '.xlsx');
return response()->download($path, 'transactions' . $fromDate . '-' . $toDate . '.xlsx');
}
}
1 change: 1 addition & 0 deletions Website/htdocs/mpmanager/app/Models/AssetRate.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
* @property int $rate_cost
* @property int $remaining
* @property string $due_date
* @property AssetPerson assetPerson
*/
class AssetRate extends BaseModel
{
Expand Down
42 changes: 21 additions & 21 deletions Website/htdocs/mpmanager/app/Services/AbstractExportService.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,32 @@
use App\Exceptions\ActiveSheetNotCreatedException;
use App\Exceptions\SpreadSheetNotCreatedException;
use App\Exceptions\SpreadSheetNotSavedException;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\IReader;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Illuminate\Support\Facades\Log;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Webpatser\Uuid\Uuid;
use DateTime;
use DateTimeZone;

abstract class AbstractExportService
{
protected IReader $reader;
protected $worksheet;
protected $spreadsheet;
protected $exportingData;
protected $currency;
protected $timeZone;
protected $recentlyCreatedSpreadSheetId;
protected Worksheet $worksheet;
protected Spreadsheet $spreadsheet;
protected Collection $exportingData;
protected string $currency;
protected string $timeZone;
protected string $recentlyCreatedSpreadSheetId;

abstract public function setExportingData();

abstract public function getTemplatePath();

abstract public function getPrefix();

public function createSpreadSheetFromTemplate(string $path): Spreadsheet
{
try {
Expand Down Expand Up @@ -79,26 +83,24 @@ public function readable($amount, $separator = ',')
return $decimal ? "$whole.$decimal" : $whole;
}

public function convertUtcDateToTimezone($utcDate)
public function convertUtcDateToTimezone($utcDate): string
{
// Create a DateTime object with the UTC-based date
$dateTimeUtc = new DateTime($utcDate, new DateTimeZone('UTC'));
$dateTimeUtc = Carbon::parse($utcDate)->setTimezone('UTC');

// Set the desired timezone
$dateTimeUtc->setTimezone(new DateTimeZone($this->timeZone));

// Format the date and time as a string
$formattedDateTime = $dateTimeUtc->format('Y-m-d H:i:s');

return $formattedDateTime;
return $dateTimeUtc->format('Y-m-d H:i:s');
}

public function setRecentlyCreatedSpreadSheetId($id)
public function setRecentlyCreatedSpreadSheetId(string $id): void
{
$this->recentlyCreatedSpreadSheetId = $id;
}

public function setActivatedSheet($sheetName)
public function setActivatedSheet($sheetName): void
{
try {
$this->worksheet = $this->spreadsheet->setActiveSheetIndexByName($sheetName);
Expand All @@ -110,20 +112,18 @@ public function setActivatedSheet($sheetName)
}
}

public function saveSpreadSheet($path)
public function saveSpreadSheet(): string
{

try {
$uuid = (string)Uuid::generate(4);
$fileName = storage_path('appliance') . "/" . $this->getPrefix() . '-' . $uuid . ".xlsx";
$this->setRecentlyCreatedSpreadSheetId($uuid);
$writer = IOFactory::createWriter($this->spreadsheet, "Xlsx");
$writer->save($path . "/" . $uuid . ".xlsx");
$writer->save($fileName);
return $fileName;
} catch (\Exception $e) {
throw new SpreadSheetNotSavedException($e->getMessage());
}
}

public function getRecentlyCreatedSpreadSheetId()
{
return $this->recentlyCreatedSpreadSheetId;
}
}
44 changes: 27 additions & 17 deletions Website/htdocs/mpmanager/app/Services/ApplianceRateService.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,27 @@

use App\Models\AssetRate;
use App\Models\MainSettings;
use App\Models\PaymentHistory;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;

class ApplianceRateService implements IBaseService
{
public function __construct(private AssetRate $applianceRate, private MainSettings $mainSettings)
{
public function __construct(
private AssetRate $applianceRate,
private MainSettings $mainSettings
) {
}

public function getCurrencyFromMainSettings()
public function getCurrencyFromMainSettings(): string
{
/** @var MainSettings $mainSettings */
$mainSettings = $this->mainSettings->newQuery()->first();
return $mainSettings === null ? '' : $mainSettings->currency;
}

public function updateApplianceRateCost($applianceRate, $creatorId, $cost, $newCost)
public function updateApplianceRateCost(AssetRate $applianceRate, $creatorId, $cost, $newCost): AssetRate
{
$currency = $this->getCurrencyFromMainSettings();
event(
Expand All @@ -40,10 +45,10 @@ public function updateApplianceRateCost($applianceRate, $creatorId, $cost, $newC
$applianceRate->remaining = $newCost;
$applianceRate->update();
$applianceRate->save();
return $applianceRate->fresh();
return $applianceRate->refresh();
}

public function deleteUpdatedApplianceRateIfCostZero($applianceRate, $creatorId, $cost, $newCost)
public function deleteUpdatedApplianceRateIfCostZero(AssetRate $applianceRate, $creatorId, $cost, $newCost): void
{
$currency = $this->getCurrencyFromMainSettings();
$appliancePerson = $applianceRate->assetPerson;
Expand All @@ -64,7 +69,7 @@ public function deleteUpdatedApplianceRateIfCostZero($applianceRate, $creatorId,
);
}

public function getByLoanIdsForDueDate($loanIds)
public function getByLoanIdsForDueDate($loanIds): Collection
{
return $this->applianceRate->newQuery()->with('assetPerson.asset')
->whereIn('asset_person_id', $loanIds)
Expand All @@ -73,7 +78,7 @@ public function getByLoanIdsForDueDate($loanIds)
->get();
}

public function getAllByLoanId($loanId)
public function getAllByLoanId($loanId): Collection
{
return $this->applianceRate->newQuery()->with('assetPerson.asset')
->where('asset_person_id', $loanId)
Expand All @@ -85,7 +90,7 @@ public function getById($id)
// TODO: Implement getById() method.
}

public function create($assetPerson, $installmentType = 'monthly')
public function create($assetPerson, $installmentType = 'monthly'): void
{
$baseTime = $assetPerson->first_payment_date ?? date('Y-m-d');
$installment = $installmentType === 'monthly' ? 'month' : 'week';
Expand Down Expand Up @@ -141,20 +146,25 @@ public function getAll($limit = null)
}


public function getDownPaymentAsAssetRate($assetPerson): AssetRate
public function getDownPaymentAsAssetRate($assetPerson): ?AssetRate
{
return $this->applianceRate->newQuery()->where('asset_person_id', $assetPerson->id)
->where('rate_cost', $assetPerson->down_payment)->where('remaining', 0)->first();
/** @var ?AssetRate $result */
$result = $this->applianceRate->newQuery()
->where('asset_person_id', $assetPerson->id)
->where('rate_cost', $assetPerson->down_payment)
->where('remaining', 0)
->first();

return $result;
}

public function getOutstandingDebtsByApplianceRates()
public function queryOutstandingDebtsByApplianceRates(CarbonImmutable $toDate): Builder
{
return $this->applianceRate->newQuery()
->with(['assetPerson.asset', 'assetPerson.person'])
->where('due_date', '<', now()->toDateString())
->where('due_date', '<', $toDate->format('Y-m-d'))
->where('remaining', '>', 0)
->groupBy('asset_person_id')
->orderBy('id')
->get();
->orderBy('id');
}
}
8 changes: 7 additions & 1 deletion Website/htdocs/mpmanager/app/Services/UserService.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Exception;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use MPM\User\Events\UserCreatedEvent;

class UserService
Expand Down Expand Up @@ -124,7 +125,7 @@ public function getCompanyId(): int

public function getById($id)
{
return $this->user->newQuery()->find($id);
return $this->user->newQuery()->find($id);
}

public function delete($model)
Expand All @@ -136,4 +137,9 @@ public function getAll($limit = null)
{
// TODO: Implement getAll() method.
}

public function getUsers(): Collection
{
return $this->user->newQuery()->get();
}
}
Loading

0 comments on commit 5af307a

Please sign in to comment.