diff --git a/app/Http/Controllers/Deal/ContractController.php b/app/Http/Controllers/Deal/ContractController.php deleted file mode 100644 index 6e2f916..0000000 --- a/app/Http/Controllers/Deal/ContractController.php +++ /dev/null @@ -1,27 +0,0 @@ - $contract - ] - ); - - } - - public function getAllDealsInCompany(Request $request) - { - $user = auth()->user(); - } -} diff --git a/app/Livewire/ClientsTable.php b/app/Livewire/ClientsTable.php index df93ce3..250f3d4 100644 --- a/app/Livewire/ClientsTable.php +++ b/app/Livewire/ClientsTable.php @@ -7,11 +7,14 @@ use Livewire\WithoutUrlPagination; use App\Models\User; +use Modules\Main\Models\Deal\Client; use Modules\Main\Models\Agent\Agent; use Modules\Main\Models\Company\CompanyAdmin; -use App\Models\Deal\Deal; -use App\Models\Deal\DealStatus; -use App\Models\Deal\Client; +use Modules\Main\Models\Deal\Deal; +use Modules\Main\Models\Deal\DealStatus; + +use Livewire\Attributes\On; + class ClientsTable extends Component { use WithPagination, WithoutUrlPagination; @@ -27,52 +30,48 @@ public function mount($status = null, $count = 10, $mode = 'full') $this->mode = $mode; } + #[On('clientCreated')] public function getDeals() { $deals = false; - $user = auth()->user(); - $clients = false; + $user = auth()->user(); if ($admin = CompanyAdmin::where('user_id', $user->id)->first()) { - /*$deals = Deal::whereIn('agent_id', function ($query) use ($admin) + $deals = Deal::whereIn('agent_id', function ($query) use ($admin) { $query->select('id'); $query->from('agents'); $query->where('company_id', $admin->company_id); - });*/ - $agentsOfCompany = Agent::where('company_id', $admin->company_id)->get()->pluck('id'); - $clients = Client::whereIn('id', function ($query) use ($agentsOfCompany) - { - $query->select('client_id') - ->from('deals') - ->whereIn('agent_id', $agentsOfCompany); }); } elseif ($agent = Agent::where('user_id', $user->id)->first()) { - //$deals = Deal::where('agent_id', $agent->id); + $deals = Deal::where('agent_id', $agent->id); + } - $clients = Client::whereIn('id', function ($query) use ($agent) + $deals = $deals->pluck('id'); + $clients = Client::join('deal_clients', 'users.id', '=', 'deal_clients.client_id') + ->whereIn('users.id', function ($query) use ($deals) { $query->select('client_id') - ->from('deals') - ->where('agent_id', $agent->id); + ->from('deal_clients') + ->whereIn('deal_id', $deals); + }) + ->orderBy('deal_clients.id', 'desc') + ->with('deals'); + ; - }); - } $clients = $clients->orderBy('name'); return $clients; } - public function render() + + function getClients() { $clients = $this->getDeals(); if ($this->status && $this->status == DealStatus::UNIQUE) { - /*$deals = $deals - ->whereIn('status', [DealStatus::UNIQUE]) - ->orderBy('id', 'desc')->paginate($this->count, ['*'], 'unique_clients');*/ $clients = $clients->whereHas('deals', function ($query) { $query->where('status', DealStatus::UNIQUE); @@ -82,9 +81,6 @@ public function render() } elseif ($this->status && $this->status == DealStatus::NOT_UNIQUE) { - /*$deals = $deals - ->whereIn('status', [DealStatus::MODERATION, DealStatus::NEW , DealStatus::NOT_UNIQUE]) - ->orderBy('id', 'desc')->paginate($this->count, ['*'], 'not_unique_clients');*/ $clients = $clients->whereHas('deals', function ($query) { $query->whereIn('status', [DealStatus::MODERATION, DealStatus::NEW , DealStatus::NOT_UNIQUE]); @@ -95,22 +91,18 @@ public function render() /*$deals = $deals->orderBy('id', 'desc')->paginate($this->count, ['*'], 'all_clients');*/ $clients = $clients->paginate($this->count, ['*'], 'all_clients'); } + return $clients; + } + public function render() + { + return view( 'livewire.clients-table', [ - 'clients' => $clients, + 'clients' => $this->getClients(), 'statuses' => DealStatus::class ] ); } - function getClients() - { - /*$clients = User::whereIn('id', function ($query) - { - });*/ - $clients = false; - //$clients = Client::ofAgent(); - return $clients; - } } diff --git a/app/Livewire/CreateClientForm.php b/app/Livewire/CreateClientForm.php deleted file mode 100644 index 50b0105..0000000 --- a/app/Livewire/CreateClientForm.php +++ /dev/null @@ -1,198 +0,0 @@ - 'Необходимо указать имя клиента', - 'client.secondName.required' => 'Необходимо указать фамилию клиента', - 'client.phone.required' => 'Необходимо указать телефон', - 'client.phone.regex' => 'Телефон должен быть в международном формате', - 'client.phone.unique' => 'Клиент с таким телефоном уже существует', - 'agent.integer' => 'Необходимо указать агента, от которого добавляется контакт' - ]; - protected function rules() - { - return [ - 'agent' => ['required', 'integer'], - 'client.firstName' => ['required', 'string', 'max:255'], - 'client.secondName' => ['required', 'string', 'max:255'], - 'client.phone' => ['required', 'string', 'regex:/^(\+7)([0-9]{3})([-]{1})([0-9]{3})([-]{1})([0-9]{4})/i'] - //'client.phone' => ['required', 'string', 'regex:/^\+7 \d{3} \d{3}-\d{2}-\d{2}$/'], - //'client.phone' => ['required', 'string'] - ]; - } - public function mount() - { - $agent = Agent::where('user_id', auth()->user()->id)->first(); - $this->client = [ - 'firstName' => '', - 'secondName' => '', - 'phone' => '', - 'complexId' => '' - ]; - $this->status = self::NEW; - - if ($agent) - { - $this->agent = $agent->id; - $this->complexes = Complex::where('city_id', $agent->company->city_id)->get(); - - } - else - { - $this->agent = false; - $admin = CompanyAdmin::where('user_id', auth()->user()->id)->first(); - if ($admin) - { - $this->complexes = Complex::where('city_id', $admin->company_id)->get(); - } - } - $this->clientSecondary = false; - } - public function update() - { - } - - public function updated($propertyName) - { - $this->status = self::NEW; - $this->validateOnly($propertyName); - } - public function getClientSecondary() - { - $this->clientSecondary = [ - 'firstName' => '', - 'secondName' => '', - 'phone' => '', - 'complexId' => '' - ]; - } - public function deleteClientSecondary() - { - $this->clientSecondary = false; - } - public function render() - { - if ( - $this->client['firstName'] - && $this->client['secondName'] - && $this->client['phone'] - && $this->client['complexId'] - && $this->status == self::NEW - ) - { - $this->status = self::READY; - } - $data = [ - 'adminAccount' => false - ]; - if ($adminAccount = CompanyAdmin::where('user_id', auth()->user()->id)->first()) - { - $data = [ - 'adminAccount' => $adminAccount, - 'agents' => Agent::where('company_id', $adminAccount->company_id)->get() - ]; - } - return view( - 'livewire.create-client-form', - $data - ); - } - public function resetData() - { - $this->mount(); - } - public function back() - { - $this->status = self::NEW; - } - public function save() - { - $validated = $this->validate($this->rules()); - $newUser = User::updateOrCreate( - ['phone' => $this->client['phone']], - [ - 'name' => trim($this->client['firstName'] . ' ' . $this->client['secondName']), - 'phone' => $this->client['phone'] - ] - ); - $data = [ - 'agent_id' => $this->agent - , - 'client_id' => $newUser->id - , - 'complex_id' => $this->client['complexId'] - ]; - //$data['confirm_token'] = $this->client['confirmToken'] = hash('sha256', json_encode($data)); - - if ($newDeal = Deal::create($data)) - { - if ($bitrixId = $this->sendToBitrix($newDeal)) - { - $newDeal->bitrix_id = $bitrixId; - $newDeal->status = DealStatus::MODERATION; - $newDeal->save(); - $this->result = $bitrixId; - return $this->status = self::SUCCESS; - } - else - { - $newDeal->delete(); - } - } - return $this->status = self::ERROR; - } - public function sendToBitrix(Deal $deal) - { - $agent = $deal->agent; - $agentName = $agent->user->getPartialsName(); - $data = [ - 'CLIENT_FIRST_NAME' => $this->client['firstName'], - 'CLIENT_SECOND_NAME' => $this->client['secondName'], - 'CLIENT_PHONE' => '+7' . $this->client['phone'], - 'BROKER_FIRST_NAME' => $agentName['firstName'], - 'BROKER_SECOND_NAME' => $agentName['secondName'], - 'BROKER_PHONE' => $agent->user->phone, - 'BROKER_INN' => $agent->company->inn, - //'BROKER_CONTACT' => $agent->bitrixId(), - 'OBJECT_NAME' => Complex::find($this->client['complexId'])->name, - 'CALLBACK_URL' => route('api.client', ['hash' => $deal->confirmToken]), - ]; - $sender = new SendClient($deal->id, $data); - if ($bitrixId = $agent->bitrixId()) - { - $sender->setAgentId($bitrixId); - } - $response = $sender->send(); - if ($response) - { - return $response; - } - else - { - return false; - } - } -} \ No newline at end of file diff --git a/app/Models/Bitrix/SendClient.php b/app/Models/Bitrix/SendClient.php deleted file mode 100644 index 445ee98..0000000 --- a/app/Models/Bitrix/SendClient.php +++ /dev/null @@ -1,72 +0,0 @@ -ID = env('BITRIX_CODE_PREFIX', '') . $id; - $data = array_change_key_case($data, CASE_UPPER); - $finalData = []; - $refl = new \ReflectionClass(__CLASS__); - $constants = $refl->getConstants(); - foreach ($constants as $constName => $constValue) - { - foreach ($data as $key => $value) - { - if ($constName == $key) - { - $finalData[$constValue] = $value; - break; - } - } - } - $finalData['NAME'] = $finalData[self::CLIENT_FIRST_NAME] . ' ' . $finalData[self::CLIENT_SECOND_NAME]; - $this->data = $finalData; - return; - } - public function setBitrixId($id) - { - $this->data['PROPERTY_123'] = $id; - } - - public function setAgentId($id) - { - $this->data['PROPERTY_108'] = $id; - } - - public function send() - { - $data = [ - 'IBLOCK_TYPE_ID' => $this->IBLOCK_TYPE_ID, - 'IBLOCK_ID' => $this->IBLOCK_ID, - 'ELEMENT_CODE' => $this->ID, - 'FIELDS' => $this->data - ]; - $sender = new BitrixSender($this->URL, $data); - return $sender->send(); - } -} \ No newline at end of file diff --git a/app/Models/Bitrix/SendCompany.php b/app/Models/Bitrix/SendCompany.php deleted file mode 100644 index 7ceefd7..0000000 --- a/app/Models/Bitrix/SendCompany.php +++ /dev/null @@ -1,64 +0,0 @@ -ID = env('BITRIX_CODE_PREFIX', '') . $id; - $data = array_change_key_case($data, CASE_UPPER); - $finalData = $this->castConstants($data); - $this->data = $finalData; - return; - } - - private function castConstants($data) - { - $finalData = []; - $refl = new \ReflectionClass(__CLASS__); - $constants = $refl->getConstants(); - foreach ($constants as $constName => $constValue) - { - foreach ($data as $key => $value) - { - if ($constName == $key) - { - $finalData[$constValue] = $value; - break; - } - } - } - return $finalData; - } - public function send() - { - $data = [ - 'IBLOCK_TYPE_ID' => $this->IBLOCK_TYPE_ID, - 'IBLOCK_ID' => $this->IBLOCK_ID, - 'ELEMENT_CODE' => $this->ID, - 'FIELDS' => $this->data - ]; - $sender = new BitrixSender($this->URL, $data); - return $sender->send(); - } - } diff --git a/app/Modules/Bitrix/Database/Migrations/2025_11_08_456725_copy_client_field_from_deals_table.php b/app/Modules/Bitrix/Database/Migrations/2025_11_08_456725_copy_client_field_from_deals_table.php new file mode 100644 index 0000000..9e5f2c3 --- /dev/null +++ b/app/Modules/Bitrix/Database/Migrations/2025_11_08_456725_copy_client_field_from_deals_table.php @@ -0,0 +1,32 @@ +whereNotNull('client_id')->orderBy('id')->chunk(1000, function ($rows) + { + foreach ($rows as $row) + { + \DB::table('deal_clients')->updateOrInsert(['deal_id' => $row->id, 'client_id' => $row->client_id]); + // Or if you're creating new records in the new table based on the old, use insert: + // \DB::table('new_table_name')->insert(['id' => $row->id, 'field_name' => $row->field_name]); + } + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + + } +}; diff --git a/app/Modules/Bitrix/Database/Migrations/2025_11_08_456729_delete_client_field_from_deals_table.php b/app/Modules/Bitrix/Database/Migrations/2025_11_08_456729_delete_client_field_from_deals_table.php new file mode 100644 index 0000000..41a57c3 --- /dev/null +++ b/app/Modules/Bitrix/Database/Migrations/2025_11_08_456729_delete_client_field_from_deals_table.php @@ -0,0 +1,28 @@ +dropForeign(['client_id']); + $table->dropColumn(['client_id']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + + } +}; diff --git a/app/Modules/Bitrix/Models/BitrixId.php b/app/Modules/Bitrix/Models/BitrixId.php index 7e964a2..3bc15c0 100644 --- a/app/Modules/Bitrix/Models/BitrixId.php +++ b/app/Modules/Bitrix/Models/BitrixId.php @@ -7,6 +7,12 @@ use Illuminate\Database\Eloquent\Relations\MorphTo; use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Modules\Main\Models\Deal\Deal; +use Modules\Main\Models\Deal\Client; +use Modules\Main\Models\Deal\DealClients; +use Modules\Main\Models\Agent\Agent; +use Modules\Main\Models\Company\Company; +use Modules\Main\Models\Complex; class BitrixId extends Model { @@ -20,4 +26,91 @@ public function bitrixable(): MorphTo { return $this->morphTo(); } + + protected static function booted() + { + static::creating(function (BitrixId $bitrixId) + { + if ($bitrixId->bx_id) + { + return; + } + switch ( $bitrixId->bitrixable_type ) + { + case Deal::class: + $deal = Deal::findOrFail($bitrixId->bitrixable_id); + $sender = new SendDeal($deal); + $result = $sender->send(); + if ($result == true) + { + $id = $sender->resultData['id']; + $bitrixId->bx_id = $id; + return; + } + break; + case Agent::class: + $agent = Agent::findOrFail($bitrixId->bitrixable_id); + $sender = new SendAgent($agent); + $result = $sender->send(); + if ($result == true) + { + $id = $sender->resultData['id']; + $bitrixId->bx_id = $id; + return; + }; + break; + case DealClients::class: + $dealClient = DealClients::findOrFail($bitrixId->bitrixable_id); + $client = $dealClient->client; + $sender = new SendClient($client); + $result = $sender->send(); + if ($result) + { + $id = $sender->resultData['id']; + $bitrixId->bx_id = $id; + $bitrixId->bitrixable_type = Client::class; + $bitrixId->bitrixable_id = $client->id; + return; + }; + break; + case Company::class: + $company = Company::findOrFail($bitrixId->bitrixable_id); + $sender = new SendCompany($company); + $result = $sender->send(); + if ($result == true) + { + $id = $sender->resultData['id']; + $bitrixId->bx_id = $id; + return; + }; + break; + } + throw new \Exception('Error of bitrix identifier getter for ' . $bitrixId->bitrixable_type . ' with id ' . $bitrixId->bitrixable_id); + + }); + static::created(function (BitrixId $bitrixId) + { + if (!$bitrixId->bx_id) + { + return; + } + switch ( $bitrixId->bitrixable_type ) + { + case Deal::class: + $deal = Deal::findOrFail($bitrixId->bitrixable_id); + $agentAppender = new SendDealAgent($deal); + $agentAppender->send(); + break; + case Client::class: + $client = Client::findOrFail($bitrixId->bitrixable_id); + if ($dealClient = DealClients::where('client_id', $client->id)->orderByDesc('id')->first()) + { + $clientAppender = new SendDealClient(Deal::find($dealClient->deal_id), $client); + $result = $clientAppender->send(); + } + break; + } + + }); + } } diff --git a/app/Models/Bitrix/BitrixSender.php b/app/Modules/Bitrix/Models/BitrixSender.php similarity index 77% rename from app/Models/Bitrix/BitrixSender.php rename to app/Modules/Bitrix/Models/BitrixSender.php index 4f6617b..96cb3ba 100644 --- a/app/Models/Bitrix/BitrixSender.php +++ b/app/Modules/Bitrix/Models/BitrixSender.php @@ -1,58 +1,60 @@ url = $url; $this->data = $data; - } + } public function send() - { + { $postdata = http_build_query( $this->data ); $opts = array( - 'ssl' => array( - 'verify_peer' => true, + 'ssl' => array( + 'verify_peer' => true, 'verify_peername' => true ), 'http' => array( - 'method' => 'POST', - 'header' => + 'method' => 'POST', + 'header' => 'Content-type: application/x-www-form-urlencoded' . "\r\n" . '', 'content' => $postdata ) ); try - { + { $context = stream_context_create($opts); $result = file_get_contents($this->url, false, $context); $result = json_decode($result, $associative = true); + $this->resultData = $result; if (array_key_exists('result', $result)) - { - return $result['result']; - } - else - { - return false; - } - } - catch (\Exception $e) { - Log::build([ - 'driver' => 'single', - 'path' => storage_path('logs/bitrix.log'), - ])->error($e->getMessage()); - return false; + return $result['result']; + } + else + { + return false; } } + catch (\Exception $e) + { + Log::build([ + 'driver' => 'single', + 'path' => storage_path('logs/bitrix.log'), + ])->error($e->getMessage()); + return false; + } } +} diff --git a/app/Modules/Bitrix/Models/SendAgent.php b/app/Modules/Bitrix/Models/SendAgent.php new file mode 100644 index 0000000..72b4500 --- /dev/null +++ b/app/Modules/Bitrix/Models/SendAgent.php @@ -0,0 +1,22 @@ +data = [ + 'name' => $agent->user->name, + 'phones' => [$agent->user->phone], + ]; + dd($this->data); + $this->url = 'https://b24alfa.pro/channels/lk/createContact/'; + } +} diff --git a/app/Modules/Bitrix/Models/SendClient.php b/app/Modules/Bitrix/Models/SendClient.php new file mode 100644 index 0000000..d753813 --- /dev/null +++ b/app/Modules/Bitrix/Models/SendClient.php @@ -0,0 +1,21 @@ +data = [ + 'name' => $client->name, + 'phones' => [$client->phone], + ]; + $this->url = 'https://b24alfa.pro/channels/lk/createContact/'; + } +} diff --git a/app/Modules/Bitrix/Models/SendCompany.php b/app/Modules/Bitrix/Models/SendCompany.php new file mode 100644 index 0000000..f1b5978 --- /dev/null +++ b/app/Modules/Bitrix/Models/SendCompany.php @@ -0,0 +1,21 @@ +data = [ + 'name' => $agent->user->name, + 'phones' => [$agent->user->phone], + ]; + $this->url = 'https://b24alfa.pro/channels/lk/createCompany/'; + } +} diff --git a/app/Modules/Bitrix/Models/SendDeal.php b/app/Modules/Bitrix/Models/SendDeal.php new file mode 100644 index 0000000..36683c0 --- /dev/null +++ b/app/Modules/Bitrix/Models/SendDeal.php @@ -0,0 +1,20 @@ +data = [ + 'complexName' => $deal->complex->name + ]; + $this->url = 'https://b24alfa.pro/channels/lk/createSmartProcess/'; + } +} diff --git a/app/Modules/Bitrix/Models/SendDealAgent.php b/app/Modules/Bitrix/Models/SendDealAgent.php new file mode 100644 index 0000000..caac447 --- /dev/null +++ b/app/Modules/Bitrix/Models/SendDealAgent.php @@ -0,0 +1,22 @@ +data = [ + 'spId' => $deal->bitrixId(), + 'contactId' => $deal->agent->bitrixId(), + 'type' => 'agent' + ]; + $this->url = 'https://b24alfa.pro/channels/lk/addContactToSmartProcess/'; + } +} diff --git a/app/Modules/Bitrix/Models/SendDealClient.php b/app/Modules/Bitrix/Models/SendDealClient.php new file mode 100644 index 0000000..68e6344 --- /dev/null +++ b/app/Modules/Bitrix/Models/SendDealClient.php @@ -0,0 +1,23 @@ +data = [ + 'spId' => $deal->bitrixId(), + 'contactId' => $client->bitrixId(), + 'type' => 'contact' + ]; + $this->url = 'https://b24alfa.pro/channels/lk/addContactToSmartProcess/'; + } +} diff --git a/app/Modules/Bitrix/Traits/Bitrixable.php b/app/Modules/Bitrix/Traits/Bitrixable.php index 1ca382f..6ee0a79 100644 --- a/app/Modules/Bitrix/Traits/Bitrixable.php +++ b/app/Modules/Bitrix/Traits/Bitrixable.php @@ -26,17 +26,48 @@ public function bitrixId() } return false; } - public function setBitrixId($id): bool + public function setBitrixId($id = null) { - $this->bitrixy()->delete(); - $bitrixId = new BitrixId([ - 'bx_id' => $id - ]); - if ($this->bitrixy()->save($bitrixId)) + $bitrixy = $this->bitrixy; + if (!$bitrixy) { - return true; + $bitrixId = new BitrixId(); + $bitrixId->bx_id = $id ?? null; + $this->bitrixy()->save($bitrixId); } - return false; + if ($id) + { + $bitrixy = $this->bitrixy; + $bitrixy->bx_id = $id; + $bitrixy->save(); + } + return true; + } + protected static function create(array $attributes = []) + { + $model = new static(); + $model->fill($attributes); + $model->save(); + $model->setBitrixId(); + return $model; + } + + public static function firstOrCreate($attributes = [], $values = []) + { + $model = new static(); + foreach ($attributes as $key => $value) + { + $model = $model->where($key, $value); + } + if ($model->count()) + { + return $model->first(); + } + else + { + self::create(array_merge($attributes, $values)); + } + return true; } } diff --git a/app/Modules/ClientCreateForm/Http/Livewire/ClientCreateLivewire.php b/app/Modules/ClientCreateForm/Http/Livewire/ClientCreateLivewire.php index dadfe6e..ec641b0 100644 --- a/app/Modules/ClientCreateForm/Http/Livewire/ClientCreateLivewire.php +++ b/app/Modules/ClientCreateForm/Http/Livewire/ClientCreateLivewire.php @@ -2,116 +2,165 @@ namespace Modules\ClientCreateForm\Http\Livewire; +use Exception; +use Laravel\Prompts\FormStep; use Livewire\Component; +use Livewire\Attributes\Validate; +use Modules\Main\Models\Deal\Deal; +use Modules\Main\Models\Deal\Client; +use Modules\Main\Models\Deal\DealClients; class ClientCreateLivewire extends Component { - //public ClientCreateForm $form; + public $status; public $availableAgents; public $complexes; - public $maxClientsCount; - public $maxClientPhonesCount; + public $maxContactsCount; + public $maxContactPhonesCount; ///////////////////// - public $agent; - public $clients; - public $currentClientIndex; - public $currentClient; - public $addSecondaryClient; - public $secondaryClient; - public $clientLabels; + public $agentId; + public $contacts; + public $complexId; + public $currentContactIndex; + public $contactLabels; public $bitrixId; + + protected function rules() + { + return [ + 'contacts.*' => ['required', 'min:1'], + 'contacts.*.firstName' => ['required', 'string', 'max:50'], + 'contacts.*.secondName' => ['required', 'string', 'max:50'], + 'contacts.*.phones.*' => 'required|string|regex:/^(\+7)([(]{1})([0-9]{3})([)]{1})([\s]{1})([0-9]{3})([-]{1})([0-9]{2})([-]{1})([0-9]{2})/', + 'complexId' => ['required'], + 'agentId' => ['required'], + ]; + } + protected function messages() + { + return [ + 'contacts.*.firstName.reqired' => 'Необходимо указать имя (отчество) клиента', + 'contacts.*.secondName.reqired' => 'Необходимо указать фамилию клиента', + 'contacts.*.firstName.max' => 'Указанное имя клиента слишком длинное', + 'contacts.*.secondName.max' => 'Указанное имя клиента слишком длинное', + 'contacts.*.phones.*.reqired' => 'Необходимо указать номер телефона клиента', + 'contacts.*.phones.*.regex' => 'Указанный номер телефона некорректный', + + ]; + } public function mount() { + $this->status = FormStatus::NEW; $this->complexes = GetAvailableComplexes(); $this->availableAgents = GetAvailableAgents(); - $this->maxClientsCount = 2; - $this->maxClientPhonesCount = 2; - $this->clientLabels = ['Основной контакт', 'Супруг/супруга']; - - $this->status = FormStatus::NEW; - $this->secondaryClient = false; - $this->addSecondaryClient = true; + $this->maxContactsCount = 2; + $this->maxContactPhonesCount = 1; + $this->contactLabels = ['Основной контакт', 'Супруг/супруга']; if (count($this->availableAgents) == 1) //чтобы не выводить в форму { //и не заставлять пользователя указывать вручную - $this->agent = $this->availableAgents[0]['id']; + $this->agentId = $this->availableAgents[0]['id']; } - $this->addClient(); - $this->addClient();//по-умолчанию сразу выводить супруга - $this->setCurrentClient(0); + $this->contacts = []; + $this->addContact(); + $this->addContact();//по-умолчанию сразу выводить супруга + $this->setCurrentContactIndex(0); } - public function updated($propertyName) + + /** + * Метод срабатывает, когда пользователь нажимает в форме + * на кнопку "Добавить супруга" + * @return void + */ + public function addContact() { - $this->status = FormStatus::NEW; - } - public function addClient() - { - if (!isset($this->clients)) + if (!isset($this->contacts)) { - $this->clients = []; + $this->contacts = []; } - if ($this->maxClientsCount > count($this->clients)) + if ($this->maxContactsCount > count($this->contacts)) { - $this->clients[] = [ + $this->contacts[] = [ 'firstName' => '', 'secondName' => '', - 'phones' => [''], - 'complexId' => '' + 'phones' => [''] ]; } - $this->setCurrentClient(count($this->clients) - 1); + $this->setCurrentContactIndex(count($this->contacts) - 1); } + /** + * Метод срабатывает, когда пользователь нажимает кнопку "Удалить контакт" + * Кнопка доступна на всех вкладках, кроме первой + * @param mixed $index Индекс контакта по порядку следования на вкладках + * @return void + */ public function deleteContact($index = false) { if ($index === false) { - $index = $this->currentClientIndex; + $index = $this->currentContactIndex; } if ($index > 0) { - unset($this->clients[$index]); - $this->clients = array_values($this->clients); - $this->setCurrentClient($index - 1); + unset($this->contacts[$index]); + $this->contacts = array_values($this->contacts); + $this->setCurrentContactIndex($index - 1); } } - public function setCurrentClient($index) + /** + * Вызвается при переходе пользователя по вкладкам + * @param mixed $index + * @return void + */ + public function setCurrentContactIndex($index) { - $this->saveClient(); - $this->updateCurrentClientIndex($index); + $this->currentContactIndex = $index; + $this->updated('currentContactIndex'); } - public function toggleSecondClient() + /** + * Вызывается, когда пользователь нажимает на кнопку + * "Добавить супруга" на первой вкладке + * @return void + */ + public function toggleSecondContact() { - if ($this->currentClientIndex == 0) + if ($this->currentContactIndex == 0) { - if (count($this->clients) == 2) + if (count($this->contacts) == 2) { $this->deleteContact(1); } - elseif (count($this->clients) == 1) + elseif (count($this->contacts) == 1) { - $this->addClient(); + $this->addContact(); } } } - private function updateCurrentClientIndex($index) + /** + * Вызывается, когда пользователь нажимает на кнопку "добавить телефон" + * на вкладке любого из контактов + * @return void + */ + public function addPhoneForCurrentContact() { - $this->currentClient = $this->clients[$index]; - $this->currentClientIndex = $index; - } - public function saveClient() - { - if (isset($this->currentClientIndex)) + if (count($this->contacts[$this->currentContactIndex]['phones']) < $this->maxContactPhonesCount) { - //$this->form->validate(); - $this->clients[$this->currentClientIndex] = $this->currentClient; + $this->contacts[$this->currentContactIndex]['phones'][] = ''; } } - public function addPhoneForClient() + public function updated($propertyName) { - if (count($this->currentClient['phones']) < $this->maxClientPhonesCount) + $this->status = FormStatus::IN_PROCESS; + $this->validateOnly($propertyName); + try { - $this->currentClient['phones'][] = ''; + $this->validate(); + $this->status = FormStatus::READY; + } + catch (\Exception $e) + { + $this->status = FormStatus::IN_PROCESS; } } public function render() @@ -123,6 +172,7 @@ public function render() public function rendered() { $this->dispatch('phoneInputAdded'); + } public function resetData() { @@ -130,75 +180,50 @@ public function resetData() } public function back() { - $this->status = FormStatus::NEW; + $this->status = FormStatus::IN_PROCESS; } - //далее - сохранение клиента в базу и отправка в битрикс. - //надо разделить на invoke классы! - /*public function save() + public function save() { - $validated = $this->form->validate(); - $newUser = User::updateOrCreate( - ['phone' => $this->client['phone']], - [ - 'name' => trim($this->client['firstName'] . ' ' . $this->client['secondName']), - 'phone' => $this->client['phone'] - ] - ); - $data = [ - 'agent_id' => $this->agent - , - 'client_id' => $newUser->id - , - 'complex_id' => $this->client['complexId'] - ]; + if ( + !$deal = Deal::create([ + 'agent_id' => $this->agentId, + 'complex_id' => $this->complexId + ]) + ) + { + $this->status = FormStatus::ERROR; + return; + } - if ($newDeal = Deal::create($data)) + foreach ($this->contacts as $contact) { - if ($bitrixId = $this->sendToBitrix($newDeal)) + if ( + !$newUser = Client::updateOrCreate( + ['phone' => $contact['phones'][0]], + [ + 'name' => trim($contact['firstName'] . ' ' . $contact['secondName']), + 'phone' => $contact['phones'][0] + ] + ) + ) { - $newDeal->bitrix_id = $bitrixId; - $newDeal->status = DealStatus::MODERATION; - $newDeal->save(); - $this->bitrixId = $bitrixId; - return $this->status = FormStatus::SUCCESS; + $this->status = FormStatus::ERROR; + return; } - else + if ( + !$dealClient = DealClients::firstOrCreate([ + 'deal_id' => $deal->id, + 'client_id' => $newUser->id + ]) + ) { - $newDeal->delete(); + $this->status = FormStatus::ERROR; + return; } } - return $this->status = FormStatus::ERROR; + $this->status = FormStatus::SUCCESS; + $this->dispatch('clientCreated'); + } - public function sendToBitrix(Deal $deal) - { - $agent = $deal->agent; - $agentName = $agent->user->getPartialsName(); - $data = [ - 'CLIENT_FIRST_NAME' => $this->client['firstName'], - 'CLIENT_SECOND_NAME' => $this->client['secondName'], - 'CLIENT_PHONE' => '+7' . $this->client['phone'], - 'BROKER_FIRST_NAME' => $agentName['firstName'], - 'BROKER_SECOND_NAME' => $agentName['secondName'], - 'BROKER_PHONE' => $agent->user->phone, - 'BROKER_INN' => $agent->company->inn, - //'BROKER_CONTACT' => $agent->bitrixId(), - 'OBJECT_NAME' => Complex::find($this->client['complexId'])->name, - 'CALLBACK_URL' => route('api.client', ['hash' => $deal->confirmToken]), - ]; - $sender = new SendClient($deal->id, $data); - if ($bitrixId = $agent->bitrixId()) - { - $sender->setAgentId($bitrixId); - } - $response = $sender->send(); - if ($response) - { - return $response; - } - else - { - return false; - } - }*/ } \ No newline at end of file diff --git a/app/Modules/ClientCreateForm/Views/livewire/form.blade.php b/app/Modules/ClientCreateForm/Views/livewire/form.blade.php index a089120..4d06092 100644 --- a/app/Modules/ClientCreateForm/Views/livewire/form.blade.php +++ b/app/Modules/ClientCreateForm/Views/livewire/form.blade.php @@ -8,27 +8,27 @@