Guest User

Untitled

a guest
Jan 17th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.26 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Forest\Jobs\Imports;
  4.  
  5. use Forest\Jobs\Job;
  6.  
  7. use Illuminate\Bus\Queueable;
  8. use Illuminate\Queue\SerializesModels;
  9. use Illuminate\Queue\InteractsWithQueue;
  10. use Illuminate\Contracts\Queue\ShouldQueue;
  11. use Illuminate\Foundation\Bus\Dispatchable;
  12.  
  13. use Forest\Mail\SendEmailImport;
  14.  
  15. use Forest\Repositories\Imports\ImportationsRepository;
  16. use Forest\Repositories\Configurations\SegmentsRepository;
  17. use Forest\Repositories\Actors\ActorsRepository;
  18. use Forest\Repositories\AddressesRepository;
  19. use Forest\Repositories\Configurations\FlagsRepository;
  20. use Forest\Repositories\Configurations\BrandsRepository;
  21. use Forest\Repositories\Configurations\PartnersRepository;
  22. use Forest\Repositories\CustomersRepository;
  23. use Forest\Repositories\TimelinesRepository;
  24.  
  25. use Forest\Helpers\Common as Common;
  26.  
  27. use Illuminate\Contracts\Filesystem\Factory;
  28. use Illuminate\Support\Str;
  29. use Illuminate\Support\Facades\Log;
  30.  
  31. use DB, Request, Validator, Input, Redirect, Session, Paginator, Response, Queue, Bus, Mail, Carbon, Config, Storage, File, Excel;
  32.  
  33. class Customers implements ShouldQueue
  34. {
  35. use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
  36.  
  37. protected $file;
  38. protected $map;
  39. protected $actor_id;
  40. protected $tree_id;
  41. protected $user;
  42. protected $importationsRepository;
  43. protected $segmentsRepository;
  44. protected $actorsRepository;
  45. protected $addressRepository;
  46. protected $flagsRepository;
  47. protected $brandsRepository;
  48. protected $partnersRepository;
  49. protected $customersRepository;
  50. protected $timelinesRepository;
  51.  
  52. /**
  53. * Create a new command instance.
  54. *
  55. * @return void
  56. */
  57. public function __construct($file, $map, $actor_id, $tree_id, $user)
  58. {
  59. $this->file = $file;
  60. $this->map = $map;
  61. $this->actor_id = $actor_id;
  62. $this->tree_id = $tree_id;
  63. $this->user = $user;
  64. $this->importationsRepository = new ImportationsRepository;
  65. $this->segmentsRepository = new SegmentsRepository;
  66. $this->actorsRepository = new ActorsRepository;
  67. $this->addressRepository = new AddressesRepository;
  68. $this->flagsRepository = new FlagsRepository;
  69. $this->brandsRepository = new BrandsRepository;
  70. $this->partnersRepository = new PartnersRepository;
  71. $this->customersRepository = new CustomersRepository;
  72. $this->timelinesRepository = new TimelinesRepository;
  73. }
  74.  
  75. /**
  76. * Execute the command.
  77. *
  78. * @return void
  79. */
  80.  
  81. public function handle()
  82. {
  83. $file_rows = Excel::load(storage_path('app/' . $this->file['file_name']), function($reader)
  84. {
  85. $reader->toObject();
  86. })->get();
  87.  
  88. $data = [];
  89. $data_errors = [];
  90.  
  91. foreach ($file_rows as $key => $file_row)
  92. {
  93. foreach ($this->map as $column_database => $column_file)
  94. {
  95. if($column_file != "")
  96. {
  97. $validate = true;
  98.  
  99. /*
  100. * Verifica se o campo é CNPJ
  101. */
  102. if($column_database == 'cnpj')
  103. {
  104. $column_line = "A";
  105.  
  106. /*
  107. * Se existir um CNPJ
  108. */
  109. if(isset($file_row[$column_file]))
  110. {
  111. if($file_row[$column_file])
  112. {
  113. $data[$key][$column_database] = $file_row[$column_file];
  114.  
  115. /*
  116. * Veririca se este CNPJ é valido
  117. */
  118. if(!Common::verifyCNPJ($file_row[$column_file]))
  119. {
  120. $data_errors[$key]['cnpj'] = ['key' => $key, 'value' => 'cnpj', 'error' => 'CNPJ inválido.', 'column_line' => $column_line];
  121. }
  122. else
  123. {
  124. /*
  125. * Verifica se existe um cliente com este CNPJ
  126. */
  127. $customer = $this->customersRepository->getCustomerByCnpj(Common::verifyCNPJ($file_row[$column_file]));
  128.  
  129. /*
  130. * Se não existir um cliente com esse CNPJ
  131. */
  132. if($customer)
  133. {
  134. $data_errors[$key]['cnpj'] = ['key' => $key, 'value' => 'cnpj', 'error' => 'CNPJ existente no sistema.', 'column_line' => $column_line];
  135. }
  136. }
  137. }
  138. else
  139. {
  140. $data[$key][$column_database] = null;
  141. $data_errors[$key]['cnpj'] = ['key' => $key, 'value' => 'cnpj', 'error' => 'CNPJ é um campo obrigatório.', 'column_line' => $column_line];
  142. }
  143. }
  144.  
  145. /*
  146. * Se não existir
  147. */
  148. else
  149. {
  150. $data[$key][$column_database] = null;
  151. $data_errors[$key]['cnpj'] = ['key' => $key, 'value' => 'cnpj', 'error' => 'CNPJ é um campo obrigatório.', 'column_line' => $column_line];
  152. }
  153. }
  154.  
  155. /*
  156. * SE a coluna for razão social
  157. */
  158. else if($column_database == 'social_name')
  159. {
  160. $column_line = "B";
  161.  
  162. if(isset($file_row[$column_file]))
  163. {
  164. $data[$key][$column_database] = $file_row[$column_file];
  165.  
  166. if(!$file_row[$column_file])
  167. {
  168. $data_errors[$key]['social_name'] = ['key' => $key, 'value' => 'social_name', 'error' => 'Razão Social é um campo obrigatório.', 'column_line' => $column_line];
  169. }
  170. }
  171. else
  172. {
  173. $data[$key][$column_database] = null;
  174. $data_errors[$key]['social_name'] = ['key' => $key, 'value' => 'social_name', 'error' => 'Razão Social é um campo obrigatório.', 'column_line' => $column_line];
  175. }
  176. }
  177.  
  178. else if($column_database == 'fantasy_name')
  179. {
  180. if(isset($file_row[$column_file]))
  181. {
  182. $data[$key][$column_database] = $file_row[$column_file];
  183. }
  184. else
  185. {
  186. $data[$key][$column_database] = null;
  187. }
  188. }
  189.  
  190. else if($column_database == 'zip')
  191. {
  192. $column_line = "D";
  193.  
  194. if(isset($file_row[$column_file]))
  195. {
  196. $data[$key][$column_database] = $file_row[$column_file];
  197.  
  198. if(!$file_row[$column_file])
  199. {
  200. $data_errors[$key]['CEP'] = ['key' => $key, 'value' => 'CEP', 'error' => 'CEP é um campo obrigatório.', 'column_line' => $column_line];
  201. }
  202. }
  203. else
  204. {
  205. $data[$key][$column_database] = null;
  206. $data_errors[$key]['CEP'] = ['key' => $key, 'value' => 'CEP', 'error' => 'CEP é um campo obrigatório.', 'column_line' => $column_line];
  207. }
  208. }
  209.  
  210. else if($column_database == 'city')
  211. {
  212. $column_line = "E";
  213.  
  214. if(isset($file_row[$column_file]))
  215. {
  216. $data[$key][$column_database] = $file_row[$column_file];
  217.  
  218. if(!$file_row[$column_file])
  219. {
  220. $data_errors[$key]['Cidade'] = ['key' => $key, 'value' => 'Cidade', 'error' => 'Cidade é um campo obrigatório.', 'column_line' => $column_line];
  221. }
  222. }
  223. else
  224. {
  225. $data[$key][$column_database] = null;
  226. $data_errors[$key]['Cidade'] = ['key' => $key, 'value' => 'Cidade', 'error' => 'Cidade é um campo obrigatório.', 'column_line' => $column_line];
  227. }
  228. }
  229.  
  230. else if($column_database == 'state')
  231. {
  232. $column_line = "F";
  233.  
  234. if(isset($file_row[$column_file]))
  235. {
  236. $data[$key][$column_database] = $file_row[$column_file];
  237.  
  238. if(!$file_row[$column_file])
  239. {
  240. $data_errors[$key]['UF'] = ['key' => $key, 'value' => 'UF', 'error' => 'UF é um campo obrigatório.', 'column_line' => $column_line];
  241. }
  242. }
  243. else
  244. {
  245. $data[$key][$column_database] = null;
  246. $data_errors[$key]['UF'] = ['key' => $key, 'value' => 'UF', 'error' => 'UF é um campo obrigatório.', 'column_line' => $column_line];
  247. }
  248. }
  249.  
  250. else if($column_database == 'address')
  251. {
  252. $column_line = "G";
  253.  
  254. if(isset($file_row[$column_file]))
  255. {
  256. $data[$key][$column_database] = $file_row[$column_file];
  257.  
  258. if(!$file_row[$column_file])
  259. {
  260. $data_errors[$key]['Endereço'] = ['key' => $key, 'value' => 'Endereço', 'error' => 'Endereço é um campo obrigatório.', 'column_line' => $column_line];
  261. }
  262. }
  263. else
  264. {
  265. $data[$key][$column_database] = null;
  266. $data_errors[$key]['Endereço'] = ['key' => $key, 'value' => 'Endereço', 'error' => 'Endereço é um campo obrigatório.', 'column_line' => $column_line];
  267. }
  268. }
  269.  
  270. else if($column_database == 'number')
  271. {
  272. $column_line = "H";
  273.  
  274. if(isset($file_row[$column_file]))
  275. {
  276. $data[$key][$column_database] = $file_row[$column_file];
  277.  
  278. if(!$file_row[$column_file])
  279. {
  280. $data_errors[$key]['Número'] =['key' => $key, 'value' => 'Número', 'error' => 'Número é um campo obrigatório.', 'column_line' => $column_line];
  281. }
  282. }
  283. else
  284. {
  285. $data[$key][$column_database] = null;
  286. $data_errors[$key]['Número'] =['key' => $key, 'value' => 'Número', 'error' => 'Número é um campo obrigatório.', 'column_line' => $column_line];
  287. }
  288. }
  289.  
  290. else if($column_database == 'neighborhood')
  291. {
  292. $column_line = "I";
  293.  
  294. if(isset($file_row[$column_file]))
  295. {
  296. $data[$key][$column_database] = $file_row[$column_file];
  297.  
  298. if(!$file_row[$column_file])
  299. {
  300. $data_errors[$key]['Bairro'] =['key' => $key, 'value' => 'Bairro', 'error' => 'Bairro é um campo obrigatório.', 'column_line' => $column_line];
  301. }
  302. }
  303. else
  304. {
  305. $data[$key][$column_database] = null;
  306. $data_errors[$key]['Bairro'] =['key' => $key, 'value' => 'Bairro', 'error' => 'Bairro é um campo obrigatório.', 'column_line' => $column_line];
  307. }
  308. }
  309.  
  310. else if($column_database == 'complement')
  311. {
  312. if(isset($file_row[$column_file]))
  313. {
  314. $data[$key][$column_database] = $file_row[$column_file];
  315. }
  316. else
  317. {
  318. $data[$key][$column_database] = null;
  319. }
  320. }
  321.  
  322. else if($column_database == 'contact_name')
  323. {
  324. if(isset($file_row[$column_file]))
  325. {
  326. $data[$key][$column_database] = $file_row[$column_file];
  327. }
  328. else
  329. {
  330. $data[$key][$column_database] = null;
  331. $validate = false;
  332. }
  333. }
  334.  
  335. else if($column_database == 'email')
  336. {
  337. if(isset($file_row[$column_file]))
  338. {
  339. $data[$key][$column_database] = $file_row[$column_file];
  340. }
  341. else
  342. {
  343. $data[$key][$column_database] = null;
  344. }
  345. }
  346.  
  347. else if($column_database == 'phone')
  348. {
  349. if(isset($file_row[$column_file]))
  350. {
  351. $data[$key][$column_database] = $file_row[$column_file];
  352. }
  353. else
  354. {
  355. $data[$key][$column_database] = null;
  356. }
  357. }
  358.  
  359. else if($column_database == 'ie')
  360. {
  361. if(isset($file_row[$column_file]))
  362. {
  363. $data[$key][$column_database] = $file_row[$column_file];
  364. }
  365. else
  366. {
  367. $data[$key][$column_database] = null;
  368. }
  369. }
  370.  
  371. else if($column_database == 'im')
  372. {
  373. if(isset($file_row[$column_file]))
  374. {
  375. $data[$key][$column_database] = $file_row[$column_file];
  376. }
  377. else
  378. {
  379. $data[$key][$column_database] = null;
  380. }
  381. }
  382.  
  383. else if($column_database == 'segment')
  384. {
  385. $column_line = "P";
  386.  
  387. if(isset($file_row[$column_file]))
  388. {
  389. $data[$key][$column_database] = $file_row[$column_file];
  390.  
  391. $segment = $this->segmentsRepository->getSegmentByName($file_row[$column_file]);
  392.  
  393. if(!$segment)
  394. {
  395. $data_errors[$key]['Bairro'] =['key' => $key, 'value' => 'Segmento', 'error' => 'Este Segmento não é válido, infome algum dos seguinte Segmentos: Agro, Auto Peças, Auto Serviços, Centros Automotivos, Concessionárias, Distribuiores, Montadoras, Postos, Calçados', 'column_line' => $column_line];
  396. }
  397. }
  398. else
  399. {
  400. $data[$key][$column_database] = null;
  401. $data_errors[$key]['Segmento'] =['key' => $key, 'value' => 'Segmento', 'error' => 'Segmento é um campo obrigatório.', 'column_line' => $column_line];
  402. }
  403. }
  404.  
  405. else if($column_database == 'flag')
  406. {
  407. if(isset($file_row[$column_file]))
  408. {
  409. $data[$key][$column_database] = $file_row[$column_file];
  410. }
  411. else
  412. {
  413. $data[$key][$column_database] = null;
  414. }
  415. }
  416.  
  417. else if($column_database == 'partner')
  418. {
  419. if(isset($file_row[$column_file]))
  420. {
  421. $data[$key][$column_database] = $file_row[$column_file];
  422. }
  423. else
  424. {
  425. $data[$key][$column_database] = null;
  426. }
  427. }
  428.  
  429. else if($column_database == 'brand')
  430. {
  431. if(isset($file_row[$column_file]))
  432. {
  433. $data[$key][$column_database] = $file_row[$column_file];
  434. }
  435. else
  436. {
  437. $data[$key][$column_database] = null;
  438. }
  439. }
  440. }
  441. }
  442. }
  443.  
  444. $file_error = $this->generateExcelErrors($data_errors, $data);
  445. $data = $this->validateImportNotErrors($data_errors, $data);
  446.  
  447. try {
  448.  
  449. foreach ($data as $customer)
  450. {
  451. $address = $this->addressRepository->store($customer);
  452. $customer['address_id'] = $address->id;
  453. $customer['email'] = Common::validateEmail($customer['email']);
  454. $customer['phone'] = Common::validatePhone($customer['phone']);
  455. $customer['cnpj'] = Common::verifyCNPJ($customer['cnpj']);
  456. $customer['segment_id'] = null;
  457. $customer['flag_id'] = null;
  458. $customer['partner_id'] = null;
  459. $customer['brand_id'] = null;
  460. $customer['validated'] = 1;
  461. $customer['customer_matrix_id'] = null;
  462.  
  463. $customer['actors'][] = $this->actor_id;
  464.  
  465. $segment = $this->segmentsRepository->getSegmentByName($customer['segment']);
  466.  
  467. if($segment)
  468. {
  469. $customer['segment_id'] = $segment->id;
  470. }
  471.  
  472. $flag = $this->flagsRepository->getFlagByName($customer['flag']);
  473.  
  474. if($flag)
  475. {
  476. $customer['flag_id'] = $flag->id;
  477. }
  478.  
  479. $partner = $this->partnersRepository->getPartnerByName($customer['partner']);
  480.  
  481. if($partner)
  482. {
  483. $customer['partner_id'] = $partner->id;
  484. }
  485.  
  486. $brand = $this->brandsRepository->getBrandByName($customer['brand']);
  487.  
  488. if($brand)
  489. {
  490. $customer['brand_id'] = $brand->id;
  491. }
  492.  
  493. $new_customer = $this->customersRepository->store($customer);
  494.  
  495. if(!$new_customer->contact_name)
  496. {
  497. $new_customer->validated = 0;
  498. $new_customer->save();
  499. }
  500.  
  501. $new_customer->actors()->attach($this->actor_id, ['tree_id' => $this->tree_id]);
  502.  
  503. /*
  504. * Enviar para a timeline
  505. */
  506. $this->timelinesRepository->store([
  507. 'user_id' => $this->user->id,
  508. 'customer_id' => $new_customer->id,
  509. 'event_name' => 'CUSTOMER_IMPORT',
  510. 'description' => 'Importado pelo usuário ' . $this->user->name
  511. ]);
  512. }
  513.  
  514. $actor = $this->actorsRepository->getById($this->actor_id);
  515.  
  516. /*
  517. * Enviar para a timeline
  518. */
  519. if(count($data) > 1)
  520. {
  521. $description = 'Importou ' . count($data) . ' clientes para o ator '. $actor->name;
  522. }
  523. else
  524. {
  525. $description = 'Importou ' . count($data) . ' cliente'. $actor->name;
  526. }
  527.  
  528. if(count($data) > 0)
  529. {
  530. $this->timelinesRepository->store([
  531. 'user_id' => $this->user->id,
  532. 'actor_id' => $actor->id,
  533. 'event_name' => 'USER_IMPORT_CUSTOMERS',
  534. 'description' => $description
  535. ]);
  536. }
  537.  
  538. $importation = $this->importationsRepository->getImportation([
  539. 'status' => 'Processing',
  540. 'type' => 'Customers'
  541. ]);
  542.  
  543. if($importation)
  544. {
  545. $importation = $this->importationsRepository->update([
  546. 'id' => $importation->id,
  547. 'status' => 'Completed'
  548. ]);
  549.  
  550. Storage::disk('local')->delete($importation->file_name);
  551.  
  552. Mail::to($importation->user['email'])->send(new SendEmailImport($importation->user, $file_error, 'customers'));
  553. }
  554.  
  555. } catch (\Exception $e) {
  556. Log::info($e);
  557. }
  558.  
  559. /**
  560. * Remove da fila
  561. */
  562. $this->delete();
  563. }
  564.  
  565. public function generateExcelErrors($data_errors, $data)
  566. {
  567. $excel_data = [];
  568.  
  569. foreach ($data_errors as $data_error)
  570. {
  571. foreach ($data_error as $error)
  572. {
  573. if(isset($excel_data[$error['key']]))
  574. {
  575. $excel_data[$error['key']]['errors'] = $excel_data[$error['key']]['errors'] . ' - ' . $error['error'];
  576. }
  577. else
  578. {
  579. $excel_data[$error['key']] = $data[$error['key']];
  580. $excel_data[$error['key']]['errors'] = $error['error'];
  581. }
  582. }
  583. }
  584.  
  585. if(count($excel_data) > 0)
  586. {
  587. $data_errors = collect($data_errors)->values();
  588.  
  589. $name = 'clientes_com_errors'.date('Ymdhis');
  590.  
  591. Excel::create($name, function($excel) use($excel_data, $data_errors)
  592. {
  593. $excel->setTitle('Clientes com erros');
  594. $excel->sheet('Sheet', function($sheet) use ($excel_data, $data_errors) {
  595. $sheet->appendRow([
  596. 'CNPJ', 'Razão Social', 'Nome Fantasia', 'CEP', 'Cidade', 'UF', 'Endereço', 'Número', 'Bairro', 'Complemento', 'Nome de Contato', 'E-mail', 'Telefone', 'IE', 'IM', 'Segmento', 'Bandeira', 'Parceiro', 'Rede', 'Erros'
  597. ]);
  598.  
  599. $sheet->rows($excel_data);
  600.  
  601. foreach ($data_errors as $key => $data_error)
  602. {
  603. foreach ($data_error as $error)
  604. {
  605. $column_line = $key+2;
  606. $column_line = $error['column_line'].$column_line;
  607.  
  608. $sheet->cell($column_line, function($cell) {
  609. $cell->setBackground('#ffc000');
  610. $cell->setBorder('thin','thin','thin','thin');
  611. });
  612.  
  613. $column_line = $key+2;
  614. $column_line = 'T'.$column_line;
  615.  
  616. $sheet->cell($column_line, function($cell) {
  617. $cell->setBackground('#ffc000');
  618. $cell->setBorder('thin','thin','thin','thin');
  619. });
  620. }
  621. }
  622. });
  623.  
  624. })->store('xlsx', storage_path('importation/erros'));
  625.  
  626. return $name;
  627. }
  628. else
  629. {
  630. return null;
  631. }
  632. }
  633.  
  634. public function validateImportNotErrors($data_errors, $data)
  635. {
  636. foreach ($data_errors as $data_error)
  637. {
  638. foreach ($data_error as $error)
  639. {
  640. if(isset($data[$error['key']]))
  641. {
  642. unset($data[$error['key']]);
  643. }
  644. }
  645. }
  646.  
  647. return $data;
  648. }
  649. }
Add Comment
Please, Sign In to add comment