Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

E bike and daly bms integration #18

Merged
merged 9 commits into from
Jan 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

namespace App\Console\Commands;

use App\Services\MenuItemsService;
use Illuminate\Console\Command;

class AddEBikesItemToNavbar extends AbstractSharedCommand
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'navbar:add-ebikes-item';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Add ebikes item to navbar';

/**
* Create a new command instance.
*
* @return void
*/
public function __construct(private MenuItemsService $menuItemsService,)
{
parent::__construct();
}

/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$this->addSolarHomeSystemsToNavBar();
return 0;
}

private function addSolarHomeSystemsToNavBar()
{
$eBikesMenuItem = 'E-Bikes';
$menuItem = $this->menuItemsService->getByName($eBikesMenuItem);

if (!$menuItem) {
$this->menuItemsService->create([
'name' => $eBikesMenuItem,
'url_slug' => '/e-bikes/page/1',
'md_icon' => 'electric_bike',
'menu_order' => 0,
]);
}
}
}
76 changes: 44 additions & 32 deletions Website/htdocs/mpmanager/app/Console/Commands/AssetRateChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,15 @@
use App\Jobs\SmsProcessor;
use App\Models\AssetRate;
use App\Models\User;
use App\Services\MainSettingsService;
use App\Services\SmsApplianceRemindRateService;
use App\Services\SmsService;
use App\Sms\Senders\SmsConfigs;
use App\Sms\SmsTypes;
use Carbon\Carbon;
use Exception;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Log;
use Inensus\Ticket\Models\TicketCategory;
use Inensus\Ticket\Services\TicketService;

Expand All @@ -25,51 +27,34 @@ public function __construct(
private TicketService $ticketService,
private SmsApplianceRemindRateService $smsApplianceRemindRateService,
private User $user,
private TicketCategory $label
private TicketCategory $label,
private MainSettingsService $mainSettingsService
) {
parent::__construct();
}


public function runInCompanyScope(): void
public function handle(): void
{
$this->remindUpComingRates();
$this->findOverDueRates();
}


private function findOverDueRates(): void
{
$smsApplianceRemindRates = $this->getApplianceRemindRates();
$smsApplianceRemindRates->each(function ($smsApplianceRemindRate) {
$overDueRates = $this->assetRate::with(['assetPerson.assetType', 'assetPerson.person.addresses'])
->whereDate(
'due_date',
'>=',
Carbon::parse('due_date')->addDays($smsApplianceRemindRate->overdue_remind_rate)
)
->where('remaining', '>', 0)
->where('remind', 0)
->get();
echo "\n" . count($overDueRates) . ' overdue rates found' . "\n";
$this->sendReminders($overDueRates, SmsTypes::OVER_DUE_APPLIANCE_RATE);
});
}

