Esempio n. 1
0
 public function search($word, $coords, $distance = 5, $limit = 25, $offset = 0)
 {
     $collection = $tmp = $idEtabs = [];
     $nb = $incr = 0;
     $services = rdb('geo', 'service')->select('id')->where(['family', 'LIKE', '%' . $word . '%'])->where(['code', 'LIKE', '%' . $word . '%'], 'OR')->where(['label', 'LIKE', '%' . $word . '%'], 'OR')->exec(true);
     foreach ($services as $service) {
         $sEtabs = $service->pivots(rdb('geo', 'etablissement')->model())->exec();
         foreach ($sEtabs as $sEtab) {
             $idEtabs[] = $sEtab['etablissement_id'];
         }
     }
     $idEtabs = array_unique($idEtabs);
     $db = Model::Location();
     $odm = $db->getOdm();
     $coll = $odm->selectCollection($db->collection);
     $coll->ensureIndex(['value' => '2d', 'object_motor' => 1, 'object_database' => 1, 'object_table' => 1]);
     $filter = ["value" => ['$within' => ['$center' => [[floatval($coords['lng']), floatval($coords['lat'])], floatval($distance / 111.12)]]], 'object_motor' => 'dbredis', 'object_database' => 'geo', 'object_table' => 'etablissement'];
     $results = $coll->find($filter);
     foreach ($results as $result) {
         if (Arrays::in($result['object_id'], $idEtabs)) {
             $etab = rdb('geo', 'etablissement')->find($result['object_id']);
             $distances = distanceKmMiles($coords['lng'], $coords['lat'], $etab->lng, $etab->lat);
             $distance = $distances['km'];
             $item = $etab->assoc();
             $item['distance'] = $distance;
             $collection[] = $item;
         }
     }
     $collection = $this->orderBy($collection, 'distance');
     if ($limit == 0) {
         return $collection;
     } else {
         return array_slice($collection, $offset, $limit);
     }
 }
