1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-16 08:02:40 +01:00
invoiceninja/app/Models/Client.php

725 lines
23 KiB
PHP
Raw Normal View History

<?php
2019-05-11 05:32:07 +02:00
/**
* Invoice Ninja (https://invoiceninja.com).
2019-05-11 05:32:07 +02:00
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
* @copyright Copyright (c) 2021. Invoice Ninja LLC (https://invoiceninja.com)
2019-05-11 05:32:07 +02:00
*
2021-06-16 08:58:16 +02:00
* @license https://www.elastic.co/licensing/elastic-license
2019-05-11 05:32:07 +02:00
*/
namespace App\Models;
use App\DataMapper\ClientSettings;
2019-04-29 02:54:26 +02:00
use App\DataMapper\CompanySettings;
2020-10-28 11:10:49 +01:00
use App\Models\Presenters\ClientPresenter;
use App\Services\Client\ClientService;
2021-06-10 05:56:02 +02:00
use App\Utils\Traits\AppSetup;
2019-06-03 07:31:20 +02:00
use App\Utils\Traits\GeneratesCounter;
2019-04-30 08:02:39 +02:00
use App\Utils\Traits\MakesDates;
use App\Utils\Traits\MakesHash;
2020-10-28 11:10:49 +01:00
use Exception;
use Illuminate\Contracts\Translation\HasLocalePreference;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Cache;
use Laracasts\Presenter\PresentableTrait;
class Client extends BaseModel implements HasLocalePreference
{
use PresentableTrait;
use MakesHash;
2019-04-30 08:02:39 +02:00
use MakesDates;
use SoftDeletes;
2019-03-28 11:07:45 +01:00
use Filterable;
2019-06-03 07:31:20 +02:00
use GeneratesCounter;
2021-06-10 05:56:02 +02:00
use AppSetup;
2020-10-28 11:10:49 +01:00
protected $presenter = ClientPresenter::class;
2019-07-30 00:28:38 +02:00
protected $hidden = [
'id',
2019-07-30 00:28:38 +02:00
'private_notes',
'user_id',
'company_id',
'last_login',
];
protected $fillable = [
'assigned_user_id',
'name',
'website',
'private_notes',
'industry_id',
'size_id',
'address1',
'address2',
'city',
'state',
'postal_code',
'country_id',
'custom_value1',
'custom_value2',
'custom_value3',
'custom_value4',
'shipping_address1',
'shipping_address2',
'shipping_city',
'shipping_state',
'shipping_postal_code',
'shipping_country_id',
'settings',
'payment_terms',
'vat_number',
'id_number',
2019-10-07 22:49:16 +02:00
'group_settings_id',
'public_notes',
2021-01-25 11:34:12 +01:00
'phone',
'number',
];
2019-04-29 02:54:26 +02:00
protected $with = [
2020-10-26 01:58:08 +01:00
'gateway_tokens',
2021-05-04 14:04:07 +02:00
'documents',
'contacts.company',
// 'currency',
// 'primary_contact',
// 'country',
// 'contacts',
// 'shipping_country',
// 'company',
2019-04-29 02:54:26 +02:00
];
protected $casts = [
'is_deleted' => 'boolean',
'country_id' => 'string',
'settings' => 'object',
'updated_at' => 'timestamp',
'created_at' => 'timestamp',
'deleted_at' => 'timestamp',
];
2020-07-23 05:55:11 +02:00
protected $touches = [];
/**
* Whitelisted fields for using from query parameters on subscriptions request.
*
* @var string[]
*/
public static $subscriptions_fillable = [
'assigned_user_id',
'address1',
'address2',
'city',
'state',
'postal_code',
'country_id',
'custom_value1',
'custom_value2',
'custom_value3',
'custom_value4',
'shipping_address1',
'shipping_address2',
'shipping_city',
'shipping_state',
'shipping_postal_code',
'shipping_country_id',
'payment_terms',
'vat_number',
'id_number',
'public_notes',
'phone',
];
public function getEntityType()
{
return self::class;
}
public function ledger()
{
2020-06-20 01:23:41 +02:00
return $this->hasMany(CompanyLedger::class)->orderBy('id', 'desc');
}
2020-07-01 07:51:19 +02:00
public function company_ledger()
{
return $this->morphMany(CompanyLedger::class, 'company_ledgerable');
}
2019-09-08 12:39:13 +02:00
public function gateway_tokens()
{
return $this->hasMany(ClientGatewayToken::class);
}
2019-09-13 00:33:48 +02:00
/**
* Retrieves the specific payment token per
* gateway - per payment method.
2019-09-13 00:33:48 +02:00
*
* Allows the storage of multiple tokens
* per client per gateway per payment_method
*
2019-09-25 04:07:33 +02:00
* @param int $company_gateway_id The company gateway ID
2019-09-13 00:33:48 +02:00
* @param int $payment_method_id The payment method ID
* @return ClientGatewayToken The client token record
*/
2019-09-25 04:07:33 +02:00
public function gateway_token($company_gateway_id, $payment_method_id)
2019-09-13 00:33:48 +02:00
{
2019-09-25 04:07:33 +02:00
return $this->gateway_tokens()
->whereCompanyGatewayId($company_gateway_id)
->whereGatewayTypeId($payment_method_id)
2019-09-13 00:33:48 +02:00
->first();
}
public function credits()
{
return $this->hasMany(Credit::class)->withTrashed();
}
public function activities()
{
2020-06-20 01:23:41 +02:00
return $this->hasMany(Activity::class)->orderBy('id', 'desc');
}
public function contacts()
{
return $this->hasMany(ClientContact::class)->orderBy('is_primary', 'desc');
}
public function primary_contact()
{
return $this->hasMany(ClientContact::class)->where('is_primary', true);
}
public function company()
{
return $this->belongsTo(Company::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function assigned_user()
{
return $this->belongsTo(User::class, 'assigned_user_id', 'id');
}
2019-01-26 10:34:38 +01:00
public function country()
{
return $this->belongsTo(Country::class);
}
public function invoices()
{
2020-07-07 09:54:21 +02:00
return $this->hasMany(Invoice::class)->withTrashed();
2019-01-26 10:34:38 +01:00
}
2021-07-02 08:36:14 +02:00
public function recurring_invoices()
{
return $this->hasMany(RecurringInvoice::class)->withTrashed();
}
2019-01-26 10:34:38 +01:00
public function shipping_country()
{
return $this->belongsTo(Country::class, 'shipping_country_id', 'id');
}
2020-08-24 04:45:53 +02:00
public function system_logs()
{
return $this->hasMany(SystemLog::class);
}
2019-04-24 02:22:02 +02:00
public function timezone()
{
2019-09-11 07:32:47 +02:00
return Timezone::find($this->getSetting('timezone_id'));
2019-04-24 02:22:02 +02:00
}
public function language()
{
$languages = Cache::get('languages');
2021-06-10 05:56:02 +02:00
if(!$languages)
$this->buildCache(true);
return $languages->filter(function ($item) {
return $item->id == $this->getSetting('language_id');
})->first();
2021-06-10 04:24:32 +02:00
}
public function locale()
{
return $this->language()->locale ?: 'en';
}
public function date_format()
{
$date_formats = Cache::get('date_formats');
return $date_formats->filter(function ($item) {
return $item->id == $this->getSetting('date_format_id');
})->first()->format;
}
2019-08-28 04:36:53 +02:00
public function currency()
{
$currencies = Cache::get('currencies');
2021-06-10 05:56:02 +02:00
if(!$currencies)
$this->buildCache(true);
return $currencies->filter(function ($item) {
return $item->id == $this->getSetting('currency_id');
})->first();
2019-08-28 04:36:53 +02:00
}
public function service() :ClientService
{
return new ClientService($this);
}
public function updateBalance($amount) :ClientService
{
return $this->service()->updateBalance($amount);
}
/**
* Adjusts client "balances" when a client
* makes a payment that goes on file, but does
* not effect the client.balance record.
*
* @param float $amount Adjustment amount
* @return Client
*/
// public function processUnappliedPayment($amount) :Client
// {
// return $this->service()->updatePaidToDate($amount)
// ->adjustCreditBalance($amount)
// ->save();
// }
2019-09-12 05:23:44 +02:00
/**
* Returns the entire filtered set
2019-09-12 05:23:44 +02:00
* of settings which have been merged from
* Client > Group > Company levels.
*
* @return stdClass stdClass object of settings
2019-09-12 05:23:44 +02:00
*/
public function getMergedSettings() :object
2019-04-29 02:54:26 +02:00
{
if ($this->group_settings !== null) {
2019-09-19 07:50:05 +02:00
$group_settings = ClientSettings::buildClientSettings($this->group_settings->settings, $this->settings);
2019-09-11 07:32:47 +02:00
2019-09-19 07:50:05 +02:00
return ClientSettings::buildClientSettings($this->company->settings, $group_settings);
2019-09-11 07:32:47 +02:00
}
return CompanySettings::setProperties(ClientSettings::buildClientSettings($this->company->settings, $this->settings));
}
2019-09-12 05:23:44 +02:00
/**
* Returns a single setting
* which cascades from
* Client > Group > Company.
*
2019-09-12 05:23:44 +02:00
* @param string $setting The Setting parameter
* @return mixed The setting requested
*/
2019-09-10 12:25:29 +02:00
public function getSetting($setting)
{
2019-09-19 07:50:05 +02:00
/*Client Settings*/
if ($this->settings && property_exists($this->settings, $setting) && isset($this->settings->{$setting})) {
/*need to catch empty string here*/
if (is_string($this->settings->{$setting}) && (iconv_strlen($this->settings->{$setting}) >= 1)) {
2019-09-19 07:50:05 +02:00
return $this->settings->{$setting};
}
}
2019-09-10 12:25:29 +02:00
2019-10-08 13:14:23 +02:00
/*Group Settings*/
if ($this->group_settings && (property_exists($this->group_settings->settings, $setting) !== false) && (isset($this->group_settings->settings->{$setting}) !== false)) {
return $this->group_settings->settings->{$setting};
2019-09-19 07:50:05 +02:00
}
2019-10-08 13:14:23 +02:00
/*Company Settings*/
elseif ((property_exists($this->company->settings, $setting) != false) && (isset($this->company->settings->{$setting}) !== false)) {
2019-09-11 05:46:23 +02:00
return $this->company->settings->{$setting};
2019-09-19 07:50:05 +02:00
}
elseif( property_exists(CompanySettings::defaults(), $setting) ) {
return CompanySettings::defaults()->{$setting};
}
return '';
// throw new \Exception("Settings corrupted", 1);
2019-10-08 13:14:23 +02:00
}
public function getSettingEntity($setting)
{
/*Client Settings*/
if ($this->settings && (property_exists($this->settings, $setting) !== false) && (isset($this->settings->{$setting}) !== false)) {
2019-10-08 13:14:23 +02:00
/*need to catch empty string here*/
if (is_string($this->settings->{$setting}) && (iconv_strlen($this->settings->{$setting}) >= 1)) {
2019-10-08 13:14:23 +02:00
return $this;
}
}
/*Group Settings*/
if ($this->group_settings && (property_exists($this->group_settings->settings, $setting) !== false) && (isset($this->group_settings->settings->{$setting}) !== false)) {
return $this->group_settings;
2019-10-08 13:14:23 +02:00
}
/*Company Settings*/
if ((property_exists($this->company->settings, $setting) != false) && (isset($this->company->settings->{$setting}) !== false)) {
2019-10-08 13:14:23 +02:00
return $this->company;
}
2020-10-28 11:10:49 +01:00
throw new Exception('Could not find a settings object', 1);
2019-09-10 12:25:29 +02:00
}
2019-04-28 07:31:32 +02:00
public function documents()
{
return $this->morphMany(Document::class, 'documentable');
}
2019-09-10 04:30:43 +02:00
public function group_settings()
{
return $this->belongsTo(GroupSetting::class);
}
2019-09-13 07:52:01 +02:00
/**
* Returns the first Credit Card Gateway.
*
* @return null|CompanyGateway The Priority Credit Card gateway
2019-09-13 07:52:01 +02:00
*/
public function getCreditCardGateway() :?CompanyGateway
{
$company_gateways = $this->getSetting('company_gateway_ids');
/* It is very important to respect the order of the company_gateway_ids as they are ordered by priority*/
if (strlen($company_gateways) >= 1) {
$transformed_ids = $this->transformKeys(explode(',', $company_gateways));
$gateways = $this->company
->company_gateways
->whereIn('id', $transformed_ids)
->sortby(function ($model) use ($transformed_ids) {
return array_search($model->id, $transformed_ids);
});
} else {
2020-11-25 15:19:52 +01:00
$gateways = $this->company->company_gateways;
}
2019-09-13 07:52:01 +02:00
foreach ($gateways as $gateway) {
2021-06-30 13:21:46 +02:00
if (in_array(GatewayType::CREDIT_CARD, $gateway->driver($this)->gatewayTypeEnabled(GatewayType::CREDIT_CARD))) {
2019-09-13 07:52:01 +02:00
return $gateway;
}
2019-09-13 07:52:01 +02:00
}
return null;
}
2020-07-03 10:14:15 +02:00
public function getBankTransferGateway() :?CompanyGateway
2019-09-25 04:07:33 +02:00
{
2020-07-03 10:14:15 +02:00
$company_gateways = $this->getSetting('company_gateway_ids');
if (strlen($company_gateways) >= 1) {
$transformed_ids = $this->transformKeys(explode(',', $company_gateways));
$gateways = $this->company
->company_gateways
->whereIn('id', $transformed_ids)
->sortby(function ($model) use ($transformed_ids) {
return array_search($model->id, $transformed_ids);
});
2020-07-03 10:14:15 +02:00
} else {
$gateways = $this->company->company_gateways;
2019-09-25 04:07:33 +02:00
}
2020-07-03 10:14:15 +02:00
foreach ($gateways as $gateway) {
2021-06-30 13:21:46 +02:00
if ($this->currency()->code == 'USD' && in_array(GatewayType::BANK_TRANSFER, $gateway->driver($this)->gatewayTypeEnabled(GatewayType::BANK_TRANSFER))) {
2020-07-03 10:14:15 +02:00
return $gateway;
}
2021-06-30 13:21:46 +02:00
if ($this->currency()->code == 'EUR' && in_array(GatewayType::SEPA, $gateway->driver($this)->gatewayTypeEnabled(GatewayType::SEPA))) {
2020-07-03 10:14:15 +02:00
return $gateway;
}
}
return null;
2019-09-25 04:07:33 +02:00
}
2020-07-03 02:56:36 +02:00
2020-07-03 14:39:29 +02:00
public function getBankTransferMethodType()
{
if ($this->currency()->code == 'USD') {
return GatewayType::BANK_TRANSFER;
}
if ($this->currency()->code == 'EUR') {
return GatewayType::SEPA;
}
}
2020-07-03 10:14:15 +02:00
public function getCurrencyCode()
2020-07-03 02:56:36 +02:00
{
2020-07-03 10:14:15 +02:00
if ($this->currency()) {
return $this->currency()->code;
}
2020-07-03 02:56:36 +02:00
2020-07-03 10:14:15 +02:00
return 'USD';
2020-07-03 02:56:36 +02:00
}
2019-09-09 08:25:33 +02:00
/**
* Generates an array of payment urls per client
* for a given amount.
*
* The route produced will provide the
2019-09-09 08:25:33 +02:00
* company_gateway and payment_type ids
*
* The invoice/s will need to be injected
* upstream of this method as they are not
2019-09-09 08:25:33 +02:00
* included in this logic.
*
2019-09-09 08:25:33 +02:00
* @param float $amount The amount to be charged
* @return array Array of payment labels and urls
2021-01-18 03:59:06 +01:00
* @deprecated 5.0.38 - see service()->getPaymentMethods($amount);
2019-09-09 08:25:33 +02:00
*/
// public function getPaymentMethods($amount) :array
// {
// //this method will get all the possible gateways a client can pay with
// //but we also need to consider payment methods that are already stored
// //so we MUST filter the company gateways and remove duplicates.
// //Also need to harvest the list of client gateway tokens and present these
// //for instant payment
// $company_gateways = $this->getSetting('company_gateway_ids');
// //we need to check for "0" here as we disable a payment gateway for a client with the number "0"
// if ($company_gateways || $company_gateways == '0') {
// $transformed_ids = $this->transformKeys(explode(',', $company_gateways));
// $gateways = $this->company
// ->company_gateways
// ->whereIn('id', $transformed_ids)
// ->where('gateway_key', '!=', '54faab2ab6e3223dbe848b1686490baa')
// ->sortby(function ($model) use ($transformed_ids) { //company gateways are sorted in order of priority
// return array_search($model->id, $transformed_ids);// this closure sorts for us
// });
// } else {
// $gateways = $this->company
// ->company_gateways
// ->where('gateway_key', '!=', '54faab2ab6e3223dbe848b1686490baa')
// ->where('is_deleted', false);
// }
// $payment_methods = [];
// foreach ($gateways as $gateway) {
// foreach ($gateway->driver($this)->gatewayTypes() as $type) {
// if (isset($gateway->fees_and_limits) && property_exists($gateway->fees_and_limits, $type)) {
// if ($this->validGatewayForAmount($gateway->fees_and_limits->{$type}, $amount)) {
// $payment_methods[] = [$gateway->id => $type];
// }
// } else {
// $payment_methods[] = [$gateway->id => $type];
// }
// }
// }
// $payment_methods_collections = collect($payment_methods);
// //** Plucks the remaining keys into its own collection
// $payment_methods_intersect = $payment_methods_collections->intersectByKeys($payment_methods_collections->flatten(1)->unique());
// // handle custom gateways as they are not unique'd()---------------------------------------------------------
// // we need to split the query here as we allow multiple custom gateways, so we must show all of them, they query logic
// // above only pulls in unique gateway types.. ie.. we only allow 1 credit card gateway, but many custom gateways.
// if ($company_gateways || $company_gateways == '0') {
// $transformed_ids = $this->transformKeys(explode(',', $company_gateways));
// $gateways = $this->company
// ->company_gateways
// ->whereIn('id', $transformed_ids)
// ->where('gateway_key', '=', '54faab2ab6e3223dbe848b1686490baa')
// ->sortby(function ($model) use ($transformed_ids) { //company gateways are sorted in order of priority
// return array_search($model->id, $transformed_ids);// this closure sorts for us
// });
// } else {
// $gateways = $this->company
// ->company_gateways
// ->where('gateway_key', '=', '54faab2ab6e3223dbe848b1686490baa')
// ->where('is_deleted', false);
// }
// //note we have to use GatewayType::CREDIT_CARD as alias for CUSTOM
// foreach ($gateways as $gateway) {
// foreach ($gateway->driver($this)->gatewayTypes() as $type) {
// if (isset($gateway->fees_and_limits) && property_exists($gateway->fees_and_limits, $type)) {
// if ($this->validGatewayForAmount($gateway->fees_and_limits->{GatewayType::CREDIT_CARD}, $amount)) {
// $payment_methods_intersect->push([$gateway->id => $type]);
// }
// } else {
// $payment_methods_intersect->push([$gateway->id => NULL]);
// }
// }
// }
// //handle custom gateways as they are not unique'd()---------------------------------------------------------
// $payment_urls = [];
// foreach ($payment_methods_intersect as $key => $child_array) {
// foreach ($child_array as $gateway_id => $gateway_type_id) {
// $gateway = CompanyGateway::find($gateway_id);
// $fee_label = $gateway->calcGatewayFeeLabel($amount, $this);
// if(!$gateway_type_id){
// $payment_urls[] = [
// 'label' => $gateway->getConfigField('name') . $fee_label,
// 'company_gateway_id' => $gateway_id,
// 'gateway_type_id' => GatewayType::CREDIT_CARD,
// ];
// }
// else
// {
// $payment_urls[] = [
// 'label' => $gateway->getTypeAlias($gateway_type_id) . $fee_label,
// 'company_gateway_id' => $gateway_id,
// 'gateway_type_id' => $gateway_type_id,
// ];
// }
// }
// }
// if (($this->getSetting('use_credits_payment') == 'option' || $this->getSetting('use_credits_payment') == 'always') && $this->service()->getCreditBalance() > 0) {
// // Show credits as only payment option if both statements are true.
// if (
// $this->service()->getCreditBalance() > $amount
// && $this->getSetting('use_credits_payment') == 'always') {
// $payment_urls = [];
// }
// $payment_urls[] = [
// 'label' => ctrans('texts.apply_credit'),
// 'company_gateway_id' => CompanyGateway::GATEWAY_CREDIT,
// 'gateway_type_id' => GatewayType::CREDIT,
// ];
// }
// return $payment_urls;
// }
public function validGatewayForAmount($fees_and_limits_for_payment_type, $amount) :bool
2020-10-12 06:10:34 +02:00
{
2020-11-25 15:19:52 +01:00
if (isset($fees_and_limits_for_payment_type)) {
$fees_and_limits = $fees_and_limits_for_payment_type;
} else {
return true;
}
2020-10-12 06:10:34 +02:00
2020-11-25 15:19:52 +01:00
if ((property_exists($fees_and_limits, 'min_limit')) && $fees_and_limits->min_limit !== null && $fees_and_limits->min_limit != -1 && $amount < $fees_and_limits->min_limit) {
return false;
}
2020-10-12 06:10:34 +02:00
2020-11-25 15:19:52 +01:00
if ((property_exists($fees_and_limits, 'max_limit')) && $fees_and_limits->max_limit !== null && $fees_and_limits->max_limit != -1 && $amount > $fees_and_limits->max_limit) {
return false;
}
2020-10-12 06:10:34 +02:00
2020-11-25 15:19:52 +01:00
return true;
2020-10-12 06:10:34 +02:00
}
public function preferredLocale()
{
$languages = Cache::get('languages');
2021-06-10 05:56:02 +02:00
if(!$languages)
$this->buildCache(true);
return $languages->filter(function ($item) {
return $item->id == $this->getSetting('language_id');
})->first()->locale;
}
2021-06-12 13:50:01 +02:00
public function invoice_filepath($invitation)
{
$contact_key = $invitation->contact->contact_key;
return $this->company->company_key.'/'.$this->client_hash.'/'.$contact_key.'/invoices/';
}
2021-06-12 13:50:01 +02:00
public function quote_filepath($invitation)
{
2021-06-12 13:50:01 +02:00
$contact_key = $invitation->contact->contact_key;
return $this->company->company_key.'/'.$this->client_hash.'/'.$contact_key.'/quotes/';
}
2021-06-12 13:50:01 +02:00
public function credit_filepath($invitation)
{
2021-06-12 13:50:01 +02:00
$contact_key = $invitation->contact->contact_key;
return $this->company->company_key.'/'.$this->client_hash.'/'.$contact_key.'/credits/';
}
2021-06-12 13:50:01 +02:00
public function recurring_invoice_filepath($invitation)
{
2021-06-12 13:50:01 +02:00
$contact_key = $invitation->contact->contact_key;
return $this->company->company_key.'/'.$this->client_hash.'/'.$contact_key.'/recurring_invoices/';
}
public function company_filepath()
{
return $this->company->company_key.'/';
}
public function document_filepath()
{
return $this->company->company_key.'/documents/';
}
public function setCompanyDefaults($data, $entity_name) :array
{
$defaults = [];
if (! (array_key_exists('terms', $data) && strlen($data['terms']) > 1)) {
$defaults['terms'] = $this->getSetting($entity_name.'_terms');
} elseif (array_key_exists('terms', $data)) {
$defaults['terms'] = $data['terms'];
}
if (! (array_key_exists('footer', $data) && strlen($data['footer']) > 1)) {
$defaults['footer'] = $this->getSetting($entity_name.'_footer');
} elseif (array_key_exists('footer', $data)) {
$defaults['footer'] = $data['footer'];
}
if (strlen($this->public_notes) >= 1) {
$defaults['public_notes'] = $this->public_notes;
}
return $defaults;
}
2020-06-12 14:48:54 +02:00
public function payments()
{
return $this->hasMany(Payment::class);
}
2021-06-10 23:34:03 +02:00
public function timezone_offset()
{
2021-06-11 23:41:02 +02:00
$offset = 0;
2021-06-10 23:34:03 +02:00
$entity_send_time = $this->getSetting('entity_send_time');
if($entity_send_time == 0)
return 0;
$timezone = $this->company->timezone();
2021-06-11 23:41:02 +02:00
$offset -= $timezone->utc_offset;
$offset += ($entity_send_time * 3600);
2021-06-10 23:34:03 +02:00
return $offset;
}
}