private function remindUpComingRates(): void
{
$smsApplianceRemindRates = $this->getApplianceRemindRates();
$smsApplianceRemindRates->each(function ($smsApplianceRemindRate) {
$remindDay = Carbon::now()->subDays($smsApplianceRemindRate->remind_rate)->format('Y-m-d');
$dueAssetRates = $this->assetRate::with([
'assetPerson.assetType.smsReminderRate',
'assetPerson.asset.smsReminderRate',
'assetPerson.person.addresses'
])
->whereDate('due_date', '>=', $remindDay)
->whereBetween('due_date', [
now()->subDays($smsApplianceRemindRate->remind_rate)->toDateString(),
now()->toDateString()
])
->where('remaining', '>', 0)
->whereHas(
'assetPerson.person.addresses',
static function ($q) {
function ($q) {
$q->where('is_primary', 1);
}
)
Expand All @@ -79,6 +64,24 @@ static function ($q) {
});
}

private function findOverDueRates(): void
{
$smsApplianceRemindRates = $this->getApplianceRemindRates();
$smsApplianceRemindRates->each(function ($smsApplianceRemindRate) {
$overDueRates = $this->assetRate::with(['assetPerson.asset', 'assetPerson.person.addresses'])
->whereBetween('due_date', [
now()->toDateString(),
now()->addDays($smsApplianceRemindRate->overdue_remind_rate)->toDateString(),
])
->where('remaining', '>', 0)
->where('remind', 0)
->get();

echo "\n" . count($overDueRates) . ' overdue rates found' . "\n";
$this->sendReminders($overDueRates, SmsTypes::OVER_DUE_APPLIANCE_RATE);
});
}

private function sendReminderSms(AssetRate $assetRate): void
{
$smsService = app()->make(SmsService::class);
Expand All @@ -99,20 +102,29 @@ private function sendReminders($dueAssetRates, $smsType)

private function createReminderTicket(AssetRate $assetRate, $overDue = false): void
{
$currency = $this->mainSettingsService->getAll()->first()->currency;
//create ticket for customer service
$creator = $this->user->newQuery()->where('name', 'System')->first();
$creator = $this->user->newQuery()->firstOrCreate([
'name' => 'System',
]);
//reformat due date if it is set
if ($overDue) {
$category = $this->label->newQuery()->where('label_name', 'Payments Issue')->first();
$description = 'Customer didn\'t pay ' . $assetRate->remaining . 'TZS on ' . $assetRate->due_date;
$category = $this->label->newQuery()->firstOrCreate([
'label_name' => 'Payments Issue',
]);
$description = 'Customer didn\'t pay ' . $assetRate->remaining . $currency . ' on ' . $assetRate->due_date;
} else {
$category = $this->label->newQuery()->where('label_name', 'Customer Follow Up')->first();
$description = 'Customer should pay ' . $assetRate->remaining . 'TZS until ' . $assetRate->due_date;
$category = $this->label->newQuery()->firstOrCreate([
'label_name' => 'Customer Follow Up',

]);
$description =
'Customer should pay ' . $assetRate->remaining . $currency . ' until ' . $assetRate->due_date;
}


$this->ticketService->create(
title: $assetRate->assetPerson->assetType->name . ' rate reminder',
title: $assetRate->assetPerson->asset->name . ' rate reminder',
content: $description,
categoryId: $category->id,
assignedId: $creator?->id,
Expand Down
9 changes: 3 additions & 6 deletions Website/htdocs/mpmanager/app/Console/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Inensus\SunKingSHS\Console\Commands\InstallPackage as InstallSunKingSHSPackage;
use Inensus\GomeLongMeter\Console\Commands\InstallPackage as InstallGomeLongMeterPackage;
use Inensus\WavecomPaymentProvider\Console\Commands\InstallPackage as InstallWaveComPackage;
use Inensus\DalyBms\Console\Commands\InstallPackage as InstallDalyBmsPackage;

class Kernel extends ConsoleKernel
{
Expand All @@ -45,6 +46,7 @@ class Kernel extends ConsoleKernel
InstallSunKingSHSPackage::class,
InstallGomeLongMeterPackage::class,
InstallWaveComPackage::class,
InstallDalyBmsPackage::class,
];

/**
Expand All @@ -56,19 +58,14 @@ class Kernel extends ConsoleKernel
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
/* $schedule->command('accessrate:check')->daily();
$schedule->command('asset-rate:check')->daily();
$schedule->command('calinMeters:readOnline')->dailyAt('04:00');
$schedule->job(new SocialTariffPiggyBankManager())->daily();*/
$schedule->command('reports:city-revenue weekly')->weeklyOn(1, '3:00');
$schedule->command('reports:city-revenue monthly')->monthlyOn(1, '3:00');
$schedule->command('reports:outsource')->monthlyOn(1, '3:30');
$schedule->command('sms:resend-rejected 5')->everyMinute();
$schedule->command('update:cachedClustersDashboardData')->everyFifteenMinutes();
$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');
}

/**
Expand Down
84 changes: 84 additions & 0 deletions Website/htdocs/mpmanager/app/Http/Controllers/EBikeController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreEBikeRequest;
use App\Http\Resources\ApiResource;
use App\Services\AppliancePersonService;
use App\Services\ManufacturerService;
use MPM\Device\DeviceService;
use MPM\EBike\EBikeDeviceService;
use MPM\EBike\EBikeService;
use Illuminate\Http\Request;

class EBikeController extends Controller
{
public function __construct(
private DeviceService $deviceService,
private EBikeService $eBikeService,
private EBikeDeviceService $eBikeDeviceService,
private ManufacturerService $manufacturerService,
private AppliancePersonService $appliancePersonService
) {
}

public function index(Request $request): ApiResource
{
$limit = $request->input('per_page');
return ApiResource::make($this->eBikeService->getAll($limit));
}

public function store(StoreEBikeRequest $request)
{
$eBikeData = $request->all();
$deviceData = [
'device_serial' => $eBikeData['serial_number'],
'person_id' => null
];

$device = $this->deviceService->make($deviceData);
$eBike = $this->eBikeService->create($eBikeData);
$this->eBikeDeviceService->setAssigned($device);
$this->eBikeDeviceService->setAssignee($eBike);
$this->eBikeDeviceService->assign();
$this->deviceService->save($device);

return ApiResource::make($eBike->load(['manufacturer', 'appliance', 'device.person']));
}

public function search(Request $request): ApiResource
{
$term = $request->input('term');
$paginate = $request->input('paginate') ?? 1;

return ApiResource::make($this->eBikeService->search($term, $paginate));
}

public function show(string $serialNumber): ApiResource
{
return ApiResource::make($this->eBikeService->getBySerialNumber($serialNumber));
}

public function switch(Request $request): ApiResource
{
$serialNumber = $request->input('serial_number');
$manufacturerName = $request->input('manufacturer_name');
$status = $request->input('status');
$manufacturer = $this->manufacturerService->getByName($manufacturerName);
$manufacturerApi = resolve($manufacturer->api_name);
$manufacturerApi->switchDevice($serialNumber, $status);
$creatorId = auth('api')->user()->id;
$appliancePerson = $this->appliancePersonService->getBySerialNumber($serialNumber);
event(
'new.log',
[
'logData' => [
'user_id' => $creatorId,
'affected' => $appliancePerson,
'action' => 'Bike (' . $serialNumber . ') is set as ' . $status . ' manually.'
]
]
);
return ApiResource::make($this->eBikeService->getBySerialNumber($serialNumber));
}
}
32 changes: 32 additions & 0 deletions Website/htdocs/mpmanager/app/Http/Requests/StoreEBikeRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreEBikeRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize(): bool
{
return true;
}

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'serial_number' => 'required|min:8|max:15|unique:shard.devices,device_serial',
'manufacturer_id' => 'required|exists:shard.manufacturers,id',
'asset_id' => 'required|exists:shard.assets,id',
];
}
}
2 changes: 1 addition & 1 deletion Website/htdocs/mpmanager/app/Jobs/TokenProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ private function handleExistingToken()
private function generateToken($api): void
{
try {
$tokenData = $api->chargeMeter($this->transactionContainer);
$tokenData = $api->chargeDevice($this->transactionContainer);
} catch (Exception $e) {
$this->handleTokenGenerationFailure($e);
return;
Expand Down
7 changes: 3 additions & 4 deletions Website/htdocs/mpmanager/app/Lib/IManufacturerAPI.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,15 @@
namespace App\Lib;

use App\Misc\TransactionDataContainer;
use App\Models\Meter\Meter;
use App\Models\Meter\MeterToken;
use App\Models\Device;

interface IManufacturerAPI
{
/**
* @param TransactionDataContainer $transactionContainer
* @return array
*/
public function chargeMeter(TransactionDataContainer $transactionContainer): array;
public function chargeDevice(TransactionDataContainer $transactionContainer): array;

public function clearMeter(Meter $meter);
public function clearDevice(Device $device);
}
Loading
Loading