· 6 years ago · Aug 13, 2019, 06:58 AM
1<?php
2
3namespace App\Models;
4use App\Repositories\InvestmentRepository;
5use App\Repositories\DocumentRepository;
6use App\Repositories\CustomerRepository;
7use Illuminate\Support\Facades\DB;
8use Auth;
9
10class Customer extends AuthenticableModel
11{
12
13 protected $table = 'customer';
14 protected $primaryKey = 'customer_ID';
15
16 /**
17 * The attributes that are mass assignable.
18 *
19 * @var array
20 */
21 protected $fillable = [
22 'ga_secret_ID',
23 'parent_customer_ID',
24 'owner_ID',
25 'file_ID',
26 'slug',
27 'type',
28 'tipster',
29 'portfolio_manager',
30 'company_name',
31 'name',
32 'surname',
33 'password',
34 'degree',
35 'born_date',
36 'personal_in',
37 'phone',
38 'email',
39 'corporate_email',
40 'note',
41 'in',
42 'tin',
43 'registration_text',
44 'registered_for_vat',
45 'affiliate_target',
46 'affiliate_mining_target',
47 'affiliate_profit',
48 'struct_position',
49 'remember_token',
50 'token',
51 'token_created_at',
52 'active',
53 'verified',
54 'deleted_at',
55 'citizenship',
56 'sex',
57 'born_place',
58 'ID_type',
59 'ID_number',
60 'ID_place_of_issue',
61 'ID_validity_start',
62 'ID_validity_end',
63 'authorization_code',
64 'approved_at',
65 'is_admin',
66 'is_limited',
67 'is_trainer',
68 'main_image',
69 'want_be_representative',
70 'last_activity',
71 'reward_1',
72 'reward_2',
73 'reward_3',
74 'extended_registration_approved',
75 'customer_ap_ID',
76 ];
77
78 /**
79 * The attributes that should be hidden for arrays.
80 *
81 * @var array
82 */
83 protected $hidden = [
84 'password',
85 'remember_token',
86 ];
87
88 // relations
89 public function bankAccount()
90 {
91 return $this->hasMany('App\Models\CustomerBankAccount', 'customer_ID', 'customer_ID');
92 }
93
94
95 public function address()
96 {
97 return $this->hasMany('App\Models\CustomerAddress', 'customer_ID', 'customer_ID');
98 }
99 public function investment()
100 {
101 return $this->hasMany('App\Models\Investment', 'customer_ID', 'customer_ID');
102 }
103
104 public function investmentMining()
105 {
106 return $this->investment()->where('product_ID', 3)->get();
107 }
108
109 public function beneficiaryInvestment()
110 {
111 return $this->hasOne('App\Models\Investment', 'beneficiary_ID', 'customer_ID');
112 }
113 public function owner()
114 {
115 return $this->hasOne('App\Models\Customer', 'customer_ID', 'owner_ID');
116 }
117 public function ownedInvestment()
118 {
119 return $this->hasMany('App\Models\Investment', 'owner_ID', 'customer_ID');
120 }
121 public function gaSecret()
122 {
123 return $this->hasOne('App\Models\GaSecret', 'ga_secret_ID', 'ga_secret_ID');
124 }
125 public function stats()
126 {
127 return $this->hasMany('App\Models\CustomerStats', 'customer_ID', 'customer_ID');
128 }
129 public function affiliateReport()
130 {
131 return $this->hasMany('App\Models\AffiliateReport', 'customer_ID', 'customer_ID');
132 }
133 public function affiliateMove()
134 {
135 return $this->hasMany('App\Models\AffiliateMove', 'owner_ID', 'customer_ID');
136 }
137
138 public function affiliateTarget() {
139 if($this->affiliate_target == 'BANK_ACCOUNT' || $this->affiliate_target == null)
140 return $this->hasOne('App\Models\Investment','investment_ID','affiliate_target')->where('investment_ID','=','0');
141 return $this->hasOne('App\Models\Investment','investment_ID','affiliate_target');
142 }
143
144 public function document()
145 {
146 return $this->hasMany('App\Models\Document', 'customer_ID', 'customer_ID');
147 }
148 public function beneficiary()
149 {
150 return $this->hasMany('App\Models\Customer', 'parent_customer_ID', 'customer_ID');
151 }
152 public function investmentAsBeneficiary()
153 {
154 return $this->hasMany('App\Models\Investment', 'beneficiary_ID', 'customer_ID');
155 }
156 public function calendarEventMember()
157 {
158 return $this->hasMany('App\Models\CalendarEventMember', 'customer_ID', 'customer_ID');
159 }
160 public function email()
161 {
162 return $this->hasMany('App\Models\Email', 'customer_ID', 'customer_ID');
163 }
164 public function wallPost()
165 {
166 return $this->hasMany('App\Models\WallPost', 'customer_ID', 'customer_ID');
167 }
168 public function setting()
169 {
170 return $this->hasMany('App\Models\CustomerSetting', 'customer_ID', 'customer_ID');
171 }
172 public function file()
173 {
174 return $this->belongsToMany('App\Models\File', 'customer_file', 'customer_ID', 'file_ID');
175 }
176
177 public function avatar()
178 {
179 return $this->hasOne('App\Models\File', 'file_ID', 'file_ID');
180 }
181
182 public function getPersonalDocuments()
183 {
184 return $this->document()
185 ->where('type','=','CV')
186 ->orWhere('type','=','BARRETT_TEST')
187 ->orWhere('type','=','CRIMINAL_RECORD')
188 ->orWhere('type','=','FORM_TO_REP_CONTRACT')
189 ->get();
190 }
191
192 // getters
193 public function getCustomerID()
194 {
195 return $this->customer_ID;
196 }
197 public function getGaSecretID()
198 {
199 return $this->ga_secret_ID;
200 }
201 public function getParentCustomerID()
202 {
203 return $this->parent_customer_ID;
204 }
205 public function getOwnerID()
206 {
207 return $this->owner_ID;
208 }
209 public function getSlug()
210 {
211 return $this->slug;
212 }
213 public function getType()
214 {
215 return $this->type;
216 }
217 public function getTipster()
218 {
219 return $this->tipster;
220 }
221 public function getPortfolioManager()
222 {
223 return $this->portfolio_manager;
224 }
225 public function getCompanyName()
226 {
227 return $this->company_name;
228 }
229 public function getName()
230 {
231 return $this->name;
232 }
233 public function getSurname()
234 {
235 return $this->surname;
236 }
237 public function getPassword()
238 {
239 return $this->password;
240 }
241 public function getDegree()
242 {
243 return $this->degree;
244 }
245 public function getBornDate()
246 {
247 return $this->born_date;
248 }
249 public function getPersonalIn()
250 {
251 return $this->personal_in;
252 }
253 public function getPhone()
254 {
255
256 return $this->phone;
257 }
258 public function getPhoneLink()
259 {
260
261 return $this->phone;
262 }
263 public function getEmail()
264 {
265 return $this->email;
266 }
267 public function getCorporateEmail()
268 {
269 return $this->corporate_email;
270 }
271 public function getNote()
272 {
273 return $this->note;
274 }
275 public function getIn()
276 {
277 return $this->in;
278 }
279 public function getTin()
280 {
281 return $this->tin;
282 }
283 public function getRegistrationText()
284 {
285 return $this->registration_text;
286 }
287 public function getRegisteredForVat()
288 {
289 return $this->registered_for_vat;
290 }
291 public function getAffiliateTarget()
292 {
293 return $this->affiliate_target;
294 }
295 public function getAffiliateMiningTarget()
296 {
297 return $this->affiliate_mining_target;
298 }
299 public function getAffiliateProfit()
300 {
301 return $this->affiliate_profit;
302 }
303
304 public function getRememberToken()
305 {
306 return $this->remember_token;
307 }
308 public function getToken()
309 {
310 return $this->token;
311 }
312 public function getTokenCreatedAt()
313 {
314 return $this->token_created_at;
315 }
316 public function getActive()
317 {
318 return $this->active;
319 }
320 public function getVerified()
321 {
322 return $this->verified;
323 }
324 public function getDeletedAt()
325 {
326 return $this->deleted_at;
327 }
328 public function getCitizenship()
329 {
330 return $this->citizenship;
331 }
332 public function getSex()
333 {
334 return $this->sex;
335 }
336 public function getBornPlace()
337 {
338 return $this->born_place;
339 }
340 public function getIDType()
341 {
342 return $this->ID_type;
343 }
344 public function getIDNumber()
345 {
346 return $this->ID_number;
347 }
348 public function getIDPlaceOfIssue()
349 {
350 return $this->ID_place_of_issue;
351 }
352 public function getIDValidityStart()
353 {
354 return $this->ID_validity_start;
355 }
356 public function getIDValidityEnd()
357 {
358 return $this->ID_validity_end;
359 }
360 public function getAuthorizationCode()
361 {
362 return $this->authorization_code;
363 }
364 public function getApprovedAt()
365 {
366 return $this->approved_at;
367 }
368 public function getIsAdmin()
369 {
370 return $this->is_admin;
371 }
372 public function getIsLimited()
373 {
374 return $this->is_limited;
375 }
376 public function getIsTrainer()
377 {
378 return $this->is_trainer;
379 }
380 public function getMainImage()
381 {
382 return $this->main_image;
383 }
384 public function getWantBeRepresentative()
385 {
386 return $this->want_be_representative;
387 }
388 public function getLastActivity()
389 {
390 return $this->last_activity;
391 }
392 public function getReward1()
393 {
394 return $this->reward_1;
395 }
396 public function getReward2()
397 {
398 return $this->reward_2;
399 }
400 public function getReward3()
401 {
402 return $this->reward_3;
403 }
404
405 public function getDepositsAmount()
406 {
407 return $this->deposits_amount;
408 }
409 public function getExtendedRegistrationApproved()
410 {
411 return $this->extended_registration_approved;
412 }
413 public function getFullName()
414 {
415 if ($this->company_name != null) {
416 return $this->company_name;
417 }
418
419 return $this->name . ' ' . $this->surname;
420 }
421
422 public function getStructPosition()
423 {
424 if ($this->custom_struct_position != null) {
425 return $this->custom_struct_position;
426 }
427
428 return $this->struct_position;
429 }
430
431 public function getCustomStructPosition()
432 {
433 return $this->custom_struct_position;
434 }
435
436 public function getStrPosition()
437 {
438 return $this->struct_position;
439 }
440
441 public function getModelType() {
442 return "CUSTOMER";
443 }
444
445 public function getBankAccountCurrency() {
446
447 $bankAccount = $this->primaryBankAccount();
448 return $bankAccount != null ? $bankAccount->getCurrency() : '';
449
450 }
451
452
453 public function getBankAccountNumberFull() {
454 $bankAccount = $this->primaryBankAccount();
455 if($bankAccount->bank == null)
456 return $bankAccount->getIBAN();
457
458 return $bankAccount != null ? $bankAccount->getAccount().'/'.$bankAccount->bank->getCode() : '';
459 }
460
461 public function getTypeName($type = null) {
462 $names = $this->getTypesNames();
463 if ($type == null) {
464 $type = $this->type;
465 }
466
467 if (isset($names[$type])) {
468 return $names[$type];
469 }
470
471 return $type;
472 }
473
474 public function getTypesNames() {
475 $types = [
476 'TOP_REP_MANAGER' => 'TOP Manažer',
477 'REP_MANAGER' => 'Manažer',
478 'TOP_REP' => 'TOP Obchodní zástupce',
479 'REP' => 'Obchodní zástupce',
480 'CUSTOMER' => 'Klient',
481 'USER' => 'Správce',
482 'MANAGER' => 'Správce'
483 ];
484 return $types;
485 }
486
487 public function getStructByStructPosition() {
488
489 $array = [];
490 $lastOwner = $this;
491 $lastOwnerStructPosition = $lastOwner->getStructPosition();
492 $checkStruct = true;
493
494 while($checkStruct) {
495
496 // reload last owner
497 $lastOwner = $lastOwner->owner;
498
499 if(is_null($lastOwner))
500 return $array;
501
502 // if last owner struct position is higher than previous last owner struct position,
503 // save it and reset struct position
504 if($lastOwner->getStructPosition() > $lastOwnerStructPosition) {
505 $array[] = $lastOwner;
506 $lastOwnerStructPosition = $lastOwner->getStructPosition();
507 }
508
509 // check if should do loop or not
510 // -> stop loop if no owner or last owner struct position is 1 -> 1%
511 if($lastOwner->getStructPosition() == 1 || $lastOwner->owner == null)
512 $checkStruct = false;
513
514 }
515
516 return $array;
517
518 }
519
520 public function ownSumInvestmentAmount(){
521 return $this->investment()
522 ->whereNotNull('started_at')
523 ->whereNull('deleted_at')
524 ->sum('present_amount');
525 }
526
527 public function getUpdatedAt()
528 {
529 return $this->updated_at;
530 }
531
532 public function getArraySetting()
533 {
534 $array = [
535 'setting' => $this->setting,
536 'affiliate_target' => $this->getAffiliateTarget(),
537 'affiliate_mining_target' => $this->getAffiliateMiningTarget(),
538 'avatar' => $this->avatar,
539 'twofactor_state' => $this->get2FAState()
540 ];
541
542 $array['investment_product_2'] = $this->investment()->select('code','investment_ID')->whereNull('deleted_at')->where('product_ID',2)->get();
543 $array['investment_product_3'] = $this->investment()->select('code','investment_ID')->whereNull('deleted_at')->where('product_ID',3)->get();
544
545 return $array;
546 }
547
548 public function getArrayDefault()
549 {
550 $array = [
551 'customer_ID' => $this->getCustomerID(),
552 'owner_ID' => $this->getOwnerID(),
553 'name' => $this->getName(),
554 'surname' => $this->getSurname(),
555 'fullname' => $this->getFullname(),
556 'slug' => $this->getSlug(),
557 'type' => $this->getType(),
558 'tipster' => $this->getTipster()
559 ];
560 return $array;
561 }
562
563 public function getArrayBasic()
564 {
565 $array = [
566 'customer_ID' => $this->getCustomerID(),
567 'owner_ID' => $this->getOwnerID(),
568 'born_date' => format_iso_to_date($this->getBornDate()),
569 'authorization_code' => $this->getAuthorizationCode(),
570 'slug' => $this->getSlug(),
571 'name' => $this->getName(),
572 'surname' => $this->getSurname(),
573 'address' => $this->getPrimaryAddress(),
574 'secondary_address' => $this->getSecondaryAddress(),
575 'email' => $this->getEmail(),
576 'phone' => $this->getPhone(),
577 'phone_formated' => format_phone($this->getPhone()),
578 'phone_link' => $this->getPhoneLink(),
579 'type' => $this->getType(),
580 'avatar' => $this->avatar,
581 'avatar_path' => $this->avatar != null ? $this->avatar->getPath() : ''
582 ];
583 return $array;
584 }
585
586 public function getArrayDatatables() {
587 $array = [
588 'customer_ID' => $this->getCustomerID(),
589 'slug' => $this->getSlug(),
590 'name' => $this->getName(),
591 'surname' => $this->getSurname(),
592 'fullname_avatar_link' => 'BLA BLA '.$this->getFullName().'',
593 'email' => $this->getEmail(),
594 'born_date' => format_iso_to_date($this->getBornDate()),
595 'authorization_code' => $this->getAuthorizationCode(),
596 'phone_formated' => format_phone($this->getPhone()),
597 'avatar' => $this->avatar,
598 'avatar_path' => $this->avatar != null ? $this->avatar->getPath() : ''
599 ];
600 return $array;
601 }
602
603 public function getArrayStructure()
604 {
605 $array = [
606 'customer_ID' => $this->getCustomerID(),
607 'slug' => $this->getSlug(),
608 'owner_ID' => $this->getOwnerID(),
609 'name' => $this->getName(),
610 'surname' => $this->getSurname(),
611 'email' => $this->getEmail(),
612 'type' => $this->getType(),
613 'own_sum_investment_amount' => format_price($this->ownSumInvestmentAmount()),
614 'structure_sum_investment_amount' => format_price('1000'),
615 'avatar' => $this->avatar,
616 'avatar_path' => $this->avatar != null ? $this->avatar->getPath() : ''
617 ];
618 return $array;
619 }
620
621
622 public function getArrayExtend()
623 {
624 $array = [
625 'type' => $this->getType(),
626 'note' => $this->getNote(),
627 'authorization_code' => $this->getAuthorizationCode(),
628 'corporate_email' => $this->getCorporateEmail(),
629 'personal_in' => $this->getPersonalIn(),
630 'active' => $this->getActive(),
631 'verified' => $this->getVerified(),
632 'struct_position' => roundNumber($this->getStrPosition(),1),
633 'custom_struct_position' => roundNumber($this->getCustomStructPosition(),1),
634 'is_limited' => $this->getIsLimited(),
635 'want_be_representative' => $this->getWantBeRepresentative(),
636 'updated_at' => $this->getUpdatedAt(),
637 'updated_at_formated' => getFormatedDateTime($this->getUpdatedAt()),
638 'avatar' => $this->avatar,
639 'avatar_path' => $this->avatar != null ? $this->avatar->getPath() : '',
640 'can_create_investment' => $this->canCreateInvestment()
641 ];
642 return $array;
643 }
644
645 public function canCreateInvestment() {
646 $loggedInCustomer = Auth::guard('customer')->user();
647 return $loggedInCustomer != null && $loggedInCustomer->isRepresentative();
648 }
649
650 public function getArrayTraining()
651 {
652 $array = [
653 'customer_ID' => $this->getCustomerID(),
654 'name' => $this->getName(),
655 'surname' => $this->getSurname(),
656 'fullname' => $this->getFullname(),
657 'slug' => $this->getSlug(),
658 'type' => $this->getType(),
659 'email' => $this->getEmail(),
660 'phone_formated' => format_phone($this->getPhone())
661 ];
662 return $array;
663 }
664
665 public function getArrayBeneficiaryInvestment()
666 {
667 $array = [
668 'investment' => $this->beneficiaryInvestment,
669 ];
670 return $array;
671 }
672
673 public function getPrimaryAddress(){
674 return $this->address()->where('type',"PRIMARY")->first();
675 }
676
677 public function getSecondaryAddress(){
678 return $this->address()->where('type',"SECONDARY")->first();
679 }
680
681 public function hasSameShipping() {
682 return $this->getSecondaryAddress() != null;
683 }
684
685 public function primaryBankAccount(){
686 return $this->bankAccount()->where('type',"PRIMARY")->first();
687 }
688
689 public function secondaryBankAccount(){
690 return $this->bankAccount()->where('type',"SECONDARY")->first();
691 }
692
693
694
695
696 public function getAddress(){
697 $address = $this->primaryAddress();
698 if(isset($address)){
699 $adressInString = $address->getStreet().", ".$address->getCity();
700 if($address->country != null)
701 $adressInString .= ', '.$address->country->getName();
702 } else {
703 $adressInString = "";
704 }
705 return $adressInString;
706 }
707
708 public function getShippingAddress(){
709 $address = $this->secondaryAddress();
710 if(isset($address)){
711 $adressInString = $address->getStreet().", ".$address->getCity();
712 if($address->country != null)
713 $adressInString .= ', '.$address->country->getName();
714 } else {
715 $adressInString = "";
716 }
717 return $adressInString;
718 }
719
720 public function name(){
721 $name = $this->getName();
722 $surname = $this->getSurname();
723 $nameInString = $name." ".$surname;
724 return $nameInString;
725 }
726
727 public function getDocumentLocale(){
728 $documentLocale = $this->setting()->where('key','locale')->where('customer_ID',$this->getCustomerID())->first();
729 return $documentLocale->getValue();
730 }
731
732 public function getAffiliateBankAccount() {
733
734 if($this->secondary_bank_account != null) {
735 $return = $this->secondary_bank_account != null ? $this->secondary_bank_account : ' ';
736 if($this->secondaryBank != null)
737 $return .= ' / ' . $this->secondaryBank->code;
738
739 return $return;
740 }
741
742 $return = $this->bank_account != null ? $this->bank_account : ' ';
743 if($this->bank != null)
744 $return .= ' / ' . $this->bank->code;
745
746 return $return;
747
748 }
749
750 public function getAffiliateBankAccountIBAN() {
751
752 if($this->secondary_bank_account_IBAN != null) {
753 return $this->secondary_bank_account_IBAN;
754 }
755
756 return $this->bank_account_IBAN;
757
758 }
759
760 public function affiliateMoves() {
761
762 return $this->hasMany('App\Models\AffiliateMove', 'owner_ID', 'customer_ID')->where('owner_type', '=', 'CUSTOMER');
763
764 }
765
766 public function primaryAddress(){
767 return $this->address()->where('type',"PRIMARY")->first();
768 }
769
770 public function secondaryAddress(){
771 return $this->address()->where('type',"SECONDARY")->first();
772 }
773
774 public function getAddressSwitch(){
775 $secondary = $this->address()->where('type',"SECONDARY")->first();
776 if(is_null($secondary)){
777 return 1;
778 }
779 return 0;
780 }
781
782 public function isTipster(){
783 $isTipster = $this->getTipster();
784 if($isTipster == NULL){
785 return false;
786 } else {
787 return true;
788 }
789 }
790
791 public function getArrayFullname(){
792 $array = [
793 'customer_ID' => $this->getCustomerID(),
794 'fullname' => $this->getFullName()
795 ];
796 return $array;
797 }
798
799 public function getTotalOwnAmount(){
800 print_r($this);
801 die;
802 }
803
804 public function getArrayEditForm()
805 {
806 $array = [
807 'customer_ID' => $this->getCustomerID(),
808 'owner_ID' => $this->getOwnerID(),
809 'type' => $this->getType(),
810 'tipster' => $this->getTipster(),
811 'portfolio_manager' => $this->getPortfolioManager(),
812 'company_name' => $this->getCompanyName(),
813 'name' => $this->getName(),
814 'surname' => $this->getSurname(),
815 'citizenship' => $this->getCitizenship(),
816 'degree' => $this->getDegree(),
817 'personal_in' => $this->getPersonalIn(),
818 'sex' => $this->getSex(),
819 'born_date' => $this->getBornDate(),
820 'born_place' => $this->getBornPlace(),
821 'in' => $this->getIn(),
822 'tin' => $this->getTin(),
823 'parent_customer_ID' => $this->getParentCustomerID(),
824 'registration_text' => $this->getRegistrationText(),
825 'authorization_code' => $this->getAuthorizationCode(),
826 'ID_type' => $this->getIDType(),
827 'ID_number' => $this->getIDNumber(),
828 'ID_place_of_issue' => $this->getIDPlaceOfIssue(),
829 'ID_validity_start' => $this->getIDValidityStart(),
830 'ID_validity_end' => $this->getIDValidityEnd(),
831 'phone' => $this->getPhone(),
832 'email' => $this->getEmail(),
833 'primary_bank_account' => $this->primaryBankAccount(),
834 'secondary_bank_account' => $this->secondaryBankAccount(),
835 'primary_address' => $this->primaryAddress(),
836 'secondary_address' => $this->secondaryAddress(),
837 'address_switch' => $this->getAddressSwitch(),
838 ];
839 return $array;
840 }
841
842 public function getAffiliateToArray(){
843 $affiliate = [
844 'affiliate_target' => $this->getAffiliateTarget(),
845 'affiliate_mining_target' => $this->getAffiliateMiningTarget(),
846 ];
847 return $affiliate;
848 }
849
850 public function getToArray($scopes = [])
851 {
852 $array = array();
853 if (is_array($scopes)) {
854 foreach ($scopes as $scope) {
855 //echo $scope;
856 switch ($scope) {
857 //Basic customer info
858 case "customerBasic":
859 $arrayBasic = $this->getArrayBasic();
860 $array = $array + $arrayBasic;
861 break;
862 case "customerDatatables":
863 $arrayDatatables = $this->getArrayDatatables();
864 $array = $array + $arrayDatatables;
865 break;
866 //Extend customer info
867 case "customerExtend":
868 $arrayBasic = $this->getArrayBasic();
869 $arrayExtend = $this->getArrayExtend();
870 $array = $array + $arrayBasic + $arrayExtend;
871 break;
872 //Create bridge from customer to investment with basic info
873 case "customerInvestmentBasic":
874 $scopeInvestment = ["investmentBasic"];
875 $investments = $this->investment()->whereNull('deleted_at')->get();
876 foreach ($investments as $investment) {
877 $array['investment'][] = $investment->getToArray($scopeInvestment);
878 }
879 break;
880 case "customerStructure":
881 $arrayBasic = $this->getArrayStructure();
882 $array = $array + $arrayBasic;
883 break;
884 //Create bridge from customer to investment with basic info
885 case "customerInvestmentAll":
886 $scopeInvestment = ["investmentExtend"];
887 $investments = $this->investment;
888 foreach ($investments as $investment) {
889 $array['investment'][] = $investment->getToArray($scopeInvestment);
890 }
891 break;
892 //Create bridge from customer to investment with extend info
893 case "customerInvestmentExtend":
894 $scopeInvestment = ["investmentExtend"];
895 $investments = $this->investment;
896 foreach ($investments as $investment) {
897 $array['investment'][] = $investment->getToArray($scopeInvestment);
898 }
899 break;
900 //Create bridge from customer to mining investment with basic
901 case "customerInvestmentMiningBasic":
902 $scopeInvestment = ["investmentBasic"];
903 $investments = $this->investmentMining();
904 foreach ($investments as $investment) {
905 $array['investment'][] = $investment->getToArray($scopeInvestment);
906 }
907 break;
908 //Create bridge from customer to beneficiary wit basic info
909 case "customerBeneficiary":
910 $scopeInvestment = ["investmentCode"];
911 $beneficiaries = $this->beneficiary;
912 foreach ($beneficiaries as $beneficiary) {
913 $array['beneficiargety'][] = $beneficiary->getToArray();
914 }
915
916 break;
917 //Create bridge from customer to file
918 case "customerFile":
919 $files = $this->file;
920 foreach ($files as $file) {
921 $array['file'][] = $file->getToArray();
922 }
923
924
925 // PERSONAL DOCUMENTS
926 $documents = $this->getPersonalDocuments();
927 foreach($documents as $document) {
928 $array['file'][] = $document->getToArray();
929 }
930
931 // JESTE VYTAHNOUT, KDE TYP JE OFFICE_DOCUMENT
932
933 break;
934 //Create bridge from customer to document
935 case "customerDocument":
936 //$documents = $this->getPersonalDocuments();
937 $documents = $this->document()->whereIn('type',['AREA_REPRESENTATIVE_CONTRACT','AREA_REPRESENTATIVE_CONTRACT_APPENDIX'])->get();
938 foreach ($documents as $document) {
939 $array['document'][] = $document->getToArray();
940 }
941 break;
942 //Create bridge from customer to owner
943 case "customerOwnerBasic":
944 $scopeOwner = ["customerBasic"];
945 $owner = $this->owner;
946 if(isset($owner))
947 $array['owner'][] = $owner->getToArray($scopeOwner);
948 break;
949 case "customerEditForm":
950 $arrayEditForm = $this->getArrayEditForm();
951 $array = $array + $arrayEditForm;
952 break;
953 case "customerFullname":
954 $arrayFullname = $this->getArrayFullname();
955 $array = $array + $arrayFullname;
956 break;
957 case "customerSetting":
958 $arraySetting = $this->getArraySetting();
959 $array = $array + $arraySetting;
960 break;
961 case "customerInvestmentActivateInfo":
962 $investmentRepository = New InvestmentRepository;
963 $investmentInfo = $investmentRepository->getInvestmentActivateInfo($this)->count();
964 $investmentInfoArray = [
965 'investment_inactive' => $investmentInfo,
966 ];
967 $array = $array + $investmentInfoArray;
968 break;
969 case "customerDocumentInOffice":
970 $documentRepository = New DocumentRepository;
971 $documentInOfficeInfo = $documentRepository->getDocumentInOfficeByCustomer($this)->count();
972 $documentInOfficeInfoArray = [
973 'document_not_in_office' => $documentInOfficeInfo,
974 ];
975 $array = $array + $documentInOfficeInfoArray;
976 break;
977 case "customerTraining":
978 $arrayBasic = $this->getArrayTraining();
979 $array = $array + $arrayBasic;
980 break;
981
982
983 }
984 }
985 }
986
987 if (!count($array)) {
988 $array = $this->getArrayDefault();
989 }
990
991 return $array;
992 }
993
994 public function getStructureToArray($customerID, $arrayOfCustomerID, $scopes = [])
995 {
996 $array = array();
997 if (is_array($scopes)) {
998 foreach ($scopes as $scope) {
999
1000 switch ($scope) {
1001 case "customerStructure":
1002 $arrayBasic = $this->getArrayStructure();
1003 $array = $array + $arrayBasic;
1004 break;
1005
1006 case "customerInvestmentStructure":
1007 $investmentRepository = New InvestmentRepository;
1008 $scopeInvestment = ["investmentStructure"];
1009
1010 $investments = $investmentRepository->getNotEndOwn($customerID, $arrayOfCustomerID);
1011 //$investments = $investmentRepository->getNotEndInStructure($this, $arrayOfCustomerID);
1012 //$investments = $this->investment()->whereIn('owner_ID', $arrayOfCustomerID)->get();
1013
1014 foreach ($investments as $investment) {
1015 $array['investment'][] = $investment->getToArray($scopeInvestment);
1016 }
1017 break;
1018
1019 case "customerInvestmentStructureAll":
1020 $investmentRepository = New InvestmentRepository;
1021 $scopeInvestment = ["investmentStructure"];
1022 $investments = $investmentRepository->getNotEndAll($customerID, $arrayOfCustomerID);
1023 //$investments = $investmentRepository->getNotEndInStructure($this, $arrayOfCustomerID);
1024 //$investments = $this->investment()->whereIn('owner_ID', $arrayOfCustomerID)->get();
1025
1026 foreach ($investments as $investment) {
1027 $array['investment'][] = $investment->getToArray($scopeInvestment);
1028 }
1029 break;
1030
1031 }
1032 }
1033 }
1034
1035 if (!count($array)) {
1036 $array = $this->getArrayDefault();
1037 }
1038
1039 return $array;
1040 }
1041
1042 public function isRepresentative() {
1043 if($this->getType() == "CUSTOMER" or $this->getType() == "BENEFICIARY" ) {
1044 return false;
1045 } else {
1046 return true;
1047 }
1048 }
1049
1050 public function getEmailByCustomerType() {
1051 if($this->isRepresentative()) {
1052 return $this->getCorporateEmail();
1053 } else {
1054 return $this->getEmail();
1055 }
1056 }
1057
1058 public function getOwnerID2() {
1059 return $this->getCustomerID();
1060 }
1061
1062 public function getInvestmentsOwners() {
1063
1064 $owners = [];
1065
1066 foreach($this->investment as $investment) {
1067 if($investment->owner != null) {
1068 $owners[$investment->owner->getOwnerID2()] = $investment->owner;
1069 }
1070 }
1071
1072 return $owners;
1073
1074 }
1075
1076 public function getOwnerType() {
1077 return 'CUSTOMER';
1078 }
1079
1080 public function getPathByInvestments($toCustomer = null, $path = []) {
1081
1082 if ($toCustomer == null) {
1083 $toCustomer = Auth::guard('customer')->user();
1084 }
1085
1086 $owner = null;
1087 // $owner = $this->owner;
1088 $investmentsOwners = $this->getInvestmentsOwners();
1089 foreach ($investmentsOwners as $investmentOwner) {
1090 // check if one owner is same as logged in customer
1091 if ($investmentOwner->getOwnerID2() == $toCustomer->getOwnerID2() && $investmentOwner->getOwnerType() == $toCustomer->getOwnerType()) {
1092 $owner = $investmentOwner;
1093 break;
1094 }
1095 }
1096
1097 if ($owner == null) {
1098 // if(count($investmentsOwners))
1099 $owner = $this->owner;
1100 }
1101
1102 // if first one item, add also this item
1103 if (count($path) == 0) {
1104 array_unshift($path, $this);
1105 }
1106
1107 array_unshift($path, $owner);
1108
1109 if ($owner != null && ($owner->getOwnerID2() == $toCustomer->getOwnerID2() && $owner->getOwnerType() == $toCustomer->getOwnerType())) {
1110 return $path;
1111 } else if ($owner != null && $owner->getOwnerType() == 'USER') {
1112 return $path;
1113 } else if ($owner != null) {
1114 return $owner->getPathByInvestments($toCustomer, $path);
1115 }
1116
1117 }
1118
1119
1120 public function getCustomersPortfolioAmount($productID = null) {
1121
1122 $portfolioAmount = new \stdClass();
1123
1124 $customerRepository = New CustomerRepository;
1125 $structIDs = $customerRepository->getStructureIDs($this->getCustomerID());
1126
1127 $query = Investment::select(DB::Raw('SUM(CASE WHEN (investment.owner_ID = ' . $this->customer_ID . ' AND customer.type = "CUSTOMER") OR (investment.customer_ID = ' . $this->customer_ID . ') THEN present_amount ELSE 0 END) as ownAmount'));
1128 $query->addSelect(DB::Raw('SUM(CASE WHEN (' . (count($structIDs) ? 'investment.owner_ID IN(' . implode(',', $structIDs) . ')' : '0 = 1') . ' AND customer.type = "CUSTOMER") THEN present_amount ELSE 0 END) as structAmount'));
1129 $query->whereHas('product', function ($q) use ($productID) {
1130
1131 if (is_array($productID)) {
1132 $q->whereIn('product_ID', $productID);
1133 } else {
1134 $q->where('product_ID', $productID);
1135 }
1136
1137 $q->where(function ($q2) {
1138 $q2->where(function ($q3) {
1139 $q3->whereNull('investment_move.end_date')
1140 ->orWhere('investment_move.end_date', '>=', DB::Raw('NOW()'));
1141 })
1142 // ->whereNull('investment_move.deleted_at')
1143 ->whereNotNull('investment_move.start_date')
1144 ->where('investment_move.start_date', '<=', DB::Raw('NOW()'));
1145 });
1146
1147 });
1148
1149 $query->join('investment_move', function ($join) {
1150 $join->on('investment_move.investment_ID', '=', 'investment.investment_ID');
1151 });
1152
1153 // add join with customer table and filter by active
1154 $query->join('customer', function ($join) {
1155 $join->on('customer.customer_ID', '=', 'investment.customer_ID')
1156 ->where('customer.active', '=', '1');
1157 });
1158
1159 $query->where(function ($qMain) use ($structIDs) {
1160 $qMain->where(function ($q) use ($structIDs) {
1161 $q->where(function ($q2) use ($structIDs) {
1162 $q2->whereIn('investment.owner_ID', $structIDs)
1163 ->where('customer.type', '=', 'CUSTOMER');
1164 })->orWhere(function ($q2) {
1165 $q2->where('investment.owner_ID', '=', $this->customer_ID)
1166 ->where('customer.type', '=', 'CUSTOMER');
1167 });
1168 });
1169 });
1170
1171
1172
1173 $result = $query->get();
1174 $portfolioAmount->own = $result->first()->ownAmount;
1175 $portfolioAmount->struct = $result->first()->structAmount;
1176 $portfolioAmount->total = $portfolioAmount->own + $portfolioAmount->struct;
1177
1178 return $portfolioAmount;
1179 }
1180
1181 public function getCustomersDatePortfolioAmount($productID = null, $date = null) {
1182
1183 // check if exists cached data
1184 if ($productID == null) {
1185 $cacheProductID = 'null';
1186 } else {
1187 $cacheProductID = is_array($productID) ? implode('-', $productID) : $productID;
1188 }
1189
1190 if ($date == null) {
1191 $cacheDate = 'null';
1192 } else {
1193 $cacheDate = $date;
1194 }
1195
1196 $cacheName = 'getCustomersDatePortfolioAmount-' . $cacheProductID . ' - ' . $cacheDate;
1197 if (!isset($this->cache[$cacheName])) {
1198
1199 $portfolioAmount = new \stdClass();
1200
1201 $customerRepository = New CustomerRepository;
1202 $structIDs = $customerRepository->getStructureIDs($this->getCustomerID());
1203 $investmentRepository = new \App\Repositories\InvestmentRepository;
1204 $investmentMoveRepository = new \App\Repositories\InvestmentMoveRepository;
1205 $productMoveRepository = new \App\Repositories\ProductMoveRepository;
1206 $investmentCalculateAmountService = new \App\Services\InvestmentCalculateAmountService($investmentRepository, $investmentMoveRepository, $productMoveRepository);
1207
1208 $query = Investment::whereHas('product', function ($q) use ($productID, $date) {
1209
1210 if (is_array($productID)) {
1211 $q->whereIn('product_ID', $productID);
1212 } elseif($productID != null) {
1213 $q->where('product_ID', $productID);
1214 } else {
1215 $q->where('product_ID','!=','7'); // not cloud mining
1216 }
1217
1218 if($date == null) {
1219 $q->where(function ($q2) {
1220 $q2->where(function ($q3) {
1221 $q3->whereNull('investment_move.end_date')
1222 ->orWhere('investment_move.end_date', '>=', DB::Raw('NOW()'));
1223 })
1224 // ->whereNull('investment_move.deleted_at')
1225 ->whereNotNull('investment_move.start_date')
1226 ->where('investment_move.start_date', '<=', DB::Raw('NOW()'));
1227 // aktivní investice
1228 });
1229 } else {
1230 $q->where(function ($q2) use($date) {
1231 $q2->where(function ($q3) use($date) {
1232 $q3->whereNull('investment_move.end_date')
1233 ->orWhere(DB::Raw('DATE(investment_move.end_date)'), '>=', DB::Raw('DATE("'.$date.'")'));
1234 })
1235 // ->whereNull('investment_move.deleted_at')
1236 ->whereNotNull('investment_move.start_date')
1237 ->where(DB::Raw('DATE(investment_move.start_date)'), '<=', DB::Raw('DATE("'.$date.'")'));
1238 });
1239 }
1240
1241 });
1242
1243 $query->join('investment_move', function ($join) {
1244 $join->on('investment_move.investment_ID', '=', 'investment.investment_ID');
1245 });
1246
1247 // add join with customer table and filter by active
1248 $query->join('customer', function ($join) {
1249 $join->on('customer.customer_ID', '=', 'investment.customer_ID')
1250 ->where('customer.active', '=', '1');
1251 });
1252
1253 $query->where(function ($qMain) use ($structIDs) {
1254 $qMain->where(function ($q) use ($structIDs) {
1255 $q->where(function ($q2) use ($structIDs) {
1256 $q2->whereIn('investment.owner_ID', $structIDs)
1257 ->where('customer.type', '=', 'CUSTOMER');
1258 })->orWhere(function ($q2) {
1259 $q2->where('investment.owner_ID', '=', $this->customer_ID)
1260 ->where('customer.type', '=', 'CUSTOMER');
1261 });
1262 });
1263 });
1264
1265 $query->orderBy('customer.surname','ASC');
1266
1267 $result = $query->get();
1268 $portfolioAmount->own = 0;
1269 $portfolioAmount->struct = 0;
1270
1271 foreach ($result as $resultInvestment) {
1272 if ($resultInvestment->owner_ID == $this->getOwnerID() && $resultInvestment->customer->type == $this->getType()) {
1273 $value = $investmentCalculateAmountService->process($resultInvestment, $date);
1274 $portfolioAmount->own += $value;
1275
1276
1277 } else {
1278 $portfolioAmount->struct += $investmentCalculateAmountService->process($resultInvestment, $date);
1279 }
1280
1281 }
1282
1283 $portfolioAmount->total = $portfolioAmount->own + $portfolioAmount->struct;
1284
1285 $this->cache[$cacheName] = $portfolioAmount;
1286
1287 }
1288
1289 return $this->cache[$cacheName];
1290 }
1291
1292 public function isActive() {
1293 if ($this->getActive() == 1) {
1294 return true;
1295 } else {
1296 return false;
1297 }
1298 }
1299
1300 public function get2FAState() {
1301 $gaSecret = $this->gaSecret()->whereNull('inactive_from')->first();
1302 if ($gaSecret == null) {
1303 return 0;
1304 } else {
1305 return 1;
1306 }
1307 }
1308}