Using morphTo() on services, added Ezypay payment Import

This commit is contained in:
Deon George
2019-06-07 16:54:27 +10:00
parent 41d6a07196
commit 253eb55c19
33 changed files with 11398 additions and 183 deletions

25
app/Classes/Payments.php Normal file
View File

@@ -0,0 +1,25 @@
<?php
namespace App\Classes;
use GuzzleHttp\Client;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
abstract class Payments
{
abstract protected function connect(string $url,array $args=[]);
abstract public function getCustomers(): Collection;
abstract public function getDebits($opt=[]): Collection;
abstract public function getSettlements($opt=[]): Collection;
protected function getClient(string $base_uri): Client
{
return new Client(['base_uri'=>$base_uri]);
}
protected function mustPause()
{
return Cache::get('api_throttle');
}
}

View File

@@ -0,0 +1,61 @@
<?php
namespace App\Classes\Payments;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use App\Classes\Payments;
class Ezypay extends Payments
{
protected function connect(string $url,array $args=[])
{
if ($x=$this->mustPause()) {
Log::error('API Throttle, waiting .',['m'=>__METHOD__]);
sleep($x);
}
$client = $this->getClient(config('services.ezypay.base_uri'));
$result = $client->request('GET',$url.($args ? '?'.http_build_query($args) : ''),[
'headers' => [
'Authorization'=>'Basic '.base64_encode(config('services.ezypay.token_user').':'),
'Accept'=>'application/json',
],
]);
$api_remain = Arr::get($result->getHeader('X-RateLimit-Remaining'),0);
$api_reset = Arr::get($result->getHeader('X-RateLimit-Reset'),0);
if ($api_remain == 0) {
Log::error('API Throttle.',['m'=>__METHOD__]);
Cache::put('api_throttle',$api_reset,now()->addSeconds($api_reset));
}
return json_decode($result->getBody()->getContents());
}
public function getCustomers(): Collection
{
return Cache::remember(__METHOD__,86400,function() {
return collect($this->connect('customers'));
});
}
public function getDebits($opt=[]): Collection
{
return Cache::remember(__METHOD__.http_build_query($opt),86400,function() use ($opt) {
return Collect($this->connect('debits'.($opt ? '?'.http_build_query($opt) : '')));
});
}
public function getSettlements($opt=[]): Collection
{
return Cache::remember(__METHOD__.http_build_query($opt),86400,function() use ($opt) {
return Collect($this->connect('settlements/'.config('services.ezypay.guid').($opt ? '?'.http_build_query($opt) : '')));
});
}
}

View File

@@ -0,0 +1,115 @@
<?php
namespace App\Console\Commands;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use App\Classes\Payments\Ezypay;
use App\Models\{Account,AccoutBilling,Checkout,Payment};
class EzypayImport extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'payments:ezypay';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Retrieve payments from Ezypay';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
/*
DB::listen(function($query) {
$this->warn('- SQL:'.json_encode(['sql'=>$query->sql,'binding'=>$query->bindings]));
});
*/
$poo = new Ezypay();
// Get our checkout IDs for this plugin
$cos = Checkout::where('plugin',config('services.ezypay.plugin'))->pluck('id');
foreach ($poo->getCustomers() as $c)
{
if ($c->BillingStatus == 'Inactive')
{
$this->info(sprintf('Ignoring INACTIVE: [%s] %s %s',$c->EzypayReferenceNumber,$c->Firstname,$c->Surname));
continue;
}
// Load Direct Debit Details
$ab = AccoutBilling::whereIN('checkout_id',$cos)->where('checkout_data',$c->EzypayReferenceNumber)->first();
if (! $ab)
{
$this->warn(sprintf('Missing: [%s] %s %s',$c->EzypayReferenceNumber,$c->Firstname,$c->Surname));
continue;
}
// Find the last payment logged
$last = Carbon::createFromTimestamp(Payment::whereIN('checkout_id',$cos)->where('account_id',$ab->service->account_id)->max('date_payment'));
$o = $poo->getDebits([
'customerId'=>$c->Id,
'dateFrom'=>$last->format('Y-m-d'),
'dateTo'=>$last->addQuarter()->format('Y-m-d'),
'pageSize'=>100,
]);
// Load the payments
if ($o->count())
{
foreach ($o->reverse() as $p)
{
// If not success, ignore it.
if (! $p->Status == 'Success')
continue;
$pd = Carbon::createFromFormat('Y-m-d?H:i:s.u',$p->Date);
$lp = $ab->service->account->payments->last();
if ($lp AND (($pd == $lp->date_payment) OR ($p->Id == $lp->checkout_data)))
continue;
// New Payment
$po = new Payment;
$po->site_id = 1; // @todo
$po->date_payment = $pd;
$po->checkout_id = '999'; // @todo
$po->checkout_data = $p->Id;
$po->total_amt = $p->Amount;
$ab->service->account->payments()->save($po);
$this->info(sprintf('Recorded: [%s] %s %s (%s)',$c->EzypayReferenceNumber,$c->Firstname,$c->Surname,$po->id));
}
}
}
}
}

