akaunting/app/Jobs/Common/DeleteCompany.php

83 lines
2.0 KiB
PHP
Raw Normal View History

2019-11-16 10:21:14 +03:00
<?php
namespace App\Jobs\Common;
use App\Abstracts\Job;
2021-05-06 00:13:52 +03:00
use App\Events\Common\CompanyDeleted;
use App\Events\Common\CompanyDeleting;
2019-11-16 10:21:14 +03:00
use App\Traits\Users;
class DeleteCompany extends Job
{
use Users;
protected $company;
2021-04-16 00:59:43 +03:00
protected $current_company_id;
2020-12-25 12:08:15 +03:00
2019-11-16 10:21:14 +03:00
/**
* Create a new job instance.
*
2021-04-16 00:59:43 +03:00
* @param $company
2019-11-16 10:21:14 +03:00
*/
2021-04-16 00:59:43 +03:00
public function __construct($company)
2019-11-16 10:21:14 +03:00
{
$this->company = $company;
2021-04-16 00:59:43 +03:00
$this->current_company_id = company_id();
2019-11-16 10:21:14 +03:00
}
/**
* Execute the job.
*
2020-03-28 22:50:06 +03:00
* @return boolean|Exception
2019-11-16 10:21:14 +03:00
*/
public function handle()
{
$this->authorize();
2021-05-06 00:13:52 +03:00
$this->company->makeCurrent();
event(new CompanyDeleting($this->company, $this->current_company_id));
2020-06-26 13:40:19 +03:00
\DB::transaction(function () {
$this->deleteRelationships($this->company, [
2021-05-12 17:17:22 +03:00
'accounts', 'document_histories', 'document_item_taxes', 'document_items', 'document_totals', 'documents', 'categories',
'contacts', 'currencies', 'dashboards', 'email_templates', 'items', 'module_histories', 'modules', 'reconciliations',
2020-06-26 13:40:19 +03:00
'recurring', 'reports', 'settings', 'taxes', 'transactions', 'transfers', 'widgets',
]);
2019-12-22 15:58:48 +03:00
$this->company->users()->detach();
2020-06-26 13:40:19 +03:00
$this->company->delete();
});
2019-11-16 10:21:14 +03:00
2021-05-06 00:13:52 +03:00
event(new CompanyDeleted($this->company, $this->current_company_id));
company($this->current_company_id)->makeCurrent();
2019-11-16 10:21:14 +03:00
return true;
}
/**
* Determine if this action is applicable.
*
* @return void
*/
public function authorize()
{
// Can't delete active company
2021-04-16 00:59:43 +03:00
if ($this->company->id == $this->current_company_id) {
2019-11-16 10:21:14 +03:00
$message = trans('companies.error.delete_active');
throw new \Exception($message);
}
// Check if user can access company
2021-04-16 00:59:43 +03:00
if ($this->isNotUserCompany($this->company->id)) {
2019-11-16 10:21:14 +03:00
$message = trans('companies.error.not_user_company');
throw new \Exception($message);
}
}
}