Example #1
0
 public function makeSepa($reseller_id, $redo = false, $disposition = null)
 {
     $disposition = is_null($disposition) ? 'attachment' : $disposition;
     $reseller = Model::Reseller()->find((int) $reseller_id);
     if ($reseller) {
         $bi = Model::Inovibackend()->where(['reseller_id', '=', (int) $reseller_id])->first(true);
         if ($bi) {
             $infos = $bi->toArray();
             $url = isAke($infos, 'url_sepa', false);
             if (!$url || $redo) {
                 $tpl = File::read(APPLICATION_PATH . DS . 'templates/sepa.html');
                 $tpl = str_replace(['##ics##', '##rum##', '##inovi_id##', '##iban##', '##bic##', '##adresse##', '##code_postal##', '##ville##', '##banque##', '##ville_banque##', '##nom##', '##corporate##', '##pays##', '##ville_signature##', '##date_signature##'], ['zelift123456789', $infos['id'] . date('dmY'), $infos['id'], $infos['iban'], $infos['bic'], $infos['address'], $infos['zip'], $infos['city'], $infos['banque_nom'], $infos['banque_ville'], $infos['name'], $infos['corporate_name'], isAke($infos, 'country', 'France'), isAke($infos, 'ville_signature', isAke($infos, 'city')), date('d/m/Y', isAke($infos, 'start_adhesion', time()))], $tpl);
                 $bucket = new Bucket(SITE_NAME, 'http://zelift.com/bucket');
                 $pdf = pdfFile($tpl, 'Mandat-SEPA', 'portrait');
                 $url = $bucket->data($pdf, 'pdf');
                 $bi->url_sepa = $url;
                 if (!fnmatch('http://*', $url)) {
                     return ['url' => false, 'error' => $bi->url_sepa];
                 }
                 $bi->save();
             } else {
                 $pdf = file_get_contents($url);
             }
             if ($disposition == 'attachment') {
                 return ['url' => $url, 'error' => false];
             }
             header('Content-Type: application/pdf');
             header('Content-Length: ' . strlen($pdf));
             header('Content-Disposition: ' . $disposition . '; filename="Mandat-SEPA.pdf"');
             header('Cache-Control: private, max-age=0, must-revalidate');
             header('Pragma: public');
             ini_set('zlib.output_compression', '0');
             die($pdf);
         }
     }
     return ['url' => false, 'error' => 'Revendeur inconnu'];
 }
Example #2
0
 public function getResellersByMarket($market)
 {
     $collection = [];
     $relations = Model::Segmentreseller()->where(['market', '=', $market])->exec();
     foreach ($relations as $relation) {
         $resellerId = isAke($relation, 'reseller_id', false);
         if (false !== $resellerId) {
             $reseller = Model::Reseller()->find($resellerId);
             if ($reseller) {
                 array_push($collection, $reseller->assoc());
             }
         }
     }
     return $this->unTuple($collection);
 }
Example #3
0
 public function consolidate($reseller_id = null)
 {
     $q = Model::Product();
     if (!is_null($reseller_id)) {
         $q->where(['reseller_id', '=', (int) $reseller_id]);
     }
     $products = $q->cursor();
     foreach ($products as $product) {
         if (isset($product['reseller_id']) && isset($product['segment_id']) && isset($product['sellzone_id'])) {
             $row = Model::Productdata()->firstOrCreate(['reseller_id' => (int) $product['reseller_id'], 'segment_id' => (int) $product['segment_id'], 'sellzone_id' => (int) $product['sellzone_id']]);
             unset($product['_id']);
             $row->product = $product;
             $family = repo('segment')->getFamilyfromItem((int) $product['segment_id']);
             if (!empty($family)) {
                 $market = current($family);
                 $market_id = (int) $market['id'];
             } else {
                 $market_id = $segment_id;
             }
             $company = Model::Company()->where(['reseller_id', '=', (int) $product['reseller_id']])->first(false);
             $reseller = Model::Reseller()->find((int) $product['reseller_id'], false);
             $segment = Model::Segment()->find((int) $product['segment_id'], false);
             $location = lib('utils')->remember('has.locations.companies.' . $product['reseller_id'], function ($reseller_id) {
                 $company = Model::Company()->where(['reseller_id', '=', (int) $reseller_id])->first(true);
                 if ($company) {
                     $coords = lib('geo')->getCoordsMap($company->address . ' ' . $company->zip . ' ' . $company->city);
                     $loc = ['lng' => $coords['lng'], 'lat' => $coords['lat']];
                 }
                 return $loc;
             }, Model::Company()->getAge(), [$product['reseller_id']]);
             $status = (int) lib('status')->getId('reseller', 'REGISTER') == $reseller['status_id'];
             $row->company = $company;
             $row->segment = $segment;
             $row->status = $status;
             $row->location = $location;
             $row->reseller = $reseller;
             $options = [];
             $resellerObj = Model::Reseller()->model($reseller);
             $hasAgenda = lib('option')->get('agenda.partage', $resellerObj, false);
             $distanceMaxReseller = (double) lib('option')->get('zone.intervention.' . $market_id, $resellerObj, 0);
             $delai_presta = lib('option')->get('delai.intervention.' . $market_id, $resellerObj, 0);
             $minAmount = lib('option')->get('montant.intervention.' . $market_id, $resellerObj, 0);
             $options['has_agenda'] = $hasAgenda;
             $options['distance_max'] = $distanceMaxReseller;
             $options['delai_min'] = $delai_presta;
             $options['amount_min'] = $minAmount;
             $options['languages'] = [];
             $languages = ['anglais', 'espagnol', 'allemand', 'italien', 'néerlandais', 'portugais', 'russe', 'japonais', 'chinois'];
             foreach ($languages as $language) {
                 $speak = lib('option')->get('langue.' . $market_id . '.' . $language, $resellerObj, false);
                 $options['languages'][$language] = $speak;
             }
             $row->options = $options;
             $row->save();
         }
     }
 }
