286 lines
8.8 KiB
PHP
286 lines
8.8 KiB
PHP
<?php
|
||
/*
|
||
* Copyright (c) 2023.
|
||
*
|
||
* A.Сапаргалиев
|
||
* ТОО "Дизайн лаборатория А7"
|
||
* Астана
|
||
*/
|
||
|
||
namespace modules\Auth\Http\Controllers;
|
||
|
||
use A7kz\Platform\Helpers\Facade\Helper;
|
||
use A7kz\Platform\Http\Controllers\Controller;
|
||
use A7kz\Platform\Models\UniModel;
|
||
use A7kz\Platform\Modules\Platform\Acl\Facades\Acl;
|
||
use A7kz\Platform\Modules\Platform\Segment\Facades\Segment;
|
||
use Carbon\Carbon;
|
||
use Illuminate\Http\RedirectResponse;
|
||
use Illuminate\Http\Request;
|
||
use Illuminate\Support\Facades\Auth;
|
||
use Illuminate\Support\Facades\Cache;
|
||
use Illuminate\Support\Facades\Session;
|
||
use Illuminate\Support\Facades\Validator;
|
||
|
||
class RegisterCompanyController extends Controller
|
||
{
|
||
const COWORKER_ROLE = 'coworker';
|
||
const DIRECTOR_ROLE = 'director';
|
||
const DEFAULT_COMPANY_ID = 0;
|
||
|
||
public function checkBiniinAjax(Request $request) {
|
||
$validation = Validator::make(['biniin' => $request->get('biniin')], $this->getBiniinRules());
|
||
|
||
if ($validation->fails()) {
|
||
return [
|
||
'status' => 'error',
|
||
'message' => __('Неправильно введен БИН/ИИН')
|
||
];
|
||
}
|
||
|
||
$biniin = $validation->validated()['biniin'];
|
||
$company = $this->getCompanyByBiniin($biniin);
|
||
|
||
if ($company) {
|
||
return [
|
||
'status' => 'success',
|
||
'data' => [
|
||
'biniin' => $biniin,
|
||
'name' => $company->name,
|
||
'fullname' => $company->fullname,
|
||
'companyExists' => true
|
||
]
|
||
];
|
||
}
|
||
else {
|
||
$inputData = [
|
||
'biniin' => $biniin
|
||
];
|
||
$minStat = $this->minStat($biniin);
|
||
|
||
if ($minStat['status'] == 2) {
|
||
$inputData['name'] = $minStat['data']['name'];
|
||
$inputData['fullname'] = $minStat['data']['name'];
|
||
}
|
||
|
||
return [
|
||
'status' => 'success',
|
||
'data' => array_merge($inputData, ['registerNewCompany' => true])
|
||
];
|
||
}
|
||
}
|
||
|
||
public function getCompanyByBiniin(string $biniin) {
|
||
return UniModel::model(config('platform.company.tables.company'))
|
||
->where('biniin', trim($biniin))
|
||
->first();
|
||
}
|
||
|
||
/**
|
||
* Store a new company.
|
||
*
|
||
* @param Request $request
|
||
* @return RedirectResponse
|
||
* @throws \Exception
|
||
*/
|
||
public function registerCompany(Request $request) {
|
||
if (!Auth::check()) {
|
||
return redirect(lurl("/"));
|
||
}
|
||
|
||
$userId = Auth::id();
|
||
$biniin = $this->getBiniin($request);
|
||
|
||
if ($company = $this->getCompanyByBiniin($biniin)) {
|
||
return $this->applyToCompany($company);
|
||
}
|
||
|
||
$minStat = $this->minStat($biniin);
|
||
|
||
[$name, $fullname] = $this->getNameAndFullName($request);
|
||
|
||
$company = $this->saveCompany([
|
||
'name' => $name,
|
||
'biniin' => $biniin,
|
||
'fullname' => $fullname
|
||
]);
|
||
|
||
$this->saveOrganization($minStat, $company);
|
||
|
||
Helper::company()->addUserToCompany($userId, $company->id);
|
||
Helper::company()->addUserRoleToCompany($userId, $company->id, self::COWORKER_ROLE);
|
||
Helper::company()->addUserRoleToCompany($userId, $company->id, self::DIRECTOR_ROLE);
|
||
|
||
$this->updateSession($company->id);
|
||
|
||
return redirect(lurl("/"));
|
||
}
|
||
|
||
public function minStat(string $biniin){
|
||
if (Cache::has($biniin)) {
|
||
return Cache::get($biniin);
|
||
}
|
||
|
||
$i = 0;
|
||
|
||
while($i < 3) {
|
||
try {
|
||
$i++;
|
||
$res = $this->getMinStatData($biniin);
|
||
if($res['status']){
|
||
Cache::put($biniin, $res, 10);
|
||
return $res;
|
||
}
|
||
sleep(10);
|
||
} catch (\Exception $e){
|
||
// ExceptionControl::message($e);
|
||
return ["status" => 0, "message" => "Данные не найдены"];
|
||
}
|
||
}
|
||
|
||
return ["status" => 0, "message" => "Данные не найдены"];
|
||
}
|
||
|
||
private function getMinStatData(string $biniin){
|
||
$curl = curl_init();
|
||
curl_setopt_array($curl, array(
|
||
CURLOPT_URL => 'https://stat.gov.kz/api/juridicalusr/counter/gov/?bin=' . $biniin . '&lang=ru',
|
||
CURLOPT_RETURNTRANSFER => true,
|
||
CURLOPT_MAXREDIRS => 10,
|
||
CURLOPT_CUSTOMREQUEST => 'GET',
|
||
CURLOPT_HTTPHEADER => array(
|
||
'Referer: https://stat.gov.kz/jur-search/bin'
|
||
),
|
||
));
|
||
|
||
$result = curl_exec($curl);
|
||
if (!curl_error($curl)) {
|
||
curl_close($curl);
|
||
$response = json_decode($result, 1);
|
||
if(!is_null($response)) {
|
||
if (array_key_exists("error", $response)) {
|
||
return ['status' => 0, 'message' => "Ошибка при запросе данных с stat gov kz"];
|
||
} else {
|
||
if ($response["success"] == true) {
|
||
return ['status' => 2, 'data' => $response['obj']];
|
||
} else {
|
||
if(is_null($response['obj'])){
|
||
return ["status" => 1, "message" => "Данные не найдены"];
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return ["status" => 0, "message" => "Сервер занят"];
|
||
} else {
|
||
return ["status" => 0, "message" => "Данные не найдены"];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* @throws \Exception
|
||
*/
|
||
private function saveCompany(array $data) {
|
||
$company = UniModel::model(config('platform.company.tables.company'));
|
||
|
||
$company->fill(array_merge($data, ['segment' => Segment::random()]));
|
||
|
||
$company->save();
|
||
return $company;
|
||
}
|
||
|
||
private function saveOrganization(array $minStat, $company) {
|
||
$data = $this->getOrganizationData($minStat, $company);
|
||
$organization = UniModel::model(config('platform.company.tables.organization'));
|
||
$organization->fill($data);
|
||
$organization->save();
|
||
}
|
||
|
||
private function getBiniin(Request $request) {
|
||
return $request->validate($this->getBiniinRules())['biniin'];
|
||
}
|
||
|
||
private function getNameAndFullName(Request $request) {
|
||
$data = $request->validate([
|
||
'name' => ['required', 'string', 'max:255'],
|
||
'fullname' => ['required', 'string', 'max:255'],
|
||
]);
|
||
|
||
return array($data['name'], $data['fullname']);
|
||
}
|
||
|
||
private function getOrganizationData(array $minStat, $company) {
|
||
|
||
if ($minStat['status'] == 2) {
|
||
$organizationData = $minStat['data'];
|
||
|
||
$organizationData['biniin'] = $organizationData['bin'];
|
||
unset($organizationData['bin']);
|
||
|
||
$organizationData['registerDate'] = Carbon::parse($organizationData['registerDate'])
|
||
->format('Y-m-d H:i:s');
|
||
|
||
unset($organizationData['id']);
|
||
}
|
||
else {
|
||
$organizationData = [
|
||
"name" => $company->name,
|
||
"biniin" => $company->biniin
|
||
];
|
||
}
|
||
$organizationData['company_id'] = $company->id;
|
||
|
||
return $organizationData;
|
||
}
|
||
|
||
public function showRegisterCompanyForm() {
|
||
return view('platform.auth::registerCompany');
|
||
}
|
||
|
||
public function applyToCompany($company) {
|
||
if ($this->issetApplication($company->id)) {
|
||
return back()
|
||
->withInput([
|
||
'name' => $company->name,
|
||
'biniin' => $company->biniin,
|
||
'fullname' => $company->name
|
||
])
|
||
->with('companyExists', true)
|
||
->withErrors(['company' => __('Your application already exists')]);
|
||
}
|
||
|
||
$addRequest = UniModel::model(config('platform.company.tables.company_request'));
|
||
|
||
$addRequest->fill([
|
||
'user_id' => Auth::id(),
|
||
'company_id' => $company->id,
|
||
]);
|
||
|
||
$addRequest->save();
|
||
|
||
$this->updateSession();
|
||
|
||
return redirect(lurl("/"));
|
||
}
|
||
|
||
private function issetApplication(int|string $companyId) {
|
||
return UniModel::model(config('platform.company.tables.company_request'))
|
||
->where('user_id', Auth::id())
|
||
->where('company_id', $companyId)
|
||
->count();
|
||
}
|
||
|
||
private function getBiniinRules(): array
|
||
{
|
||
return [
|
||
'biniin' => ['required', 'string', 'size:12', 'regex:/^[0-9]+$/']
|
||
];
|
||
}
|
||
|
||
private function updateSession(int $companyId = self::DEFAULT_COMPANY_ID): void
|
||
{
|
||
Session::put('user.company_id', $companyId);
|
||
Session::put('user.rights', Acl::getUserRights(Auth::id(), $companyId));
|
||
Session::put('user.segment', Acl::getSegment($companyId));
|
||
}
|
||
}
|