Esempio n. 2
0
 public function searchNearByAddress($address, $query)
 {
     $collection = lib('collection');
     $coords = lib('geo')->getCoords($address);
     $url = 'http://search.mappy.net/search/1.0/find?extend_bbox=1&bbox=' . $coords['lat1'] . ',' . $coords['lng1'] . ',' . $coords['lat2'] . ',' . $coords['lng2'] . '&q=' . urlencode($query) . '&favorite_country=' . $coords['country_id'] . '&language=FRE&&max_results=199';
     dd($url);
     $key = 'serach.near.' . sha1($url);
     $json = redis()->get($key);
     if (!$json) {
         $json = dwn($url);
         redis()->set($key, $json);
     }
     $data = json_decode($json, true);
     $pois = isAke($data, 'pois', []);
     foreach ($pois as $service) {
         $dbService = rdb('geo', 'service')->where(['code', '=', $service['rubricId']])->first(true);
         if ($dbService) {
             $id = $dbService->id;
         } else {
             if (isset($service['allRubrics'])) {
                 if (count($service['allRubrics'])) {
                     foreach ($service['allRubrics'] as $rubrikA) {
                         $idr = isAke($rubrikA, 'id');
                         $lr = isAke($rubrikA, 'label');
                         $pr = isAke($rubrikA, 'rubricParentId');
                         if ($idr == $service['rubricId']) {
                             $spi = rdb('geo', 'service')->firstOrCreate(['code' => $idr])->setLabel($lr)->setFamily($pr)->save();
                             $id = $spi->id;
                         }
                     }
                 }
             }
         }
         $serviceproxIds = $supplements = [];
         $serviceproxIds[] = $id;
         $poi = $service['id'];
         $checkEtab = rdb('geo', 'etablissement')->where(['poi', '=', (string) $poi])->first(true);
         $add = $checkEtab ? false : true;
         unset($service['id']);
         if (false === $add) {
             $service['id'] = $checkEtab->id;
         }
         unset($service['offer']);
         unset($service['prov']);
         unset($service['pjBlocId']);
         unset($service['thematicId']);
         if (isset($service['tabs'])) {
             if (count($service['tabs'])) {
                 foreach ($service['tabs'] as $tmp) {
                     $tmpUrl = isAke($tmp, 'url', false);
                     $tmpId = isAke($tmp, 'appId', false);
                     if (false !== $tmpUrl && false !== $tmpId) {
                         $key = 'inf.' . $poi . '.' . $tmpId;
                         if ($tmpId == 'pj') {
                             $inf = redis()->get($key);
                             if (empty($inf)) {
                                 $infHtml = dwn($tmpUrl);
                                 $inf = substr($infHtml, strlen('callback('), -1);
                                 redis()->set($key, $inf);
                             }
                             $inf = json_decode($inf, true);
                             $t = isAke($inf, 'tabs', []);
                             if (!empty($t)) {
                                 foreach ($t as $tmpT) {
                                     $b = isAke($tmpT, 'blocks', []);
                                     $t = isAke($tmpT, 'tags', []);
                                     if (!empty($b)) {
                                         for ($ti = 0; $ti < count($b); $ti += 2) {
                                             $seg = $b[$ti];
                                             $seg2 = $b[$ti + 1];
                                             if (is_array($seg) && is_array($seg2)) {
                                                 $title = isAke($seg, 'title', false);
                                                 $kv = isAke($seg2, 'keyValue', false);
                                                 if (false !== $title && false !== $kv) {
                                                     $title = Inflector::urlize($title);
                                                     foreach ($kv as $tmpRow) {
                                                         $supplements[$title][] = [$tmpRow['key'] => $tmpRow['value']];
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         } elseif ($tmpId == 'indoor') {
                         } elseif ($tmpId == 'localbusinesspremium') {
                         } elseif ($tmpId == 'total') {
                         } elseif ($tmpId == 'totalaccess') {
                         } elseif ($tmpId == 'darty') {
                         } elseif ($tmpId == 'eleclerc') {
                         } elseif ($tmpId == 'moteurproduitpromo') {
                         } elseif ($tmpId == 'mappyshopping') {
                         } elseif ($tmpId == 'booking') {
                             $inf = redis()->get($key);
                             if (empty($inf)) {
                                 $infHtml = dwn($tmpUrl);
                                 $inf = substr($infHtml, strlen('callback('), -1);
                                 redis()->set($key, $inf);
                             }
                             $inf = json_decode($inf, true);
                             /* TODO */
                         } elseif ($tmpId == 'localbusinessdiscovery') {
                             $inf = redis()->get($key);
                             if (empty($inf)) {
                                 $infHtml = dwn($tmpUrl);
                                 $inf = substr($infHtml, strlen('callback('), -1);
                                 redis()->set($key, $inf);
                             }
                             $inf = json_decode($inf, true);
                             $t = isAke($inf, 'tabs', []);
                             if (!empty($t)) {
                                 foreach ($t as $tmpT) {
                                     $b = isAke($tmpT, 'blocks', []);
                                     if (!empty($b)) {
                                         foreach ($b as $tmpB) {
                                             $kv = isAke($tmpB, 'keyValue', false);
                                             if (false !== $kv) {
                                                 foreach ($kv as $tmpRow) {
                                                     $tmpK = Inflector::urlize($tmpRow['key']);
                                                     $supplements['infos'][$tmpK] = $tmpRow['value'];
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         } else {
                             $inf = redis()->get($key);
                             if (empty($inf)) {
                                 $infHtml = dwn($tmpUrl);
                                 $inf = substr($infHtml, strlen('callback('), -1);
                                 redis()->set($key, $inf);
                             }
                             $inf = json_decode($inf, true);
                         }
                     }
                 }
             }
         }
         unset($service['tabs']);
         unset($service['contextualPoiUrl']);
         unset($service['providerIds']);
         unset($service['pjRatingId']);
         unset($service['hasUnclaimableProvider']);
         unset($service['additionalInfos']);
         unset($service['additionalInfo']);
         unset($service['coordinateProvider']);
         unset($service['coordinateProvider3D']);
         unset($service['offerType']);
         unset($service['rubricId']);
         unset($service['closestPanoramicId']);
         if (isset($service['allRubrics'])) {
             if (count($service['allRubrics'])) {
                 foreach ($service['allRubrics'] as $rubrikA) {
                     $idr = isAke($rubrikA, 'id');
                     $lr = isAke($rubrikA, 'label');
                     $pr = isAke($rubrikA, 'rubricParentId');
                     $spi = rdb('geo', 'service')->firstOrCreate(['code' => $idr])->setLabel($lr)->setFamily($pr)->save();
                 }
             }
             unset($service['allRubrics']);
         }
         if (isset($service['additionalRubricIds'])) {
             if (count($service['additionalRubricIds'])) {
                 foreach ($service['additionalRubricIds'] as $newRubrique) {
                     $spi = rdb('geo', 'service')->firstOrCreate(['code' => $newRubrique]);
                     $serviceproxIds[] = $spi->id;
                 }
             }
         }
         unset($service['additionalRubricIds']);
         unset($service['brandIconUrl']);
         unset($service['slat']);
         unset($service['slng']);
         unset($service['salt']);
         unset($service['brand']);
         unset($service['indoors']);
         unset($service['visibleIn3D']);
         unset($service['townCode']);
         if (isset($service['town'])) {
             $service['city'] = $service['town'];
             unset($service['town']);
         }
         if (isset($service['positions3D'])) {
             if (isset($service['positions3D']['origin'])) {
                 if (isset($service['positions3D']['origin']['alt'])) {
                     $service['altitude'] = $service['positions3D']['origin']['alt'];
                     unset($service['positions3D']);
                 }
             }
         }
         if (isset($service['way'])) {
             $service['address'] = $service['way'];
             unset($service['way']);
         }
         if (isset($service['pCode'])) {
             $service['zip'] = $service['pCode'];
             unset($service['pCode']);
             unset($service['positions3D']);
         }
         if (isset($service['lat']) && isset($service['lng'])) {
             $distances = distanceKmMiles($coords['lng1'], $coords['lat1'], $service['lng'], $service['lat']);
             $service['distance'] = (double) $distances['km'];
         }
         ksort($service);
         $service['poi'] = $poi;
         if (false === $add) {
             $collection[] = $service;
         }
         if (true === $add) {
             $distance = $service['distance'];
             unset($service['distance']);
             $etab = rdb('geo', 'etablissement')->firstOrCreate($service)->setPoi($poi)->save();
             setLocation($etab, $etab->lng, $etab->lat);
             if (!empty($supplements)) {
                 foreach ($supplements as $supK => $supV) {
                     $setter = setter($supK);
                     $etab->{$setter}($supV);
                 }
                 $etab->save();
             }
             $fields = $etab->_keys();
             $sFields = array_merge(array_keys($service), array_keys($supplements));
             $except = ['id', 'poi', 'created_at', 'updated_at'];
             $resave = false;
             $expurge = [];
             foreach ($fields as $field) {
                 if (!in_array($field, $except)) {
                     if (!in_array($field, $sFields)) {
                         $expurge[] = $field;
                         $etab = $etab->expurge($field);
                         $resave = true;
                     }
                 }
             }
             if (true === $resave) {
                 $etab = $etab->save();
             }
             foreach ($serviceproxIds as $serviceproxId) {
                 $spTmp = rdb('geo', 'service')->find((int) $serviceproxId);
                 $spTmp->attach($etab);
             }
             $zone = rdb('geo', 'zone')->find(1);
             $zone->attach($etab);
             $service['new'] = true;
             $service['id'] = $etab->id;
             $service['distance'] = $distance;
         }
         $collection[] = $service;
     }
     if (!empty($collection)) {
         $tuples = $new = [];
         $collection->sortBy('distance');
         foreach ($collection as $row) {
             $hasPoi = isAke($row, 'poi', false);
             if (false === $hasPoi) {
                 $new[] = $row;
             } else {
                 $poi = sha1($hasPoi);
                 if (!in_array($poi, $tuples)) {
                     $tuples[] = $poi;
                     $new[] = $row;
                 }
             }
         }
         $collection = lib('collection', [$new]);
     }
     return $collection->toArray();
 }
Esempio n. 3
0
 public function gpois($lat, $lng, $type = 'restaurant')
 {
     $url = "https://www.google.fr/search?tbm=map&fp=1&authuser=0&hl=fr&pb=!4m12!1m3!1d4073.5434512203738!2d{$lng}!3d{$lat}!2m3!1f0!2f0!3f0!3m2!1i1360!2i298!4f13.1!7i10!10b1!12m6!2m3!5m1!2b0!20e3!10b1!16b1!19m3!2m2!1i392!2i106!20m40!2m2!1i203!2i200!3m1!2i4!6m6!1m2!1i86!2i86!1m2!1i408!2i256!7m26!1m3!1e1!2b0!3e3!1m3!1e2!2b1!3e2!1m3!1e2!2b0!3e3!1m3!1e3!2b0!3e3!1m3!1e4!2b0!3e3!1m3!1e3!2b1!3e2!2b1!4b0!9b0!7e81!24m1!2b1!26m3!2m2!1i80!2i92!30m28!1m6!1m2!1i0!2i0!2m2!1i458!2i298!1m6!1m2!1i1310!2i0!2m2!1i1360!2i298!1m6!1m2!1i0!2i0!2m2!1i1360!2i20!1m6!1m2!1i0!2i278!2m2!1i1360!2i298!37m1!1e81&q=" . urlencode($type);
     $data = xCache('gpois.' . sha1(serialize(func_get_args()) . $type), function () use($url) {
         return lib('geo')->dwn($url);
     }, strtotime('+6 month'));
     $data = str_replace("\n", "", $data);
     $data = str_replace("\r", "", $data);
     $data = str_replace("\t", "", $data);
     $data = str_replace(")]}'", "", $data);
     $data = json_decode($data, true);
     $tab = $data[0][1];
     array_shift($tab);
     $collection = [];
     foreach ($tab as $row) {
         $latRow = $row[14][9][2];
         $lngRow = $row[14][9][3];
         $distances = distanceKmMiles($lng, $lat, $lngRow, $latRow);
         $name = $row[14][11];
         $ws = $row[14][7][0];
         $tel = $row[14][3][0];
         $address = $row[14][2][0] . ', ' . $row[14][2][1];
         $price = $row[14][4][2];
         $rate = floatval($row[14][4][7]);
         $avis = (int) $row[14][4][8];
         $type = $row[14][13][0];
         $hexa = $row[14][10];
         $label = $row[14][18];
         $link = $row[14][4][3][0];
         if (strstr($link, 'ludocid')) {
             $cid = 'g' . Utils::cut('ludocid=', '#', $link);
         } else {
             $cid = 'g' . Utils::cut('.com/', '/', $row[6][1]);
         }
         $horaires = $row[14][34][1];
         $abstract = $row[14][32][0][1] . '. ' . $row[14][32][1][1];
         $obj = ['distance' => $distances['km'] * 1000, 'hexa' => $hexa, 'cid' => $cid, 'type' => $type, 'label' => $label, 'abstract' => $abstract, 'name' => $name, 'lat' => $latRow, 'lng' => $lngRow, 'website' => $ws, 'phone' => $tel, 'address' => $address, 'rate' => $rate, 'avis' => $avis, 'price' => $price, 'schedule' => $this->schedule($horaires), 'img_in' => 'http:' . $row[14][37][0][1][6][0], 'img_out' => 'http:' . $row[14][37][0][2][6][0]];
         if ($obj['img_in'] == 'http:') {
             continue;
         } else {
             $obj['img_in'] .= '&w=600&h=400';
         }
         if ($obj['img_out'] == 'http:') {
             $obj['img_out'] = null;
         } else {
             $obj['img_out'] .= '&w=600&h=400';
         }
         if ($obj['cid'] == 'g') {
             $obj['cid'] = null;
             Model::FeatureMap()->firstOrCreate(['fid' => 'g' . $hexa]);
         } else {
             Model::FeatureMap()->firstOrCreate(['fid' => $cid]);
         }
         $collection[] = $obj;
     }
     $collection = coll($collection)->sortBy('distance')->toArray();
     $collection = array_values($collection);
     return $collection;
 }
Esempio n. 4
0
 public function makeOffersOut($offerin)
 {
     $collection = [];
     $errors = [];
     $infos = [];
     $resellers = [];
     $minStartDelay = Config::get('offerin.delay', 115) * 60;
     $model = lib('model')->getStaticModel((int) $offerin->segment_id);
     $isCalendar = isAke($model, 'is_calendar', true);
     $now = time();
     $isPro = false;
     if (!isset($offerin->sellzone_id)) {
         $offerin->sellzone_id = 1;
         $offerin->save();
     }
     if (isset($offerin->company_id)) {
         $address = Model::Companyaddress()->findOrFail((int) $offerin->address_id);
         $isPro = true;
     } else {
         $address = Model::Accountaddress()->findOrFail((int) $offerin->address_id);
     }
     if (true === $isPro) {
         if (!isset($offerin->company_id)) {
             $offerin->company_id = (int) $address->company_id;
             $offerin = $offerin->save();
         }
     } else {
         if (!isset($offerin->account_id)) {
             $offerin->account_id = (int) $address->account_id;
             $offerin = $offerin->save();
         }
     }
     $locationOffer = lib('utils')->remember('get.location.address.' . $address->id, function ($address) {
         return getLocation($address);
     }, $isPro ? Model::Companyaddress()->getAge() : Model::Accountaddress()->getAge(), [$address]);
     if (empty($locationOffer)) {
         $coords = lib('geo')->getCoords($address->address . ' ' . $address->zip . ' ' . $address->city, 250);
         setLocation($address, $coords['lng'], $coords['lat']);
         $locationOffer = ['lng' => $coords['lng'], 'lat' => $coords['lat']];
     }
     $segment_id = (int) $offerin->segment_id;
     $family = repo('segment')->getFamilyfromItem((int) $segment_id);
     if (!empty($family)) {
         $market = current($family);
         $market_id = (int) $market['id'];
     } else {
         $market_id = $segment_id;
     }
     $offer = $offerin->toArray();
     if (isset($offer['date']) && isset($offer['time'])) {
         list($y, $m, $d) = explode('-', $offer['date'], 3);
         list($h, $i, $s) = explode(':', $offer['time'], 3);
         $start = mktime($h, $i, $s, $m, $d, $y);
     } else {
         $start = $offerin->created_at;
     }
     if ($start < $now) {
         $errors['starttime_error'] = 'Start time [' . date('Y-m-d H:i:s', $start) . '] is before now.';
     }
     $delaySeconds = $start - $now;
     $delai = (double) round($delaySeconds / 3600, 2);
     if ($delaySeconds < $minStartDelay) {
         $errors['delay_incorrect'] = 'The delay is incorrect [' . $delaySeconds . ' seconds]. The delay me be at less egual to ' . $minStartDelay . ' seconds.';
         return ['resellers' => $resellers, 'offers' => $collection, 'errors' => $errors, 'infos' => $infos];
     }
     $langue = $offerin->langue;
     if (!strlen($langue) || empty($langue) || strtolower($langue) == 'non') {
         $langue = false;
     }
     if ($langue) {
         $langues = lib('forms')->getLanguagesFromSegmentId($segment_id);
         if (!in_array($langue, $langues)) {
             $langue = false;
         }
     }
     $this->cleanToPay($offerin->segment_id);
     $products = Model::Productdata()->where(['segment_id', '=', (int) $offerin->segment_id])->where(['sellzone_id', '=', (int) $offerin->sellzone_id])->cursor();
     foreach ($products as $product) {
         $item = [];
         $reseller = Model::Reseller()->model($product['reseller']);
         $company = Model::Company()->model($product['company']);
         // $company    = Model::Company()->where(['reseller_id', '=', (int) $product['reseller_id']])->first(true);
         if ($reseller && $company) {
             // $statusId = (int) lib('status')->getId('reseller', 'REGISTER');
             if (false === $product['status']) {
                 $infos[$reseller->id]['status'] = true;
                 continue;
             }
             $infos[$reseller->id] = [];
             $options = $product['options'];
             $hasAgenda = isAke($options, 'has_agenda', false);
             // $hasAgenda = lib('option')->get('agenda.partage', $reseller, false);
             $item['reseller_calendar'] = $hasAgenda;
             $item['reseller_id'] = $reseller->id;
             $item['segment_id'] = $segment_id;
             if (true === $isPro) {
                 $item['company_id'] = $offer['company_id'];
             } else {
                 $item['account_id'] = $offer['account_id'];
             }
             $locationReseller = lib('utils')->remember('has.locations.companies.' . $product['reseller_id'], function ($reseller_id) {
                 $company = Model::Company()->where(['reseller_id', '=', (int) $reseller_id])->first(true);
                 $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']]);
             $quantity = (double) $this->getQuantity($offer);
             /* si une langue est demandée on vérifie si le revendeur la parle, sinon, on passe au suivant */
             if ($langue) {
                 // $speak = lib('option')->get('langue.' . $market_id . '.' . $langue, $reseller, false);
                 $speak = isAke($options['languages'], $langue, false);
                 if (false === $speak) {
                     $infos[$reseller->id]['language'] = true;
                     continue;
                 }
             }
             $distanceMaxOffer = isset($offer['distance_max']) ? (double) $offer['distance_max'] : 0;
             // $distanceMaxReseller    = (double) lib('option')->get('zone.intervention.' . $market_id, $reseller, 0);
             $distanceMaxReseller = (double) isAke($options, 'distance_max', 0);
             $distance = distanceKmMiles($locationOffer['lng'], $locationOffer['lat'], $locationReseller['lng'], $locationReseller['lat']);
             $km = (double) $distance['km'];
             $item['distance'] = $km;
             if (0 < $distanceMaxOffer || 0 < $distanceMaxReseller) {
                 if ($distanceMaxOffer < $km && $distanceMaxOffer > 0) {
                     $infos[$reseller->id]['distance_reseller'] = true;
                     continue;
                 }
                 if ($distanceMaxReseller < $km && $distanceMaxReseller > 0) {
                     $infos[$reseller->id]['distance_buyer'] = true;
                     continue;
                 }
             }
             // $delai_presta = lib('option')->get('delai.intervention.' . $market_id, $reseller, 0);
             $delai_presta = isAke($options, 'delai_min', 0);
             $item['date_max_offer'] = (int) $start - 3600;
             if (0 < $delai_presta) {
                 if ($delai < $delai_presta) {
                     $infos[$reseller->id]['delay_reseller'] = true;
                     continue;
                 } else {
                     $item['date_max_offer'] = (int) $start - $delai_presta * 3600;
                 }
             }
             if ($hasAgenda) {
                 $item['date_max_offer'] = $item['date_max_offer'] > $now + 3600 ? $now + 3600 : $item['date_max_offer'];
             } else {
                 $item['date_max_offer'] = $item['date_max_offer'] > $now + 1800 ? $now + 1800 : $item['date_max_offer'];
             }
             $makePrice = $amount = (double) $this->makePrice($offer, $product['product']);
             $minAmount = isAke($options, 'amount_min', 0);
             if ($minAmount > $amount) {
                 $infos[$reseller->id]['amount_reseller'] = true;
                 continue;
             }
             $tva = isAke($product['product'], 'tva', 1);
             $discount_default_quantity = isAke($product['product'], 'discount_default_quantity', 0);
             $discount_default_amount = (double) isAke($product['product'], 'discount_default_amount', 0);
             $discount_price_quantity = isAke($product['product'], 'discount_price_quantity', 0);
             $discount_price_amount = (double) isAke($product['product'], 'discount_price_amount', 0);
             $fixed_costs_default = (double) isAke($product['product'], 'fixed_costs_default', 0);
             $travel_costs_default = (double) isAke($product['product'], 'travel_costs_default', 0);
             $shipping_costs_default = (double) isAke($product['product'], 'shipping_costs_default', 0);
             $item['fixed_costs'] = $fixed_costs_default;
             $item['travel_costs'] = $travel_costs_default;
             $item['shipping_costs'] = $shipping_costs_default;
             $item['discount'] = 0;
             $item['tva_id'] = (int) $tva;
             if ($discount_default_quantity > 0 && $discount_default_amount > 0) {
                 if ($quantity >= $discount_default_quantity) {
                     $discount = (double) round($amount * $discount_default_amount / 100, 2);
                     $amount -= $discount;
                     $item['discount'] = $discount;
                 }
             } else {
                 if ($discount_price_quantity > 0 && $discount_price_amount > 0) {
                     if ($amount >= $discount_price_quantity) {
                         $discount = (double) round($amount * $discount_price_amount / 100, 2);
                         $amount -= $discount;
                         $item['discount'] = $discount;
                     }
                 }
             }
             if (0 < $fixed_costs_default) {
                 $amount += $fixed_costs_default;
             }
             if (0 < $shipping_costs_default) {
                 $amount += $shipping_costs_default;
             }
             if (0 < $travel_costs_default) {
                 $travel_costs = (double) $travel_costs_default * $km;
                 $amount += $travel_costs;
                 $item['travel_costs'] = $travel_costs;
             }
             $optionsOffer = $this->extractOptions($offer);
             if (!empty($optionsOffer)) {
                 foreach ($optionsOffer as $opt) {
                     $value = isAke($offer, $opt, 0);
                     if ($value > 0) {
                         $price = isAke($product['product'], $this->transform($opt), 0);
                         $amountOption = (double) $price * $quantity;
                         $amount += $amountOption;
                         $item[$this->transform($opt)] = $amountOption;
                     }
                 }
             }
             $resellers[] = $reseller->id;
             $item['amount'] = (double) $amount;
             $item['offerin_id'] = (int) $offer['id'];
             if (true === $isCalendar) {
                 if (isset($product['product']['taux_horaire'])) {
                     $duration = (double) $makePrice / $product['product']['taux_horaire'];
                 } else {
                     $duration = $quantity;
                 }
                 $end = $start + 3600 * $duration;
                 $item['duration'] = $end - $start;
                 $employees = $this->getEmployeesCan((int) $start, (int) $end, (int) $product['reseller_id']);
                 if (empty($employees)) {
                     $infos[$reseller->id]['no_employee'] = true;
                     Model::offerouttrash()->create($item)->save();
                     continue;
                 }
                 $item['reselleremployees'] = $employees;
                 $item['start'] = $start;
                 $item['end'] = $end;
             } else {
                 $employees = Model::Reselleremployee()->where(['reseller_id', '=', (int) $reseller->id])->select('id')->cursor()->toArray();
                 $item['reselleremployees'] = $employees;
             }
             $item['status_id'] = (int) lib('status')->getId('offerout', 'SHOWN');
             $offerOut = Model::Offerout()->create($item)->save();
             $item['offerout_id'] = $offerOut->id;
             $collection[] = $item;
         }
     }
     $return = [];
     $return['resellers'] = $resellers;
     $return['offers'] = $collection;
     if (!empty($errors)) {
         $return['errors'] = $errors;
     }
     if (!empty($infos)) {
         $return['infos'] = $infos;
     }
     $offerin->resellers = $resellers;
     if (true === $isCalendar) {
         $offerin->start = $start;
     }
     $offerin->save();
     return $return;
 }
Esempio n. 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();
 }
Esempio n. 6
0
 public function searchGPois($type, $ll)
 {
     $rows = $this->em('nodes')->find(['type' => 'poi', 'provider' => 'g', 'subtype' => $type]);
     $collection = [];
     $start = true;
     foreach ($rows as $row) {
         $distances = distanceKmMiles(floatval($ll['lng']), floatval($ll['lat']), floatval($row['location']['coordinates'][0]), floatval($row['location']['coordinates'][1]));
         $row['distance'] = $distances['km'] * 1000;
         if ($row['distance'] <= 1000 || empty($collection) && !$start) {
             $collection[] = $row;
             $start = true;
         }
     }
     return array_values(coll($collection)->sortBy('distance')->toArray());
 }
Esempio n. 7
0
 function getDatasFromMaxDistance($model, $ref, $maxDistance = 1, $max = 1000)
 {
     if (!is_object($model)) {
         throw new Exception("The first argument is not a model.");
     }
     if (!is_object($ref)) {
         throw new Exception("The second argument is not a model.");
     }
     $lngLat = getLocation($ref);
     if ($model instanceof Dbjson\Dbjson) {
         $motor = 'dbjson';
     } else {
         $motor = 'dbredis';
     }
     $add = [];
     $db = bigDb('location');
     $odm = $db->getOdm();
     $collection = $odm->selectCollection($db->collection);
     $collection->ensureIndex(['value' => '2d', 'object_motor' => 1, 'object_database' => 1, 'object_table' => 1]);
     $filter = ['value' => ['$near' => [floatval($lngLat['lng']), floatval($lngLat['lat'])]], 'object_motor' => $motor, 'object_database' => $model->db, 'object_table' => $model->table];
     $results = $collection->find($filter)->limit($max);
     foreach ($results as $row) {
         $rowMotor = $row['object_motor'];
         if ('dbjson' == $rowMotor) {
             $rowDb = jdb($row['object_database'], $row['object_table'])->find($row['object_id'], false);
         } elseif ('dbredis' == $rowMotor) {
             $rowDb = rdb($row['object_database'], $row['object_table'])->find($row['object_id'], false);
         }
         $distances = distanceKmMiles($lngLat['lng'], $lngLat['lat'], $row['value']['lng'], $row['value']['lat']);
         if (floatval($distances['km']) <= $maxDistance) {
             $rowDb['distance'] = ['km' => (double) $distances['km'], 'miles' => (double) $distances['miles']];
             if ($distances['km'] > 0) {
                 array_push($add, $rowDb);
             }
         } else {
             break;
         }
     }
     return $add;
 }
Esempio n. 8
0
 /**
  * [assocPoi description]
  * @param  [type] $reseller_id [description]
  * @return [type]              [description]
  */
 public function assocPoi($reseller_id = null)
 {
     set_time_limit(0);
     $distanceMax = 0.5;
     $segments = Model::Segment()->where(['segmenttype_id', '=', 8])->cursor();
     $pois = [];
     foreach ($segments as $segment) {
         if (isset($segment['segment_id'])) {
             if (strlen($segment['segment_id'])) {
                 $count = Model::Segment()->where(['segment_id', '=', (int) $segment['id']])->cursor()->count();
                 $hasChildren = $count > 0;
                 if (!$hasChildren) {
                     $data = repo('segment')->getData((int) $segment['id']);
                     $latitude = isAke($data, 'latitude', false);
                     $longitude = isAke($data, 'longitude', false);
                     $sellzone_id = isAke($data, 'sellzone_id', false);
                     if (false !== $latitude && false !== $longitude && false !== $sellzone_id) {
                         $latitude = str_replace(',', '.', $latitude);
                         $longitude = str_replace(',', '.', $longitude);
                         $pois[] = ['segment_id' => (int) $segment['id'], 'lat' => (double) $latitude, 'lng' => (double) $longitude, 'sellzone_id' => (int) $sellzone_id];
                     }
                 }
             }
         }
     }
     $q = Model::Optionsrestaurant();
     if ($reseller_id) {
         $q->where(['reseller_id', '=', (int) $reseller_id]);
     }
     $restos = $q->cursor();
     foreach ($restos as $resto) {
         $company = Model::company()->where(['reseller_id', '=', (int) $resto['reseller_id']])->first(true);
         if ($company) {
             $loc = lib('utils')->remember('has.locations.companies.' . $resto['reseller_id'], function ($reseller_id) {
                 $company = Model::Company()->where(['reseller_id', '=', (int) $reseller_id])->first(true);
                 $coords = lib('geo')->getCoords($company->address . ' ' . $company->zip . ' ' . $company->city);
                 $loc = ['lng' => $coords['lng'], 'lat' => $coords['lat']];
                 return $loc;
             }, Model::Company()->getAge(), [$resto['reseller_id']]);
             foreach ($pois as $poi) {
                 if ($resto['sellzone_id'] == $poi['sellzone_id']) {
                     $distances = distanceKmMiles($loc['lng'], $loc['lat'], $poi['lng'], $poi['lat']);
                     $km = (double) $distances['km'];
                     $check = $km <= $distanceMax;
                     if (true === $check) {
                         Model::Restopoi()->firstOrCreate(['sellzone_id' => (int) $resto['sellzone_id'], 'reseller_id' => (int) $resto['reseller_id'], 'segment_id' => (int) $poi['segment_id'], 'distance' => (double) $km]);
                     }
                 }
             }
         }
     }
     Model::Cronrunning()->firstOrCreate(['task' => 'assocPoi'])->setRunning(0)->save();
 }