Example #4
0
 public function firstMyZelift($reseller_id, $disposition = null)
 {
     $bucket = new Bucket(SITE_NAME, 'http://zelift.com/bucket');
     $disposition = is_null($disposition) ? 'attachment' : $disposition;
     $reseller = Model::Reseller()->find((int) $reseller_id);
     if ($reseller) {
         $zid = $reseller->zechallenge_id;
         $myzelift = Model::Myzelift()->where(['zechallenge_id', '=', (int) $zid])->first(true);
         if ($myzelift) {
             $contract = Model::FacturationContrat()->where(['zechallenge_id', '=', (int) $zid])->where(['platform', '=', 'MyZeLift'])->first(true);
             if (!$contract) {
                 exception("facture", 'Aucun contrat zechallenge trouvé.');
             }
             $products = lib('facturation')->abonnementMyzelift(lib('zechallenge')->getContext($reseller->id));
             $toBilled = $acomptes = $hasAcomptes = $purchases = [];
             foreach ($products as $product) {
                 $haveTobeBilled = Model::FacturationAcompte()->where(['status', '=', 'UNBILLED'])->where(['product_id', '=', (int) $product['id']])->where(['zechallenge_id', '=', (int) $zid])->with('product');
                 foreach ($haveTobeBilled as $hasToBilled) {
                     $purchases[] = $hasToBilled;
                     $acomptes[] = $hasToBilled;
                     $hasAcomptes[$hasToBilled['product_id']] = true;
                 }
                 $haveTobeBilled = Model::FacturationPurchase()->where(['status', '=', 'UNBILLED'])->where(['product_id', '=', (int) $product['id']])->where(['zechallenge_id', '=', (int) $zid])->with('product');
                 foreach ($haveTobeBilled as $hasToBilled) {
                     if (!isset($hasAcomptes[$hasToBilled['product_id']])) {
                         $purchases[] = $toBilled[] = $hasToBilled;
                     }
                 }
             }
             // dd($toBilled);
             $total = 0;
             $details = [];
             foreach ($toBilled as $hastoBilled) {
                 $sum = $hastoBilled['quantity'] * $hastoBilled['product']['amount'];
                 $total += $sum;
                 $details[] = '<tr style="border:1px solid #a4a4a4;border-top:none;">
                 <td style="width:500px;">
                     <div style="width:500px; text-indent:30px; height:25px; line-height:25px;">
                         ' . $hastoBilled['product']['name'] . '
                     </div>
                 </td>
                 <td style="width:300px; font-size:0; padding:0;">
                     <div style="width:75px; display:inline-block; font-size:15px; text-align:center;">' . number_format($hastoBilled['product']['amount'], 2) . '€</div>
                     <div style="width:75px; display:inline-block; font-size:15px; text-align:center;">' . $hastoBilled['quantity'] . '</div>
                     <div style="width:75px; display:inline-block; font-size:15px; text-align:center;"></div>
                     <div style="width:75px; display:inline-block; font-size:15px; text-align:center;">
                         ' . number_format($sum, 2) . '€
                     </div>
                 </td>
             </tr>';
             }
             foreach ($acomptes as $hastoBilled) {
                 $sum = $hastoBilled['quantity'] * $hastoBilled['amount'];
                 $total += $sum;
                 $normalPrice = $hastoBilled['product']['amount'] * $hastoBilled['quantity'];
                 $pc = $sum / $normalPrice * 100;
                 $details[] = '<tr style="border:1px solid #a4a4a4;border-top:none;">
                 <td style="width:500px;">
                     <div style="width:500px; text-indent:30px; height:25px; line-height:25px;">
                         ' . $hastoBilled['product']['name'] . ' (Acompte de ' . $pc . ' %)
                     </div>
                 </td>
                 <td style="width:300px; font-size:0; padding:0;">
                     <div style="width:75px; display:inline-block; font-size:15px; text-align:center;">' . number_format($hastoBilled['amount'], 2) . '€</div>
                     <div style="width:75px; display:inline-block; font-size:15px; text-align:center;">' . $hastoBilled['quantity'] . '</div>
                     <div style="width:75px; display:inline-block; font-size:15px; text-align:center;"></div>
                     <div style="width:75px; display:inline-block; font-size:15px; text-align:center;">
                         ' . number_format($sum, 2) . '€
                     </div>
                 </td>
             </tr>';
             }
             $facture = Model::FacturationFacture()->refresh()->firstOrCreate(['zechallenge_id' => $zid, 'products' => $purchases]);
             $tva = number_format(round($total * 0.2, 2), 2);
             $ttc = number_format($total + $tva, 2);
             $details = implode("\n", $details);
             $tpl = File::read(APPLICATION_PATH . DS . 'templates/premiere_facture_zechallenge.html');
             $ib = Model::Inovibackend()->find((int) $reseller->inovibackend_id);
             $tpl = str_replace(['##typoColor##', '##typo##', '##no_facture##', '##compte_inovi##', '##no_contrat##', '##univers##', '##affil##', '##nom_client##', '##adresse_client##', '##cp_client##', '##ville_client##', '##lieu_contrat##', '##date_contrat##', '##date_debut##', '##date_fin##', '##date_jour##', '##total##', '##total_tva##', '##total_ttc##', '##details##'], ['#ba68c8', 'MyZeLift', $facture->id, $reseller->inovibackend_id, $zid, lib('zechallenge')->getMarket($reseller->id), lib('segment')->getAffiliation($reseller->id, false), $ib->name, $ib->address, $ib->zip, $ib->city, $ib->city, date('d/m/Y', $contract->contract_date), date('d/m/Y', $contract->contract_date), date('d/m/Y', $contract->end), date('d/m/Y'), number_format($total, 2), $tva, $ttc, $details], $tpl);
             $pdf = pdfFile($tpl, 'Facture-MyZeLift', 'portrait');
             $url = $bucket->data($pdf, 'pdf');
             if (!fnmatch('http://*', $url)) {
                 return ['url' => false, 'error' => $url];
             }
             if ($disposition == 'attachment') {
                 return ['url' => $url, 'error' => false];
             }
             header('Content-Type: application/pdf');
             header('Content-Length: ' . strlen($pdf));
             header('Content-Disposition: ' . $disposition . '; filename="Contrat-MyZeLift.pdf"');
             header('Cache-Control: private, max-age=0, must-revalidate');
             header('Pragma: public');
             ini_set('zlib.output_compression', '0');
             die($pdf);
         }
     }
 }
