/** * @param EmployesImportItem $item * @param AbstractItemImportResult $item_result * * @return AbstractItemImportResult * * @todo Когда в отчётах появится указание на принадлежность к компании, * не забыть про то, что компания забита в коде. */ protected function _processImportItem($item, &$item_result) { $employe = $this->findEmployes($item); if (empty($employe)) { $employe = new Entity\Employe(); } elseif ($this->getConfig('update_existing')) { if (count($employe) > 1) { return $item_result->addMessage('More than one employe was found with the given data'); } else { $employe = array_pop($employe); } } else { return $item_result->addMessage('An employe with given external_id already exists'); } $taxi_company = $this->_em->getRepository('TaxiPrizeTaxiBundle:TaxiCompany')->findBy(array('name' => 'Taxi Prize')); if (empty($taxi_company)) { return $item_result->addMessage('Can not find taxi company'); } elseif (count($taxi_company) > 1) { return $item_result->addMessage('More than one taxi company found'); } else { $taxi_company = array_pop($taxi_company); } // Обработка ролей $_roles_str = trim($item->roles); if (!empty($_roles_str)) { $roles = array(); $str_roles = array_map('trim', explode(' ', $_roles_str)); $notfound_str_roles = array(); /** @var ORM\EntityRepository */ $rep = $this->_em->getRepository('TaxiPrizeTaxiBundle:EmployeRole'); foreach ($str_roles as $str_role) { $res = $rep->findOneBy(array('name' => $str_role)); if (empty($res)) { $notfound_str_roles[] = $str_role; } else { $roles[] = $res; } } if (!empty($notfound_str_roles)) { if ($this->getConfig('create_notfound_role')) { foreach ($notfound_str_roles as $str_role) { $role = new Entity\EmployeRole(); $role->setName($str_role); $this->_em->persist($role); $roles[] = $role; } } else { return $item_result->addMessage('Following roles are not found: ' . implode(', ', $notfound_str_roles)); } } $employe->setRoles($roles); } // Остальные данные $employe->setExternalId($item->external_id)->setTaxiCompany($taxi_company)->setSecondName($item->second_name)->setFirstName($item->first_name)->setCallsign($item->callsign)->setWorkPhones(array_map('trim', explode(' ', $item->phones)))->setBalance(round(floatval($item->balance), 2))->setLastLocationChange($this->getRelocationDateTime($item)); $this->_em->persist($employe); $this->_em->flush(); return $item_result->setSuccessful(); }
/** * @param AbstractItemImportResult $import_item_result * * @return $this */ public function addItemImportResult(AbstractItemImportResult $import_item_result) { $this->_item_import_results[] = $import_item_result; if ($import_item_result->isSuccessful()) { $this->_import_item_successful_results[] = $import_item_result; } else { $this->_import_item_failed_results[] = $import_item_result; } return $this; }
/** * @param OrdersImportItem $item * @param AbstractItemImportResult $item_result * * @return AbstractItemImportResult */ protected function _processImportItem($item, &$item_result) { $order = $this->findOrders($item); if (empty($order)) { $order = new Entity\Order(); } else { return $item_result->addMessage('An order with given external_id already exists'); } // Process client $is_client_corporate = false; $phones = array_map('\\TaxiPrize\\TaxiBundle\\Entity\\Client::compressPhone', explode(';', $item->client_phone)); if (!empty($phones)) { $client = $this->findClients($item); if (empty($client)) { if ($this->getConfig('create_notfound_client')) { $client = $this->createNewClient($item); // $item_result->addMessage('A new client created from provided data'); } else { return $item_result->addMessage('The client is not found'); } } elseif (count($client) > 1) { return $item_result->addMessage('More than one client found by the phone given'); } else { $client = array_pop($client); } if (isset($client)) { $order->setClient($client->incrementOrdersQnt()); $is_client_corporate = $client->isCorporate(); } } elseif (!$this->getConfig('import_without_client')) { return $item_result->addMessage('The client phone info is empty'); } // Process owner $owner_taxi_name = trim($item->owner); if (!empty($owner_taxi_name)) { $order->setOwnerTaxiCompanyStr($owner_taxi_name); $owner_taxi = $this->findOwnerTaxis($item); if (empty($owner_taxi)) { unset($owner_taxi); /*if ($this->getConfig('create_notfound_owner_taxi')) { $owner_taxi = new Entity\TaxiCompany(); $owner_taxi ->setName($owner_taxi_name) ; // $item_result->addMessage('A new taxi-owner created from provided data'); } else*/ // return $item_result->addMessage('The owner taxi company is not found'); } elseif (count($owner_taxi) > 1) { return $item_result->addMessage('More than one taxi company found by the owner name given'); } else { $owner_taxi = array_pop($owner_taxi); } if (isset($owner_taxi)) { $order->setOwnerTaxiCompany($owner_taxi); } } elseif (!$this->getConfig('import_without_owner_taxi')) { return $item_result->addMessage('The owner taxi company info is empty'); } // Process executor $executor_taxi_name = trim($item->executor); if (!empty($executor_taxi_name)) { $order->setExecutorTaxiCompanyStr($executor_taxi_name); if (isset($owner_taxi) && $executor_taxi_name == $owner_taxi_name) { $executor_taxi = $owner_taxi; } else { $executor_taxi = $this->findExecutorTaxis($item); if (empty($executor_taxi)) { unset($executor_taxi); /*if ($this->getConfig('create_notfound_executor_taxi')) { $executor_taxi = new Entity\TaxiCompany(); $executor_taxi ->setName($executor_taxi_name) ; // $item_result->addMessage('A new taxi-executor created from provided data'); } else*/ // return $item_result->addMessage('The executor taxi company is not found'); } elseif (count($executor_taxi) > 1) { return $item_result->addMessage('More than one taxi company found by the executor name given'); } else { $executor_taxi = array_pop($executor_taxi); } } if (isset($executor_taxi)) { $order->setExecutorTaxiCompany($executor_taxi); } } elseif (!self::isOrderStateExecutorBlankable(trim($item->order_state)) && !$this->getConfig('import_without_executor_taxi')) { return $item_result->addMessage('The executor taxi company info is empty'); } // Обработка регистратора $registrant_str = trim($item->registrant); // Заказ сделан без участия диспетчера $by_automatic = (bool) preg_match('#\\.ru|\\.com|\\.net|\\.org|yandex#i', $item->order_source); if (!empty($item->registrant)) { $order->setRegistrantEmployeStr($registrant_str); $registrant_name = array(); // Заполняется функцией поиска $registrant_employe = $this->findRegistrants($item, $registrant_name); if (empty($registrant_employe)) { unset($registrant_employe); /*if ($this->getConfig('create_notfound_registrant')) { $registrant_employe = $this->createNewRegistrantEmploye($registrant_name); if (isset($owner_taxi)) // TODO: check if it's right $registrant_employe->setTaxiCompany($owner_taxi); // $item_result->addMessage('A new registrant employe created from provided data'); } else*/ // return $item_result->addMessage('The registrant is not found'); } elseif (count($registrant_employe) > 1) { return $item_result->addMessage('More than one employe found by the registrant name given'); } else { $registrant_employe = array_pop($registrant_employe); } if (isset($registrant_employe)) { $order->setRegistrantEmploye($registrant_employe); } } elseif (!$by_automatic && !$this->getConfig('import_without_registrant')) { return $item_result->addMessage('The registrant info is empty'); } // Process driver if (!empty($item->driver_phones)) { $driver_employe = $this->findDrivers($item); if (empty($driver_employe)) { unset($driver_employe); /*if ($this->getConfig('create_notfound_driver')) { $driver_employe = $this->createNewDriverEmploye($item); if (isset($executor_taxi)) $driver_employe->setTaxiCompany($executor_taxi); // $item_result->addMessage('A new driver created from provided data'); } else*/ // return $item_result->addMessage('The driver is not found'); } elseif (count($driver_employe) > 1) { return $item_result->addMessage('More than one employe found by the driver info given'); } else { $driver_employe = array_pop($driver_employe); } if (isset($driver_employe)) { $order->setDriverEmploye($driver_employe); } } elseif (!$this->getConfig('import_without_driver')) { return $item_result->addMessage('The driver phones are empty'); } // Process car // TODO: Function for car search $car_info = $this->parseCarInfo($item); if (isset($car_info['reg_nmb'])) { $order->setCarNmb($car_info['reg_nmb']); /** @var ORM\EntityRepository */ $car_rep = $this->_em->getRepository('TaxiPrizeTaxiBundle:Car'); /** @var Entity\Car */ $car = $car_rep->findOneBy(array('regNmb' => $car_info['reg_nmb'])); if (!is_null($car)) { $order->setCar($car); } } if (isset($car_info['model'])) { $order->setCarModel($car_info['model']); } if (isset($car_info['color'])) { $order->setCarColor($car_info['color']); } // Process order state if (is_array($state_map = self::$_order_state_map[$item->order_state])) { foreach ($state_map as $method => $value) { $order->{$method}($value); } } else { $order->setState($state_map); } // Other data $start_time = self::parseDateTime($item->started_at); $end_time = trim($item->ended_at); $end_time = empty($end_time) ? null : self::parseDateTime($end_time); $order->setExternalId($item->external_id)->setStartedAt($start_time)->setEndedAt($end_time)->setCommentary($item->commentary)->setPercent($item->percent)->setStartAddress($item->start_address)->setRoute($item->route)->setCost(round(floatval($item->cost), 2))->setExtraInfo($item->extra_info)->setCarInfo($item->car_info)->setDriverEmployeStr(trim($item->driver))->setClientName($item->client_name)->setClientPhone($item->client_phone)->setDiscountKeyword($item->discount_keyword)->setTariffInfo($item->base_tariff)->setIsClientCorporate($is_client_corporate)->setCreatedAt(new \DateTime()); $this->_em->persist($order); $this->_em->flush(); return $item_result->setSuccessful(); }
/** * @param Employes2ImportItem $item * @param AbstractItemImportResult $item_result * * @return AbstractItemImportResult */ protected function _processImportItem($item, &$item_result) { $merge_phones = $merge_cars = false; $employe = $this->findEmployes($item); if (empty($employe)) { $employe = new Entity\Employe(); } elseif ($this->getOption('update_existing')) { if (count($employe) > 1) { return $item_result->addMessage('More than one employe was found with the given data'); } else { $employe = array_pop($employe); if ($employe->getExternalId() !== (int) $item->external_id) { $merge_phones = $merge_cars = true; } } } else { return $item_result->addMessage('An employe with given external_id already exists'); } // Обработка компаний $_taxis_str = trim($item->taxis); $taxis = array(); if (!empty($_taxis_str)) { $str_taxis = array_map('trim', explode(',', $_taxis_str)); $notfound_str_taxis = array(); /** @var ORM\EntityRepository */ $rep = $this->_em->getRepository('TaxiPrizeTaxiBundle:TaxiCompany'); // TODO: Делать один запрос, перебирать массив результатов. foreach ($str_taxis as $str_taxi) { if (in_array($str_taxi, $notfound_str_taxis, true)) { continue; } $taxi = $rep->findOneBy(array('name' => $str_taxi)); if (empty($taxi)) { $notfound_str_taxis[] = $str_taxi; } else { $taxis[$taxi->getId()] = $taxi; } } if (!empty($notfound_str_taxis)) { if ($this->getOption('create_notfound_taxi_company')) { $new_taxis = array(); foreach ($notfound_str_taxis as $str_taxi) { $taxi = new Entity\TaxiCompany(); $taxi->setName($str_taxi); // $this->_em->persist($taxi); $taxis[] = $taxi; $new_taxis[] = $taxi; } // $this->_em->flush(); } elseif (!$this->getOption('import_with_notfound_taxi_companies')) { return $item_result->addMessage('Following taxis are not found: ' . implode(', ', $notfound_str_taxis)); } } // $employe->setTaxiCompanies($taxis); } elseif (!$this->getOption('import_without_taxi_companies')) { return $item_result->addMessage('Import without taxi companies is not allowed'); } if (!empty($taxis)) { // Обработка ролей $_roles_str = trim($item->roles); if (!empty($_roles_str)) { $str_roles = array_map('trim', explode(',', $_roles_str)); array_unique($str_roles); $notfound_str_roles = $str_name_roles = $str_title_roles = array(); foreach ($str_roles as $str_role) { if ($this->isRoleName($str_role)) { $str_name_roles[] = $str_role; } else { $str_title_roles[] = $str_role; } } // Отыскание несуществующих ролей $qb = $this->_em->createQueryBuilder(); $found_by_name = $qb->select('r')->from('TaxiPrizeTaxiBundle:EmployeRole', 'r', 'r.name')->where('r.name IN (:role_names)')->setParameter('role_names', $str_name_roles)->getQuery()->execute(); $qb = $this->_em->createQueryBuilder(); $found_by_title = $qb->select('r')->from('TaxiPrizeTaxiBundle:EmployeRole', 'r', 'r.title')->where('r.title IN (:role_titles)')->setParameter('role_titles', $str_title_roles)->getQuery()->execute(); $found_roles = array_merge($found_by_name, $found_by_title); $need_roles = $found_roles; $name_keys = array_keys($found_by_name); $title_keys = array_keys($found_by_title); $notfound_str_name_roles = array_diff($str_name_roles, $name_keys); $notfound_str_title_roles = array_diff($str_title_roles, $title_keys); $notfound_str_roles = array_merge($notfound_str_name_roles, $notfound_str_title_roles); if (!empty($notfound_str_roles)) { if ($this->getOption('create_notfound_role')) { $new_roles = array(); foreach ($notfound_str_roles as $str_role) { $role = new Entity\EmployeRole(); $this->isRoleName($str_role) ? $role->setName($str_role) : $role->setTitle($str_role); // $this->_em->persist($role); $new_roles[] = $role; $need_roles[] = $role; } // $this->_em->flush(); } else { return $item_result->addMessage('Following roles are not found: ' . implode(', ', $notfound_str_roles)); } } // Добавление несуществующих связей сотрудник - роль - компания $new_ecrs = array(); $rep = $this->_em->getRepository('TaxiPrizeTaxiBundle:EmployeCompanyRole'); foreach ($taxis as $taxi) { if (is_null($employe->getId())) { // Сотрудник новый, без сомнений добавляем все роли во все компании. foreach ($need_roles as $role) { $ecr = new Entity\EmployeCompanyRole($employe, $taxi, $role); $new_ecrs[] = $ecr; // $this->_em->persist($ecr); } } else { // Перед добавлением связки проверяем её существование foreach ($found_roles as $role) { if (is_null($rep->findOneBy(array('employe' => $employe, 'company' => $taxi, 'role' => $role)))) { $ecr = new Entity\EmployeCompanyRole($employe, $taxi, $role); $new_ecrs[] = $ecr; } } if (isset($new_roles)) { // Добавляем связки с новыми ролями foreach ($new_roles as $role) { $ecr = new Entity\EmployeCompanyRole($employe, $taxi, $role); $new_ecrs[] = $ecr; } } } } } } // Обработка автомобилей $_cars_str = trim($item->car_reg_nmbs); if (!empty($_cars_str)) { $cars = array(); $str_cars = array_map('trim', explode(',', $_cars_str)); $notfound_str_cars = array(); /** @var ORM\EntityRepository */ $rep = $this->_em->getRepository('TaxiPrizeTaxiBundle:Car'); // TODO: Делать один запрос, перебирать массив результатов. foreach ($str_cars as $str_car) { $res = $rep->findOneBy(array('regNmb' => $str_car)); if (empty($res)) { $notfound_str_cars[] = $str_car; } else { $cars[] = $res; } } if (!empty($notfound_str_cars)) { if ($this->getOption(self::OPTION_CREATE_NOTFOUND_CAR)) { foreach ($notfound_str_cars as $str_car) { $car = new Entity\Car(); $car->setRegNmb($str_car); $this->_em->persist($car); $cars[] = $car; } } } if ($merge_cars) { foreach ($cars as $car) { if (!$employe->getCars()->contains($car)) { $employe->addCar($car); } } } else { $employe->setCars($cars); } } // Остальные данные list($second_name, $first_name) = $this->parseName($item); $employe->setExternalId($item->external_id)->setSecondName($second_name)->setFirstName($first_name)->setImportName($item->name)->setCallsign($item->callsign)->setBalance(round(floatval($item->balance), 2))->setLastLocationChange($this->getRelocationDateTime($item))->setState($item->state); // Телефоны $phones = array_map('trim', preg_split('#[\\s,]+#', $item->phones)); if ($merge_phones) { $phones_cmpr = $employe->getWorkPhones(true); foreach ($phones as $phone) { if (!in_array(Entity\Client::compressPhone($phone), $phones_cmpr)) { $employe->addWorkPhone($phone); } } } else { $employe->setWorkPhones($phones); } // Сохранение подготовленных сущностей. // Первичный ключ EmployeCompanyRole состоит из внешних ключей, поэтому адресуемые сущности должны быть сохранены раньше. if (isset($new_taxis) && !empty($new_taxis)) { foreach ($new_taxis as $taxi) { $this->_em->persist($taxi); } } if (isset($new_roles) && !empty($new_roles)) { foreach ($new_roles as $role) { $this->_em->persist($role); } } $this->_em->beginTransaction(); try { $this->_em->persist($employe); $this->_em->flush(); if (isset($new_ecrs) && !empty($new_ecrs)) { foreach ($new_ecrs as $ecr) { $this->_em->persist($ecr); } } $this->_em->flush(); $this->_em->getConnection()->commit(); return $item_result->setSuccessful(); } catch (\Exception $e) { $this->_em->getConnection()->rollBack(); throw $e; } }
/** * @param CallsImportItem $item * @param AbstractItemImportResult $item_result * * @return AbstractItemImportResult */ protected function _processImportItem($item, &$item_result) { /** @var Entity\Call */ $call = $this->findCalls($item); if (empty($call)) { $call = new Entity\Call(); } elseif ($this->getConfig('update_existing')) { if (count($call) > 1) { return $item_result->addMessage('More than one calls was found with the given data'); } else { $call = array_pop($call); } } else { return $item_result->addMessage('A call with given external_id already exists'); } // process client $clients = $this->findClients($item); if (empty($clients)) { if (!$this->getConfig('import_with_notfound_client')) { return $item_result->addMessage('The client not found'); } } elseif (count($clients) > 1) { return $item_result->addMessage('More than one clients was found with the given data'); } else { $call->setClient(array_pop($clients)); } // process employe $employes = $this->findEmployes($item); if (empty($employes)) { if (!$this->getConfig('import_with_notfound_employe')) { return $item_result->addMessage('The employe not found'); } } elseif (count($employes) > 1) { return $item_result->addMessage('More than one employes was found with the given data'); } else { $call->setEmploye(array_pop($employes)); } // process group (company) $taxis = $this->findOwnerTaxis($item); if (empty($taxis)) { if (!$this->getConfig('import_with_notfound_taxi-company')) { return $item_result->addMessage('The taxi company not found'); } } elseif (count($taxis) > 1) { return $item_result->addMessage('More than one taxis was found with the given data'); } else { $call->setTaxiCompany(array_pop($taxis)); } // Обработка комментария. Там может быть ID заказа. $commentary = trim($item->commentary); if ((string) (int) $commentary === $commentary) { /** @var ORM\EntityRepository */ $rep = $this->_em->getRepository('TaxiPrizeTaxiBundle:Order'); /** @var Entity\Order */ $order = $rep->findOneBy(array('externalId' => $commentary)); // TODO: Что делать, есил заказ не найден? if (!is_null($order)) { // TODO: Что делать, если ID звонка уже выставлен? $order->setCall($call); $this->_em->persist($order); } } // Правка формата времени: 0:01:04 -> 00:01:04 strlen($item->reach_time) == 7 ? $reach_time = '0' . $item->reach_time : ($reach_time = $item->reach_time); strlen($item->duration) == 7 ? $duration = '0' . $item->duration : ($duration = $item->duration); // Остальные данные $call->setExternalId($item->external_id)->setDate(new \DateTime($item->date))->setDirection($this->convertDirection($item->direction))->setCallerPhone(Entity\Client::compressPhone($item->caller_phone))->setCallerName(trim($item->caller_name))->setGroupName(trim($item->group_name))->setEmployeName(trim($item->employe_name))->setChannelName(trim($item->channel_name))->setReachTime(new \DateTime($reach_time))->setDuration(new \DateTime($duration))->setCause(trim($item->cause))->setCommentary(trim($item->commentary)); $this->_em->persist($call); $this->_em->flush(); return $item_result->setSuccessful(); }