View File

@@ -21,7 +21,7 @@ class UserAccountMerge extends Command
*
* @var string
*/
protected $description = 'Command description';
protected $description = 'This utility will create a User account from the Account entries';
/**
* Create a new command instance.

View File

@@ -12,6 +12,6 @@ class EncryptCookies extends Middleware
* @var array
*/
protected $except = [
//
'toggleState',
];
}

View File

@@ -16,13 +16,14 @@ class Account extends Model
protected $appends = [
'active_display',
'name',
'services_count_html',
'switch_url',
];
protected $visible = [
'id',
'company',
'active_display',
'name',
'services_count_html',
'switch_url',
];
@@ -40,6 +41,11 @@ class Account extends Model
return $this->belongsTo(Language::class);
}
public function payments()
{
return $this->hasMany(Payment::class);
}
public function services()
{
return $this->hasMany(Service::class);
@@ -55,11 +61,6 @@ class Account extends Model
return sprintf('<span class="btn-sm btn-block btn-%s text-center">%s</span>',$this->active ? 'success' : 'danger',$this->active ? 'Active' : 'Inactive');
}
public function getCompanyAttribute($value)
{
return $value ? $value : $this->user->SurFirstName;
}
public function getAccountIdAttribute()
{
return sprintf('%02s-%04s',$this->site_id,$this->id);
@@ -70,6 +71,11 @@ class Account extends Model
return sprintf('<a href="/r/account/view/%s">%s</a>',$this->id,$this->account_id);
}
public function getNameAttribute()
{
return $this->company ?: $this->user->SurFirstName;
}
public function getServicesCountHtmlAttribute()
{
return sprintf('%s <small>/%s</small>',$this->services->where('active',TRUE)->count(),$this->services->count());

View File

@@ -0,0 +1,18 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Traits\OrderServiceOptions;
class AccoutBilling extends Model
{
protected $table = 'ab_account_billing';
public $timestamps = FALSE;
public function service()
{
return $this->belongsTo(Service::class);
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Models\Base;
use Illuminate\Database\Eloquent\Model;
use App\Traits\NextKey;
abstract class ServiceType extends Model
{
use NextKey;
public $timestamps = FALSE;
public $dateFormat = 'U';
/**
* @NOTE: The service_id column could be discarded, if the id column=service_id
* @return \Illuminate\Database\Eloquent\Relations\MorphOne
*/
public function service()
{
return $this->morphOne(Service::class,'type','model','id');
}
}

16
app/Models/Checkout.php Normal file
View File

@@ -0,0 +1,16 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Checkout extends Model
{
protected $table = 'ab_checkout';
public $timestamps = FALSE;
public function payments()
{
return $this->hasMany(Payment::class);
}
}

16
app/Models/Module.php Normal file
View File

@@ -0,0 +1,16 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Module extends Model
{
protected $table = 'ab_module';
public $timestamps = FALSE;
public function record()
{
return $this->hasOne(Record::class);
}
}

View File

@@ -4,10 +4,20 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Traits\NextKey;
class Payment extends Model
{
use NextKey;
const CREATED_AT = 'date_orig';
const UPDATED_AT = 'date_last';
const RECORD_ID = 'payment';
public $incrementing = FALSE;
protected $table = 'ab_payment';
protected $dates = ['date_payment'];
protected $dateFormat = 'U';
protected $with = ['account.country.currency','items'];
protected $appends = [

View File

@@ -21,9 +21,14 @@ class Product extends Model
return $this->hasMany(Service::class);
}
/**
* Get the service category (from the product)
*
* @return string
*/
public function getCategoryAttribute()
{
return $this->prod_plugin_file;
return $this->prod_plugin_file ?: 'Other';
}
public function getContractTermAttribute()

11
app/Models/Record.php Normal file
View File

@@ -0,0 +1,11 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Record extends Model
{
protected $table = 'ab_record_id';
public $timestamps = FALSE;
}

View File

@@ -3,30 +3,32 @@
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Traits\NextKey;
class Service extends Model
{
use NextKey;
public $incrementing = FALSE;
const CREATED_AT = 'date_orig';
const UPDATED_AT = 'date_last';
protected $table = 'ab_service';
protected $with = ['product.descriptions','account.language','service_adsl','service_domain.tld','service_ssl','service_voip'];
protected $with = ['product.descriptions','account.language'];
protected $dates = ['date_last_invoice','date_next_invoice'];
public $dateFormat = 'U';
protected $casts = [
'order_info'=>'array',
];
const CREATED_AT = 'date_orig';
const UPDATED_AT = 'date_last';
protected $appends = [
'account_name',
'admin_service_id_url',
'category',
'name',
'name_full',
'name_short',
'next_invoice',
'product_category',
'product_name',
'service_id',
'service_id_url',
@@ -37,12 +39,11 @@ class Service extends Model
'account_name',
'admin_service_id_url',
'active',
'category',
'data_orig',
'id',
'name',
'name_full',
'name_short',
'next_invoice',
'product_category',
'product_name',
'service_id',
'service_id_url',
@@ -85,7 +86,7 @@ class Service extends Model
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function orderby()
public function orderedby()
{
return $this->belongsTo(Account::class);
}
@@ -100,31 +101,6 @@ class Service extends Model
return $this->belongsTo(Site::class);
}
public function service_adsl()
{
return $this->belongsTo(ServiceAdsl::class,'id','service_id');
}
public function service_domain()
{
return $this->belongsTo(ServiceDomain::class,'id','service_id');
}
public function service_host()
{
return $this->belongsTo(ServiceHost::class,'id','service_id');
}
public function service_ssl()
{
return $this->belongsTo(ServiceSsl::class,'id','service_id');
}
public function service_voip()
{
return $this->belongsTo(ServiceVoip::class,'id','service_id');
}
/**
* Product of the service
*
@@ -135,6 +111,21 @@ class Service extends Model
return $this->belongsTo(Product::class);
}
public function type()
{
return $this->morphTo(null,'model','id','service_id');
}
/**
* Only query active categories
*/
public function scopeActive($query)
{
return $query->where(function () use ($query) {
$query->where('active',TRUE)->orWhereNotIn('order_status',$this->inactive_status);
});
}
/**
* Find inactive services.
*
@@ -144,57 +135,66 @@ class Service extends Model
public function scopeInActive($query)
{
return $query->where(function () use ($query) {
return $query->where('active',FALSE)->orWhereIn('order_status',$this->inactive_status);
$query->where('active',FALSE)->orWhereIn('order_status',$this->inactive_status);
});
}
/**
* Only query active categories
* Name of the account for this service
*
* @return mixed
*/
public function scopeActive($query)
{
return $query->where(function () use ($query) {
return $query->where('active',TRUE)->orWhereNotIn('order_status',$this->inactive_status);
});
}
public function getAccountNameAttribute()
{
return $this->account->company;
return $this->account->name;
}
/**
* Get the Product's Category for this service
*
*/
public function getProductCategoryAttribute(): string
{
return $this->product->category;
}
/**
* Get the Product's Short Name for the service
*
* @return string
*/
public function getProductNameAttribute(): string
{
return $this->product->name($this->account->language);
}
/**
* Return the short name for the service.
* EG:
* For ADSL, this would be the phone number,
* For Hosting, this would be the domain name, etc
*/
public function getNameShortAttribute()
{
return $this->model ? $this->type->name : NULL;
}
/**
* Return the date for the next invoice
*
* @return null
*/
public function getNextInvoiceAttribute()
{
return $this->date_next_invoice ? $this->date_next_invoice->format('Y-m-d') : NULL;
}
//@todo
public function getAdminServiceIdUrlAttribute()
{
return sprintf('<a href="/a/service/%s">%s</a>',$this->id,$this->service_id);
}
public function getCategoryAttribute()
{
// @todo: All services should be linked to a product. This might require data cleaning for old services not linked to a product.
return is_object($this->product) ? $this->product->category : 'Unknown Product';
}
public function getNameAttribute()
{
if (! isset($this->ServicePlugin()->name))
return 'Unknown';
return $this->ServicePlugin()->name;
}
public function getNameFullAttribute()
{
if (! isset($this->ServicePlugin()->full_name))
return 'Unknown';
return $this->ServicePlugin()->full_name;
}
public function getNextInvoiceAttribute()
{
return $this->date_next_invoice ? $this->date_next_invoice->format('Y-m-d') : NULL;
}
/**
* This function will present the Order Info Details
*/
@@ -216,12 +216,6 @@ class Service extends Model
return $result;
}
public function getProductNameAttribute()
{
// @todo: All services should be linked to a product. This might require data cleaning for old services not linked to a product.
return is_object($this->product) ? $this->product->name($this->account->language) : 'Unknown Product';
}
public function getServiceExpireAttribute()
{
return 'TBA';

View File

@@ -1,16 +1,11 @@
<?php
namespace App\Models;
namespace App\Models\Service;
use App\Models\Service_Model as Model;
use App\Traits\NextKey;
class ServiceAdsl extends Model
class Adsl extends \App\Models\Base\ServiceType
{
use NextKey;
// @todo column service_id can be removed.
protected $table = 'ab_service__adsl';
public $timestamps = FALSE;
public function getFullNameAttribute()
{

View File

@@ -0,0 +1,18 @@
<?php
namespace App\Models\Service;
class Domain extends \App\Models\Base\ServiceType
{
protected $table = 'ab_service__domain';
public function tld()
{
return $this->belongsTo(\App\Models\DomainTld::class,'domain_tld_id');
}
public function getNameAttribute()
{
return sprintf('%s.%s',$this->domain_name,$this->tld->name);
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace App\Models\Service;
class Host extends \App\Models\Base\ServiceType
{
protected $table = 'ab_service__hosting';
public function getNameAttribute()
{
return sprintf('%s',$this->domain_name);
}
}

View File

@@ -1,15 +1,9 @@
<?php
namespace App\Models;
namespace App\Models\Service;
use App\Models\Service_Model as Model;
use App\Traits\NextKey;
use App\Classes\SSL;
class ServiceSsl extends Model
class SSL extends \App\Models\Base\ServiceType
{
use NextKey;
protected $table = 'ab_service__ssl';
protected $_o = NULL;
@@ -22,7 +16,7 @@ class ServiceSsl extends Model
{
if (is_null($this->_o))
{
$this->_o = new SSL;
$this->_o = new \App\Classes\SSL;
if ($this->cert)
$this->_o->crt($this->cert);

View File

@@ -1,15 +1,10 @@
<?php
namespace App\Models;
namespace App\Models\Service;
use App\Models\Service_Model as Model;
use App\Traits\NextKey;
class ServiceVoip extends Model
class Voip extends \App\Models\Base\ServiceType
{
use NextKey;
protected $table = 'ab_service__voip';
public $timestamps = FALSE;
public function getFullNameAttribute()
{

View File

@@ -1,24 +0,0 @@
<?php
namespace App\Models;
use App\Models\Service_Model as Model;
use App\Traits\NextKey;
class ServiceDomain extends Model
{
use NextKey;
protected $table = 'ab_service__domain';
public $timestamps = FALSE;
public function tld()
{
return $this->belongsTo(DomainTld::class,'domain_tld_id');
}
public function getNameAttribute()
{
return sprintf('%s.%s',$this->domain_name,$this->tld->name);
}
}

View File

@@ -1,19 +0,0 @@
<?php
namespace App\Models;
use App\Models\Service_Model as Model;
use App\Traits\NextKey;
class ServiceHost extends Model
{
use NextKey;
protected $table = 'ab_service__hosting';
public $timestamps = FALSE;
public function getNameAttribute()
{
return sprintf('%s',$this->domain_name);
}
}

View File

@@ -1,22 +0,0 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
/**
* Abstract Base Model for Services
*/
abstract class Service_Model extends Model
{
public function service()
{
return $this->belongsTo(Service::class);
}
/**
* The name of the server, that will appear on invoices/service displays
* @return mixed
*/
abstract public function getNameAttribute();
}

View File

@@ -2,9 +2,13 @@
/**
* Works out the next ID to use for an Eloquent Table.
*
* If we update records, we update the record_id table
*/
namespace App\Traits;
use App\Models\Module;
trait NextKey
{
public static function boot()
@@ -15,6 +19,16 @@ trait NextKey
{
$model->id = self::NextId();
});
static::saved(function($model)
{
if (! $model::RECORD_ID)
throw new \Exception('Missing record_id const for '.get_class($model));
$mo = Module::where('name',$model::RECORD_ID)->firstOrFail();
$mo->record->id = $model->id;
$mo->record->save();
});
}
public static function NextId()