Example #5
0
 private function listBetween($offerIn, $model, $is_calendar = true)
 {
     $now = time();
     $collection = lib('collection');
     $quantity = $offerIn->quantity;
     $options = $offerIn->options;
     $language = $offerIn->language;
     $distance_maxB = $offerIn->distance_max;
     $start = $offerIn->start;
     $tolerance = $offerIn->tolerance;
     $oresellerid = $offerIn->reseller_id;
     $segment_id = $offerIn->segment_id;
     $start = is_null($start) ? $now + 4 * 3600 : $start;
     $tolerance = is_null($tolerance) ? 0 : $tolerance;
     $distance_maxB = is_null($distance_maxB) ? 0 : (double) $distance_maxB;
     $delai = $start - $now;
     $livraison = false;
     if (isset($options['shipping_costs'])) {
         if (isset($options['shipping_costs']['default'])) {
             $livraison = 'oui' == $options['shipping_costs']['default'] ? true : false;
         }
     }
     if ($delai <= 0) {
         return [];
     }
     $delai /= 3600;
     $list = Arrays::get($model, 'formulaire_achat.elements.quantity.values', []);
     $unite = Arrays::get($model, 'formulaire_achat.elements.quantity.unite', 'heure');
     $optionsPrice = Arrays::get($model, 'formulaire_achat.elements.quantity.options.price', []);
     $optionsDiscount = Arrays::get($model, 'formulaire_achat.elements.quantity.options.discount', []);
     $optionsFixedCosts = Arrays::get($model, 'formulaire_achat.elements.quantity.options.fixed_costs', []);
     $optionsTravelCosts = Arrays::get($model, 'formulaire_achat.elements.quantity.options.travel_costs', []);
     $optionsShippingCosts = Arrays::get($model, 'formulaire_achat.elements.quantity.options.shipping_costs', []);
     $locOfferIn = getLocation($offerIn);
     $queryproducts = Model::Product()->where(['segment_id', '=', $segment_id])->where(['sellzone_id', '=', $offerIn->sellzone_id]);
     if (!is_null($oresellerid)) {
         $queryproducts->where(['reseller_id', '=', (int) $oresellerid]);
     }
     $products = $queryproducts->exec(true);
     foreach ($products as $product) {
         $price = $product->price;
         $fixed_costs = $product->fixed_costs;
         $shipping_costs = $product->shipping_costs;
         $travel_costs = $product->travel_costs;
         $discount = $product->discount;
         $delai_presta = lib('option')->get('delai.intervention', $product, false);
         $montant_min = (double) lib('option')->get('montant.intervention', $product, 0);
         $distance_max = (double) lib('option')->get('zone.intervention', $product, 0);
         if (false !== $delai_presta) {
             if ($delai < $delai_presta) {
                 continue;
             }
         }
         $fixed_costs_free_from_price = 0;
         if (is_null($fixed_costs) || !is_array($fixed_costs)) {
             $fixed_costs = 0;
         } else {
             if (isset($fixed_costs['default'])) {
                 if (isset($fixed_costs['default']['value'])) {
                     $fixed_costs = (double) $fixed_costs['default']['value'];
                 }
                 if (isset($fixed_costs['default']['free_from_price'])) {
                     $fixed_costs_free_from_price = (double) $fixed_costs['default']['free_from_price'];
                 }
             } else {
                 $fixed_costs = 0;
             }
         }
         $travel_costs_free_from_price = 0;
         if (is_null($travel_costs) || !is_array($travel_costs)) {
             $travel_costs = 0;
         } else {
             if (isset($travel_costs['default'])) {
                 if (isset($travel_costs['default']['value'])) {
                     $travel_costs = (double) $travel_costs['default']['value'];
                 }
                 if (isset($travel_costs['default']['free_from_price'])) {
                     $travel_costs_free_from_price = (double) $travel_costs['default']['free_from_price'];
                 }
             } else {
                 $travel_costs = 0;
             }
         }
         if (true === $livraison) {
             $shipping_costs_free_from_price = 0;
             if (is_null($shipping_costs) || !is_array($shipping_costs)) {
                 $shipping_costs = 0;
             } else {
                 if (isset($shipping_costs['default'])) {
                     if (isset($shipping_costs['default']['value'])) {
                         $shipping_costs = (double) $shipping_costs['default']['value'];
                     }
                     if (isset($shipping_costs['default']['free_from_price'])) {
                         $shipping_costs_free_from_price = (double) $shipping_costs['default']['free_from_price'];
                     }
                 } else {
                     $shipping_costs = 0;
                 }
             }
         }
         if (!is_null($discount)) {
             $discount_quantity = 0;
             $discount_amount = 0;
             if (isset($discount['default'])) {
                 if (isset($discount['default']['quantity'])) {
                     $discount_quantity = (double) $discount['default']['quantity'];
                 }
                 if (isset($discount['default']['amount'])) {
                     $discount_amount = (double) $discount['default']['amount'];
                 }
             }
         } else {
             $discount_quantity = 0;
             $discount_amount = 0;
         }
         $reseller = Model::Reseller()->find($product->reseller_id);
         if ($reseller) {
             $min = isAke($quantity, 'min', false);
             $max = isAke($quantity, 'max', false);
             if (false === $min || false === $max) {
                 return [];
             }
             foreach ($price as $productIndex => $productInfos) {
                 $cost = isAke($productInfos, 'cost', false);
                 if ($unite == 'minute') {
                     $duration = isAke($productInfos, 'duration', false);
                     if (false === $duration || false === $cost) {
                         continue;
                     }
                     $min = (int) $min;
                     $max = (int) $max;
                     $duration = (int) $duration;
                     $cost = (double) $cost;
                     $checkContinue = $duration >= $min && $duration <= $max;
                 } else {
                     $cost = (double) $cost;
                     $min = (double) $min;
                     $max = (double) $max;
                     $checkContinue = $cost >= $min && $cost <= $max;
                 }
                 if ($checkContinue) {
                     $item = [];
                     $amount = $cost;
                     $amount = (double) $amount;
                     if (true == $livraison && $shipping_costs > 0 && $shipping_costs_free_from_price > 0) {
                         if ($shipping_costs_free_from_price <= $amount) {
                             $shipping_costs = 0;
                         }
                     }
                     if (true === $livraison) {
                         $item['shipping_costs'] = $shipping_costs;
                     }
                     if ($travel_costs > 0 && $travel_costs_free_from_price > 0) {
                         if ($travel_costs_free_from_price <= $amount) {
                             $travel_costs = 0;
                         }
                     }
                     if ($fixed_costs > 0 && $fixed_costs_free_from_price > 0) {
                         if ($fixed_costs_free_from_price <= $amount) {
                             $fixed_costs = 0;
                         }
                     }
                     /* on calcule la ristourne sur la quantité si elle existe */
                     $everDiscount = false;
                     if ($quantity >= $discount_quantity && 0 < $discount_amount) {
                         $discountAmount = (double) ($amount * $discount_amount) / 100;
                         $amount = (double) $amount - $discountAmount;
                         $everDiscount = true;
                     }
                     /* si pas de ristourne quantité on regarde s'il ya une ristourne de prix */
                     if (!is_null($discount) && is_array($discount)) {
                         $discountPrice = isAke($discount, 'price', false);
                         if (false !== $discountPrice) {
                             $discount_quantity = 0;
                             $discount_amount = 0;
                             if (isset($discountPrice['quantity'])) {
                                 $discount_quantity = (double) $discountPrice['quantity'];
                             }
                             if (isset($discountPrice['amount'])) {
                                 $discount_amount = (double) $discountPrice['amount'];
                             }
                             if ($amount >= $discount_quantity && 0 < $discount_amount) {
                                 $discountAmount = (double) ($amount * $discount_amount) / 100;
                                 $amount = (double) $amount - $discountAmount;
                                 $everDiscount = true;
                             }
                         }
                     }
                     /* on peut ajouter les frais fixes et de livraison */
                     $amount = $amount + $fixed_costs + $shipping_costs;
                     $discountAmount = 0;
                     $hasAgenda = lib('option')->get('agenda.partage.' . $segment_id, $reseller, false);
                     /* on regarde si le revendeur a spécifié un montant minumum pour accepter une presta */
                     if (0 == $montant_min) {
                         $montant_min = (double) lib('option')->get('montant.intervention.' . $segment_id, $reseller, 0);
                     }
                     /* si tel est le cas on s'assure que le montant minimum est atteint */
                     if (0 < $montant_min) {
                         if ($amount < $montant_min) {
                             continue;
                         }
                     }
                     /* on regarde si le revendeur a spécifié un délai minumum pour accepter une presta */
                     if (false === $delai_presta) {
                         $delai_presta = lib('option')->get('delai.intervention.' . $segment_id, $reseller, false);
                         /* si tel est le cas on s'assure que le délai minimum est respecté */
                         if (false !== $delai_presta) {
                             if ($delai < $delai_presta) {
                                 continue;
                             }
                         }
                     }
                     /* si une langue est demandée on vérifie si le revendeur la parle, sinon, on passe au suivant */
                     if (!is_null($language)) {
                         $speak = lib('option')->get('langue.' . $segment_id . '.' . $language, $reseller, false);
                         if (false === $speak) {
                             continue;
                         }
                     }
                     if (o == $distance_max) {
                         $distance_max = lib('option')->get('zone.intervention.' . $segment_id, $reseller, 0);
                     }
                     $locReseller = getLocation($reseller);
                     $distance = distanceKmMiles($locOfferIn['lng'], $locOfferIn['lat'], $locReseller['lng'], $locReseller['lat']);
                     $km = (double) $distance['km'];
                     /* si la distance maximale demandée par l'acheteur est supérieure à la distance calculée
                           on ne prend pas cette offre
                        */
                     if ($distance_maxB > 0) {
                         if ($km > $distance_maxB) {
                             continue;
                         }
                     }
                     /* si la distance maximale demandée par le vendeur est supérieure à la distance calculée
                           on ne prend pas cette offre
                        */
                     if ($distance_max > 0) {
                         if ($km > $distance_max) {
                             continue;
                         }
                     }
                     /* on ajoute les frais de déplacement le cas échéant */
                     if (0 < $travel_costs) {
                         $travel_costs = (double) $travel_costs * $km;
                         $amount += $travel_costs;
                     }
                     $item['quantity'] = $quantity;
                     $item['amount'] = $amount;
                     $item['discount'] = $discountAmount;
                     $item['fixed_costs'] = $fixed_costs;
                     $item['travel_costs'] = $travel_costs;
                     $item['distance'] = $km;
                     $item['reseller_id'] = $reseller->id;
                     /* si c'est une presta calendrier et que le revendeur n'a pas de calendrier, on ajoute un attribut à l'item */
                     if (true === $is_calendar && false === $hasAgenda) {
                         $item['reseller_calendar'] = false;
                     }
                     if (true === $is_calendar && false !== $hasAgenda) {
                         $item['reseller_calendar'] = true;
                         $duration = $this->duration($quantity, $unite, $offerIn->segment_id, $reseller->id);
                         $startMin = (int) $start - $tolerance;
                         $startMax = (int) $start + $tolerance;
                         $endMin = (int) $startMin + $duration;
                         $endMax = (int) $startMax + $duration;
                         $availabilities = lib('agenda')->getAvailabilitiesByResellerId($startMin, $endMax, $reseller->id);
                         if (!empty($availabilities)) {
                             if (!is_null($language)) {
                                 $find = false;
                                 foreach ($availabilities as $availability) {
                                     $employee = Model::Reselleremployee()->find($availability['reselleremployee_id']);
                                     if ($employee) {
                                         $speak = lib('option')->get('langue.' . $language, $employee, false);
                                         if (false !== $speak) {
                                             $item['availability_id'] = $availability['id'];
                                             $item['availability_start'] = $availability['start'];
                                             $item['availability_end'] = $availability['end'];
                                             $item['reselleremployee_id'] = $availability['reselleremployee_id'];
                                             $find = true;
                                             break;
                                         }
                                     }
                                 }
                                 if (false === $find) {
                                     continue;
                                 }
                             } else {
                                 $availability = Arrays::first($availabilities);
                                 $item['availability_id'] = $availability['id'];
                                 $item['availability_start'] = $availability['start'];
                                 $item['availability_end'] = $availability['end'];
                                 $item['reselleremployee_id'] = $availability['reselleremployee_id'];
                             }
                         } else {
                             /* si pas de dispo on passe */
                             continue;
                         }
                     }
                     /* on peut créer l'offre out et ajouter l'offre au retour */
                     $data = $item;
                     $data['offerin_id'] = $offerIn->id;
                     $data['account_id'] = $offerIn->account_id;
                     $data['segment_id'] = $segment_id;
                     $data['status_id'] = (int) lib('status')->getId('offerout', 'SHOWN');
                     $offerOut = Model::Offerout()->create($data)->save();
                     $item['offerout_id'] = $offerOut->id;
                     $collection[] = $item;
                 }
             }
         }
     }
     /* on ordonne les offres par distance décroissante si à domicile sinon par prix */
     if ($collection->count() > 0) {
         if ($livraison) {
             $collection->sortBy('distance');
         } else {
             $collection->sortBy('amount');
         }
     }
     return $collection->toArray();
 }
Example #6
0
 public function getOptionsMacroData($segment_id)
 {
     $user = session('user')->getUser();
     $segment = Model::Segment()->find((int) $segment_id);
     if ($segment) {
         if (Inflector::lower($segment->name) == 'restaurant') {
             return $this->getOptionsMacroDataResto($segment, $user);
         }
     }
     if ($user) {
         if (Arrays::is($user)) {
             if (!is_integer($segment_id)) {
                 return [];
             }
             if (!isset($user['employee'])) {
                 return false;
             }
             if (!isset($user['settings'])) {
                 return false;
             }
             if (!isset($user['settings']['employee_index'])) {
                 return false;
             }
             if (!isset($user['employee'][$user['settings']['employee_index']])) {
                 return false;
             }
             // if (!isset($user['employee'][$user['settings']['employee_index']]['id'])) {
             //     return false;
             // }
             if (!isset($user['employee'][$user['settings']['employee_index']]['reseller_id'])) {
                 return false;
             }
             // $reselleremployee_id    = $user['employee'][$user['settings']['employee_index']]['id'];
             $reseller_id = $user['employee'][$user['settings']['employee_index']]['reseller_id'];
             $reseller = Model::Reseller()->find((int) $reseller_id);
             // $reselleremployee = Model::Reselleremployee()->find((int) $reselleremployee_id);
             if ($reseller) {
                 // if ($reseller && $reselleremployee) {
                 if (is_integer($segment_id)) {
                     if ($segment) {
                         $form = $this->getOptionsFromMarket((int) $segment_id);
                         $returnForm = [];
                         if (!empty($form)) {
                             if (isset($form['offres_devis'])) {
                                 $offres_devis = lib('option')->get('offres.devis.' . $segment_id, $reseller, 1);
                                 if (is_bool($offres_devis)) {
                                     $offres_devis = true === $offres_devis ? 1 : 0;
                                 } elseif (empty($offres_devis)) {
                                     $offres_devis = 0;
                                 }
                                 $returnForm['offres_devis'] = $offres_devis;
                             }
                             if (isset($form['agenda_partage'])) {
                                 $agenda_partage = lib('option')->get('agenda.partage.' . $segment_id, $reseller, 1);
                                 if (is_bool($agenda_partage)) {
                                     $agenda_partage = true === $agenda_partage ? 1 : 0;
                                 } elseif (empty($agenda_partage)) {
                                     $agenda_partage = 0;
                                 }
                                 $returnForm['agenda_partage'] = $agenda_partage;
                             }
                             if (isset($form['delai_intervention'])) {
                                 $delai_intervention = lib('option')->get('delai.intervention.' . $segment_id, $reseller, 0);
                                 $returnForm['delai_intervention'] = $delai_intervention;
                             }
                             if (isset($form['montant_intervention'])) {
                                 $montant_intervention = lib('option')->get('montant.intervention.' . $segment_id, $reseller, 0);
                                 $returnForm['montant_intervention'] = $montant_intervention;
                             }
                             if (isset($form['zone_intervention'])) {
                                 $zone_intervention = lib('option')->get('zone.intervention.' . $segment_id, $reseller, 0);
                                 $returnForm['zone_intervention'] = $zone_intervention;
                             }
                             if (isset($form['langue'])) {
                                 if (isset($form['langue']['values'])) {
                                     $langues = Arrays::get($form, 'langue.values', []);
                                     foreach ($langues as $ind => $key) {
                                         $val = lib('option')->get('langue.' . $segment_id . '.' . $key, $reseller, false);
                                         if (is_bool($val)) {
                                             $val = true === $val ? 1 : 0;
                                         } elseif (empty($val)) {
                                             $val = 0;
                                         }
                                         $returnForm['langue_' . $ind] = $val;
                                     }
                                 }
                             }
                             if (isset($form['agenda_horaires'])) {
                                 $days = ['lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche'];
                                 foreach ($days as $day) {
                                     $index_am_start = str_replace('##day##', $day, 'agenda_horaires_##day##_am_start');
                                     $index_am_end = str_replace('##day##', $day, 'agenda_horaires_##day##_am_end');
                                     $index_pm_start = str_replace('##day##', $day, 'agenda_horaires_##day##_pm_start');
                                     $index_pm_end = str_replace('##day##', $day, 'agenda_horaires_##day##_pm_end');
                                     $schedule = Model::Schedule()->where(['day', '=', (string) $day])->where(['reseller_id', '=', (int) $reseller->id])->first(true);
                                     if ($schedule) {
                                         $am_start = $schedule->am_start;
                                         $am_end = $schedule->am_end;
                                         $pm_start = $schedule->pm_start;
                                         $pm_end = $schedule->pm_end;
                                         if ($am_start) {
                                             if ('ferme' == $am_start) {
                                                 $returnForm[$index_am_start] = '';
                                             } else {
                                                 $returnForm[$index_am_start] = str_replace('_', ':', $am_start);
                                             }
                                         } else {
                                             $returnForm[$index_am_start] = '';
                                         }
                                         if ($am_end) {
                                             if ('ferme' == $am_end) {
                                                 $returnForm[$index_am_end] = '';
                                             } else {
                                                 $returnForm[$index_am_end] = str_replace('_', ':', $am_end);
                                             }
                                         } else {
                                             $returnForm[$index_am_end] = '';
                                         }
                                         if ($pm_start) {
                                             if ('ferme' == $pm_start) {
                                                 $returnForm[$index_pm_start] = '';
                                             } else {
                                                 $returnForm[$index_pm_start] = str_replace('_', ':', $pm_start);
                                             }
                                         } else {
                                             $returnForm[$index_pm_start] = '';
                                         }
                                         if ($pm_end) {
                                             if ('ferme' == $pm_end) {
                                                 $returnForm[$index_pm_end] = '';
                                             } else {
                                                 $returnForm[$index_pm_end] = str_replace('_', ':', str_replace('23_59', '00_00', $pm_end));
                                             }
                                         } else {
                                             $returnForm[$index_pm_end] = '';
                                         }
                                     } else {
                                         if ($day == 'dimanche' || $day == 'samedi') {
                                             $returnForm[$index_am_start] = '';
                                             $returnForm[$index_am_end] = '';
                                             $returnForm[$index_pm_start] = '';
                                             $returnForm[$index_pm_end] = '';
                                         } else {
                                             $returnForm[$index_am_start] = '8:00';
                                             $returnForm[$index_am_end] = '12:00';
                                             $returnForm[$index_pm_start] = '14:00';
                                             $returnForm[$index_pm_end] = '18:00';
                                         }
                                     }
                                 }
                             }
                         }
                         return $returnForm;
                     }
                 }
             }
         }
     }
     return [];
 }
Example #7
0
 function consolidate($reseller_id = null)
 {
     Save::clean();
     // $szs = Model::Sellzone()->cursor();
     // foreach ($szs as $sz) {
     //     $coll = [];
     //     $zips = Model::Coveredcity()->where(['sellzone_id', '=', (int) $sz['id']])->cursor();
     //     foreach ($zips as $zip) {
     //         $cs = Model::City()->where(['zip', '=', (string) $zip['zip']])->cursor();
     //         foreach ($cs as $c) {
     //             $n      = str_replace(' ', '_', Inflector::unaccent(Inflector::lower($zip['name'])));
     //             $n2     = str_replace(' ', '_', Inflector::unaccent(Inflector::lower($c['name'])));
     //             if ($n == $n2) {
     //                 $coll[] = [
     //                     'insee' => $c['insee'],
     //                     'zip'   => $zip['zip'],
     //                     'name'  => $c['name'],
     //                 ];
     //             }
     //         }
     //     }
     //     $coll = array_values(array_unique($coll));
     //     redis()->set('insees.' . $sz['id'], serialize($coll));
     // }
     $plats = Model::Mealgeo()->cursor();
     $geos = [];
     foreach ($plats as $plat) {
         if (!isset($geos[$plat['resto_geo_id']])) {
             $geos[$plat['resto_geo_id']] = [];
         }
         $geos[$plat['resto_geo_id']][] = $plat['segment_id'];
     }
     foreach ($geos as $id => $tab) {
         redis()->set('geos.spes.' . $id, serialize($tab));
     }
     $ids = repo('segment')->getAllFamilyIds(1941);
     $names = [];
     $segs = Model::Segment()->where(['id', 'IN', implode(',', $ids)])->cursor();
     foreach ($segs as $seg) {
         $data = repo('segment')->getData((int) $seg['id']);
         $is_item = isAke($data, 'is_item', false);
         if (false !== $is_item) {
             $names[] = $seg['name'];
         }
     }
     asort($names);
     redis()->set('sucres', serialize(array_values($names)));
     $suggestIds = [];
     $segments = Model::Segment()->reset()->where(['segmenttype_id', '=', 9])->cursor();
     $collection = [];
     foreach ($segments as $segment) {
         $data = repo('segment')->getData((int) $segment['id']);
         $ordre = isAke($data, 'ordre', 1);
         $segment['ordre'] = $ordre;
         $collection[] = $segment;
     }
     $collection = lib('collection', [$collection]);
     $collection->sortBy('ordre');
     $segments = $collection->toArray();
     foreach ($segments as $segment) {
         $data = repo('segment')->getData((int) $segment['id']);
         $segmentsItem = isAke($data, 'segments', false);
         if (false !== $segmentsItem) {
             $tab = explode(',', $segmentsItem);
             $item = [];
             $item['segments'] = [];
             $item['plats'] = [];
             foreach ($tab as $itId) {
                 $seg = Model::Segment()->find($itId);
                 if ($seg) {
                     if (!in_array($itId, $suggestIds)) {
                         $suggestIds[] = $itId;
                     }
                     $s = [];
                     $s['id'] = (int) $itId;
                     $s['name'] = $seg->name;
                     unset($s['created_at']);
                     unset($s['updated_at']);
                     $type = Model::segmenttype()->find($seg->segmenttype_id);
                     if ($type) {
                         $s['type'] = $type->name;
                     }
                     if (fnmatch('*non*', $type->name)) {
                         $plats = Model::Mealnonauto()->where(['resto_nonauto_id', '=', (int) $itId])->cursor();
                         foreach ($plats as $plat) {
                             $cat = Model::Catalog()->find((int) $plat['catalog_id']);
                             if ($cat) {
                                 $item['plats'][] = $cat->segment_id . '::' . $cat->reseller_id;
                             }
                         }
                     }
                     if (fnmatch('*_type*', $type->name)) {
                         $plats = Model::Mealtype()->where(['resto_type_id', '=', (int) $itId])->cursor();
                         foreach ($plats as $plat) {
                             $item['plats'][] = $plat['segment_id'];
                         }
                     }
                     if (fnmatch('*geo*', $type->name)) {
                         $plats = Model::Mealgeo()->where(['resto_geo_id', '=', (int) $itId])->cursor();
                         foreach ($plats as $plat) {
                             $item['plats'][] = $plat['segment_id'];
                         }
                     }
                 }
                 $item['segments'][] = $s;
             }
             $row = Model::Suggestion()->firstOrCreate(['segment_id' => (int) $segment['id']])->setName($segment['name'])->setSegments($item['segments'])->setPlats($item['plats'])->save();
         }
     }
     $days = ['lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche'];
     $when = ['am_start', 'am_end', 'pm_start', 'pm_end'];
     $q = Model::Optionsrestaurant();
     if (!is_null($reseller_id)) {
         $q->where(['reseller_id', '=', (int) $reseller_id]);
     }
     $restos = $q->cursor();
     foreach ($restos as $resto) {
         $schedules = [];
         $schedules['sur_place'] = [];
         $schedules['a_emporter'] = [];
         $schedules['en_livraison'] = [];
         $row = Model::Restodata()->firstOrCreate(['reseller_id' => (int) $resto['reseller_id'], 'sellzone_id' => (int) $resto['sellzone_id']]);
         $reseller_id = $resto['reseller_id'];
         $loc = isAke($row->toArray(), 'loc', []);
         $lat = isAke($loc, 'lat', false);
         $lng = isAke($loc, 'lng', false);
         if (!$lat || !$lng) {
             $company = Model::Company()->refresh()->where(['reseller_id', '=', (int) $reseller_id])->first(true);
             $coords = lib('geo')->getCoords($company->address . ' ' . $company->zip . ' ' . $company->city);
             $locationReseller = ['lng' => $coords['lng'], 'lat' => $coords['lat']];
         } else {
             $locationReseller = ['lng' => floatval($lng), 'lat' => floatval($lat)];
         }
         $options = $resto;
         unset($options['_id']);
         unset($options['reseller_id']);
         unset($options['sellzone_id']);
         unset($options['created_at']);
         unset($options['updated_at']);
         $pattern = 'type_restauration_sur_place_horaires_services_##day##_##when##';
         foreach ($days as $day) {
             if (!isset($collection[$day])) {
                 $schedules['sur_place'][$day] = [];
             }
             foreach ($when as $moment) {
                 $key = str_replace(['##day##', '##when##'], [$day, $moment], $pattern);
                 $schedules['sur_place'][$day][$moment] = str_replace(':', '_', $options[$key]);
             }
         }
         $pattern = 'type_restauration_a_emporter_horaires_services_##day##_##when##';
         foreach ($days as $day) {
             if (!isset($collection[$day])) {
                 $schedules['a_emporter'][$day] = [];
             }
             foreach ($when as $moment) {
                 $key = str_replace(['##day##', '##when##'], [$day, $moment], $pattern);
                 $schedules['a_emporter'][$day][$moment] = str_replace(':', '_', $options[$key]);
             }
         }
         $pattern = 'type_restauration_en_livraison_horaires_services_##day##_##when##';
         foreach ($days as $day) {
             if (!isset($collection[$day])) {
                 $schedules['en_livraison'][$day] = [];
             }
             foreach ($when as $moment) {
                 $key = str_replace(['##day##', '##when##'], [$day, $moment], $pattern);
                 $schedules['en_livraison'][$day][$moment] = str_replace(':', '_', isAke($options, $key, ''));
             }
         }
         $catalog_names = $plats_names = $families_types_auto_dispo = $families_types_non_auto_dispo = $families_plats_dispo = $pois_dispo = $families_pois_dispo = $specialites_dispo = $families_specialites_dispo = $spe_plats = $auto_plats = $non_auto_plats = $types_auto_dispo = $types_non_auto_dispo = $allPlats = $restoPlats = $composed = $assocs = $families = $names = $fathers = $jours = $services = $contraintes = $orders = $carte = $descriptions = $accompagnements = $pricePlats = [];
         $catalagCategories = [1 => [402, 406], 2 => [519, 500, 518, 521, 525, 522, 696, 1538, 2100], 3 => [668, 526, 690, 1530], 4 => [1528], 5 => [1952, 1958, 1548], 6 => [2167, 2168], 7 => [1942]];
         $tuplesPlats = [];
         $carte[1] = $carte[2] = $carte[3] = $carte[4] = $carte[5] = $carte[6] = $carte[7] = [];
         if ($row->carte) {
             foreach ($row->carte as $t => $ps) {
                 $carte[$t] = $ps;
                 foreach ($ps as $platCarte) {
                     $tuplesPlats[] = $platCarte['id'];
                 }
             }
         }
         $cursor = Model::Catalog()->where(['reseller_id', '=', (int) $resto['reseller_id']])->where(['is_challenge', '=', 1])->cursor();
         $collection = [];
         foreach ($cursor as $plat) {
             $segId = isAke($plat, 'segment_id', 0);
             if ($segId < 1) {
                 continue;
             }
             $plats = isAke($plat, 'plats', []);
             $accompagnements[$plat['id']] = isAke($plat, 'accompagnement', null);
             $descriptions[$plat['id']] = isAke($plat, 'description', null);
             if (!empty($plats)) {
                 $composed[$plat['segment_id']] = $plats;
             }
             $data = repo('segment')->getData((int) $plat['segment_id']);
             $ordre = isAke($data, 'ordre', 1);
             $plat['ordre'] = $ordre;
             $collection[] = $plat;
             $fathers[$plat['segment_id']] = repo('segment')->getFather($plat['segment_id'])['id'];
             $family = repo('segment')->getFamily($plat['segment_id']);
             foreach ($catalagCategories as $idCat => $segsCat) {
                 foreach ($family as $child) {
                     if (!isset($families[$plat['segment_id']])) {
                         $families[$plat['segment_id']] = [];
                     }
                     $families[$plat['segment_id']][$child['id']] = $child;
                     if (!in_array($plat['id'], $tuplesPlats)) {
                         if (in_array($child['id'], $segsCat)) {
                             unset($plat['_id']);
                             if ($plat['segment_id'] == 1548) {
                                 $carte[5][] = $plat;
                                 $p = Model::Catalog()->find((int) $plat['id']);
                                 $p->catalogcategory_id = 5;
                                 $p->save();
                             } else {
                                 $carte[$idCat][] = $plat;
                                 $p = Model::Catalog()->find((int) $plat['id']);
                                 $p->catalogcategory_id = (int) $idCat;
                                 $p->save();
                             }
                         }
                     }
                 }
             }
         }
         $collection = lib('collection', [$collection]);
         $collection->sortBy('ordre');
         $cursor = array_values($collection->toArray());
         $contraintes['jours'] = [];
         $contraintes['services'] = [];
         foreach ($cursor as $plat) {
             $s = Model::Segment()->find((int) $plat['segment_id']);
             if (!$s) {
                 continue;
             }
             $jours[$plat['id']] = isAke($plat, 'jours', []);
             $services[$plat['id']] = isAke($plat, 'services', []);
             if (!isset($contraintes['jours'][$plat['segment_id']])) {
                 $contraintes['jours'][$plat['segment_id']] = [];
             }
             if (!isset($contraintes['services'][$plat['segment_id']])) {
                 $contraintes['services'][$plat['segment_id']] = [];
             }
             $contraintes['jours'][$plat['segment_id']][$plat['id']] = isAke($plat, 'jours', []);
             $contraintes['services'][$plat['segment_id']][$plat['id']] = isAke($plat, 'services', []);
             if (!isset($assocs[$plat['id']])) {
                 $assocs[$plat['id']] = [];
                 $assocs[$plat['id']]['family'] = [];
                 $assocs[$plat['id']]['geo'] = [];
                 $assocs[$plat['id']]['auto'] = [];
                 $assocs[$plat['id']]['non_auto'] = [];
             }
             if (!isset($allPlats[$plat['segment_id']])) {
                 $allPlats[$plat['segment_id']] = [];
             }
             $restoPlats[$plat['segment_id']] = (int) $plat['id'];
             $pricePlats[$plat['id']] = (double) $plat['price'];
             $plat['data'] = repo('segment')->getData((int) $plat['segment_id']);
             $allPlats[$plat['segment_id']][] = $plat;
             $names[$plat['segment_id']] = $plats_names[$plat['segment_id']] = Model::Segment()->find((int) $plat['segment_id'])->name;
             $orders[$plat['segment_id']] = $plat['ordre'];
             $catalog_names[$plat['id']] = $plat['name'];
             $family = repo('segment')->getFamily((int) $plat['segment_id']);
             $assocs[$plat['id']]['family'][] = $plat['segment_id'];
             foreach ($family as $seg) {
                 if (!in_array($seg['id'], $families_plats_dispo)) {
                     $families_plats_dispo[] = $assocs[$plat['id']]['family'][] = $seg['id'];
                     $names[$seg['id']] = $seg['name'];
                 }
             }
             $mgeos = Model::Mealgeo()->where(['segment_id', '=', (int) $plat['segment_id']])->models();
             if ($mgeos->count() > 0) {
                 foreach ($mgeos as $mgeo) {
                     $s = Model::Segment()->find((int) $mgeo->resto_geo_id);
                     if (!$s) {
                         continue;
                     }
                     // if (!in_array($mgeo->resto_geo_id, $specialites_dispo)) {
                     if (!isset($spe_plats[$mgeo->resto_geo_id])) {
                         $spe_plats[$mgeo->resto_geo_id] = [];
                     }
                     $specialites_dispo[] = (int) $mgeo->resto_geo_id;
                     $names[$mgeo->resto_geo_id] = Model::Segment()->find((int) $mgeo->resto_geo_id)->name;
                     $family = repo('segment')->getFamily($mgeo->resto_geo_id);
                     $assocs[$plat['id']]['geo'][] = $mgeo->resto_geo_id;
                     $spe_plats[$mgeo->resto_geo_id][] = $plat['segment_id'];
                     foreach ($family as $seg) {
                         if (!isset($spe_plats[$seg['id']])) {
                             $spe_plats[$seg['id']] = [];
                         }
                         // $spe_plats[$seg['id']][] = $plat['segment_id'];
                         // $spe_plats[$mgeo->resto_geo_id][] = $plat['segment_id'];
                         if (!in_array($seg['id'], $families_specialites_dispo)) {
                             $families_specialites_dispo[] = $assocs[$plat['id']]['geo'][] = $seg['id'];
                             $names[$seg['id']] = $seg['name'];
                         }
                     }
                     // }
                 }
             }
             $mtypeautos = Model::Mealtype()->where(['segment_id', '=', (int) $plat['segment_id']])->models();
             if ($mtypeautos->count() > 0) {
                 foreach ($mtypeautos as $mtypeauto) {
                     // if (!in_array($mtypeauto->resto_type_id, $types_auto_dispo)) {
                     if (!isset($auto_plats[$mtypeauto->resto_type_id])) {
                         $auto_plats[$mtypeauto->resto_type_id] = [];
                     }
                     $auto_plats[$mtypeauto->resto_type_id][] = $plat['segment_id'];
                     $types_auto_dispo[] = (int) $mtypeauto->resto_type_id;
                     $names[$mtypeauto->resto_type_id] = Model::Segment()->find((int) $mtypeauto->resto_type_id)->name;
                     $family = repo('segment')->getFamily($mtypeauto->resto_type_id);
                     $assocs[$plat['id']]['auto'][] = $mtypeauto->resto_type_id;
                     foreach ($family as $seg) {
                         if (!isset($auto_plats[$seg['id']])) {
                             $auto_plats[$seg['id']] = [];
                         }
                         $auto_plats[$seg['id']][] = $plat['segment_id'];
                         $auto_plats[$mtypeauto->resto_type_id][] = $plat['segment_id'];
                         if (!in_array($seg['id'], $families_types_auto_dispo)) {
                             $families_types_auto_dispo[] = $assocs[$plat['id']]['auto'][] = $seg['id'];
                             $names[$seg['id']] = $seg['name'];
                         }
                     }
                     // }
                 }
             }
             $mtypeautos = Model::Mealnonauto()->where(['catalog_id', '=', (int) $plat['id']])->models();
             if ($mtypeautos->count() > 0) {
                 foreach ($mtypeautos as $mtypeauto) {
                     // if (!in_array($mtypeauto->resto_nonauto_id, $types_non_auto_dispo)) {
                     if (!isset($non_auto_plats[$mtypeauto->resto_nonauto_id])) {
                         $non_auto_plats[$mtypeauto->resto_nonauto_id] = [];
                     }
                     $non_auto_plats[$mtypeauto->resto_nonauto_id][] = $plat['segment_id'];
                     $types_non_auto_dispo[] = (int) $mtypeauto->resto_nonauto_id;
                     $names[$mtypeauto->resto_nonauto_id] = Model::Segment()->find((int) $mtypeauto->resto_nonauto_id)->name;
                     $family = repo('segment')->getFamily($mtypeauto->resto_nonauto_id);
                     $assocs[$plat['id']]['non_auto'][] = $mtypeauto->resto_nonauto_id;
                     foreach ($family as $seg) {
                         if (!isset($non_auto_plats[$seg['id']])) {
                             $non_auto_plats[$seg['id']] = [];
                         }
                         $non_auto_plats[$seg['id']][] = $plat['segment_id'];
                         // $non_auto_plats[$mtypeauto->resto_nonauto_id][] = $plat['segment_id'];
                         if (!in_array($seg['id'], $families_types_non_auto_dispo)) {
                             $families_types_non_auto_dispo[] = $assocs[$plat['id']]['non_auto'][] = $seg['id'];
                             $names[$seg['id']] = $seg['name'];
                         }
                     }
                     // }
                 }
             }
             $assocs[$plat['id']]['family'] = array_values(array_unique($assocs[$plat['id']]['family']));
             $assocs[$plat['id']]['geo'] = array_values(array_unique($assocs[$plat['id']]['geo']));
             $assocs[$plat['id']]['auto'] = array_values(array_unique($assocs[$plat['id']]['auto']));
             $assocs[$plat['id']]['non_auto'] = array_values(array_unique($assocs[$plat['id']]['non_auto']));
         }
         $pois = Model::Restopoi()->where(['sellzone_id', '=', (int) $resto['sellzone_id']])->where(['reseller_id', '=', (int) $resto['reseller_id']])->cursor();
         $distances = [];
         foreach ($pois as $poi) {
             if (!in_array($poi['segment_id'], $pois_dispo)) {
                 $poiSeg = Model::Segment()->find((int) $poi['segment_id']);
                 if ($poiSeg && (double) $poi['distance'] <= 0.5) {
                     $distances[$poi['segment_id']] = (double) $poi['distance'];
                     $pois_dispo[] = $poi['segment_id'];
                     $names[$poi['segment_id']] = $poiSeg->name;
                     $family = repo('segment')->getFamily((int) $poi['segment_id']);
                     foreach ($family as $seg) {
                         if (!in_array($seg['id'], $families_pois_dispo) && !in_array($seg['id'], $pois_dispo)) {
                             $families_pois_dispo[] = $seg['id'];
                             $names[$seg['id']] = $seg['name'];
                         }
                     }
                 }
             }
         }
         $row->reseller = Model::Reseller()->find((int) $resto['reseller_id'], false);
         $row->company = Model::Company()->where(['reseller_id', '=', (int) $resto['reseller_id']])->first(false);
         $zc = Model::Zechallenge()->where(['reseller_id', '=', (int) $resto['reseller_id']])->cursor()->first(true);
         if ($zc) {
             $status_zechallenge = $zc->status;
         } else {
             $status_zechallenge = 'WAITING';
             // Model::Zechallenge()->firstOrCreate([
             //     'reseller_id'   => (int) $resto['reseller_id']
             // ])->setStatus('WAITING')->save();
         }
         $segmentDatas = [];
         foreach ($names as $key => $n) {
             $datasK = repo('segment')->getData((int) $key);
             $segmentDatas[$key] = $datasK;
         }
         $orders = $grandfathers = [];
         foreach ($families as $s => $fathers) {
             $f = 0;
             foreach ($fathers as $father) {
                 if ($f == 2) {
                     $orders[$s] = isAke($father['data'], 'ordre', 1);
                     $grandfathers[$s] = $father;
                 }
                 $f++;
             }
         }
         $row->composed = $composed;
         $row->grandfathers = $grandfathers;
         $row->orders = $orders;
         $row->datas = $segmentDatas;
         $row->families = $families;
         $row->names = $names;
         $row->all_plats = $allPlats;
         $row->loc = $locationReseller;
         $row->options = $options;
         $row->schedules = $schedules;
         $row->status_zechallenge = $status_zechallenge;
         $q = Model::Zenews()->where(['status', '=', 'ACTIVE'])->where(['context', '=', 'resto'])->where(['reseller_id', '=', (int) $resto['reseller_id']])->cursor()->count();
         $hmz = Model::Myzelift()->where(['reseller_id', '=', (int) $resto['reseller_id']])->where(['status', '=', 'ACTIVE'])->first(true);
         if (!$hmz) {
             $hmz = false;
         } else {
             $hmz = true;
         }
         $row->has_myzelift = $hmz;
         $row->has_news = $q > 0 ? true : false;
         $row->pois = ['dispos' => $pois_dispo, 'distances' => $distances, 'families' => $families_pois_dispo];
         $row->specialites = ['dispos' => $specialites_dispo, 'families' => $families_specialites_dispo, 'plats' => $spe_plats];
         $row->auto = ['dispos' => $types_auto_dispo, 'families' => $families_types_auto_dispo, 'plats' => $auto_plats];
         $row->non_auto = ['dispos' => $types_non_auto_dispo, 'families' => $families_types_non_auto_dispo, 'plats' => $non_auto_plats];
         /* Rating */
         $rates = Model::Rating()->where(['reseller_id', '=', (int) $resto['reseller_id']])->cursor();
         $totalRate = 0;
         if ($rates->count() == 0) {
             $row->rate = 0;
         } else {
             foreach ($rates as $rateRow) {
                 $totalRate += (double) $rateRow['rate'];
             }
             $row->rate = (double) $totalRate / $rates->count();
         }
         $row->plats = ['ordre' => $orders, 'prices' => $pricePlats, 'segments' => array_keys($pricePlats), 'catalog' => $restoPlats, 'families' => $families_plats_dispo, 'names' => $plats_names, 'catalog_names' => $catalog_names, 'fathers' => $fathers];
         $resas = [];
         $customers = [];
         $old = Model::Restoreservation()->where(['reseller_id', '=', (int) $resto['reseller_id']])->where(['updated_at', '>=', strtotime('-6 month')])->cursor();
         foreach ($old as $resa) {
             $resas[] = ['account_id' => $resa['account_id'], 'date' => $resa['updated_at'], 'filter' => $resa['filter']];
             if (!isset($customers[$resa['account_id']])) {
                 $customers[$resa['account_id']] = 1;
             } else {
                 $customers[$resa['account_id']]++;
             }
         }
         $row->assocs = $assocs;
         $row->resas = $resas;
         $row->customers = $customers;
         $row->carte = $carte;
         $nc = $c = [];
         $categories = Model::Catalogcategory()->cursor();
         foreach ($categories as $cat) {
             $collection = lib('collection', [$carte[$cat['id']]])->sortBy('ordre')->toArray();
             $nc[$cat['name']] = array_values($collection);
         }
         $row->plats_ranges = $nc;
         $row->themes = lib('myzelift')->getThemesAffil($resto['reseller_id']);
         $extras = Model::Extradata()->where(['reseller_id', '=', (int) $resto['reseller_id']])->cursor()->first();
         if (empty($extras)) {
             $extras = ['access' => 'Prendre Tram 1 descendre à l\'arrêt Godrans.'];
         }
         $row->extras = $extras;
         $ups = [];
         $uplifts = Model::Uplift()->where(['status', '=', 'ACTIVE'])->where(['start', '<=', time()])->where(['reseller_id', '=', (int) $resto['reseller_id']])->cursor();
         foreach ($uplifts as $uplift) {
             unset($uplift['_id']);
             unset($uplift['created_at']);
             unset($uplift['updated_at']);
             // unset($uplift['reseller_id']);
             $type = Model::Uplifttype()->find($uplift['uplifttype_id'], false);
             unset($type['created_at']);
             unset($type['updated_at']);
             unset($type['id']);
             $uplift['type'] = $type;
             if (!isset($uplift['duration']) && isset($uplift['upliftduration_id'])) {
                 $duration = Model::Upliftduration()->find($uplift['upliftduration_id'], false);
                 unset($duration['created_at']);
                 unset($duration['updated_at']);
                 unset($duration['id']);
                 $uplift['duration'] = $duration;
             }
             $views = isset($uplift['views']) ? $uplift['views'] : 0;
             if (100 >= $views) {
                 $ups[] = $uplift;
             } else {
                 if ($uplift['end'] > time()) {
                     $ups[] = $uplift;
                 }
             }
         }
         $row->uplifts = $ups;
         $row->jours = $jours;
         $row->services = $services;
         $row->contraintes = $contraintes;
         $row->accompagnements = $accompagnements;
         $row->descriptions = $descriptions;
         $row->contraintes = $contraintes;
         $row->save();
     }
 }