コード例 #1
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $date = $input->getArgument('date');
     if (!empty($date)) {
         $date = dateEuToCarbon($date);
         $menu = Menu::where('start_date', '=', $date)->limit(1)->firstOrFail();
     } else {
         //prendi l'ultimo menu
         $menu = Menu::orderBy('start_date', 'desc')->limit(1)->first();
     }
     //var_dump($lastMenu->start_date);
     $menuProducts = $menu->menuProducts()->get();
     $entries = [];
     foreach ($menuProducts as $mp) {
         $entry = [];
         $product = $mp->product()->first();
         $entry[] = $product->id;
         $entry[] = substr($product->getName(), 0, 60);
         $entry[] = $mp->getPrice();
         $entry[] = $product->getCategory();
         $entry[] = $mp->menuOrderProducts()->get()->sum('quantity');
         $entries[] = $entry;
         //$entries[] = new TableSeparator();
     }
     // usort($entries, function($a, $b) {
     //     return $a[3] > $b[3];
     // });
     $table = new Table($output);
     $table->setHeaders(array('ID', 'Prodotto', 'Prezzo', 'Categoria', 'Ordini del giorno precedente'))->setRows($entries);
     $table->render();
 }
コード例 #2
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $csvsPath = APP_CWD . '/../csv';
     $csvsDatesRegexp = 'd-m-Y';
     $menusDatesAlreadyLoaded = array_map(function ($date) use($csvsDatesRegexp) {
         return Carbon::parse($date['start_date'])->format($csvsDatesRegexp);
     }, Menu::all()->toArray());
     $finder = new \Symfony\Component\Finder\Finder();
     $finder = $finder->files()->name('*.csv');
     foreach ($menusDatesAlreadyLoaded as $date) {
         $finder->notPath($date);
     }
     $files = $finder->in($csvsPath);
     foreach ($files as $file) {
         list($d, $m, $Y) = explode('-', explode('_', $file->getFilename())[0]);
         $menuDate = Carbon::parse("{$Y}-{$m}-{$d}");
         $reader = \League\Csv\Reader::createFromPath($file->getPathname());
         $results = $reader->setDelimiter(';')->fetchAssoc();
         //creazione Menu ed aggiunta del prodotto
         $menu = Menu::write($menuDate, $menuDate->copy()->addHours(14));
         foreach ($results as $row) {
             if (empty($row['Prezzo'])) {
                 continue;
             }
             $price = floatval(ltrim(str_replace([','], '.', $row['Prezzo']), '€'));
             $category = Product::findCategory($row['Categoria'], false);
             //creazione Prodotto
             $product = Product::firstOrCreate(['code' => $row['Codice'], 'description' => $row['Descrizione'], 'category' => $category]);
             $product->price = $price;
             $product->update();
             $menu->addProduct($product);
         }
     }
 }
コード例 #3
0
 public function find($id)
 {
     if ($id == 'last') {
         $menu = Menu::getLast();
     } else {
         $menu = Menu::find($id);
     }
     if (empty($menu)) {
         return $this->failResponse('Menu not found ', self::STATUS_NOTFOUND);
     }
     return $this->respondWithItem($menu);
 }
コード例 #4
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $gmail = new \Jambon\GmailClient\GmailClient();
     $emails = $gmail->readEmails(['maxResults' => $input->getArgument('entries'), 'labelIds' => 'INBOX', 'includeSpamTrash' => true, 'q' => 'from:serviziomensa@mosaicoon.com conferma menu ' . $input->getArgument('extraString')], function (array $email) use($output) {
         $content = $email['body']['html'][0];
         // --------------------------------------------------------------------
         preg_match("/[0-9]{1,2}\\/[0-9]{1,2}\\/[0-9]{4}/", $content, $matched);
         list($d, $m, $y) = explode('/', $matched[0]);
         $menuDate = Carbon::parse("{$y}-{$m}-{$d} 00:00:00");
         $output->writeLn("Importando Menu del " . $matched[0]);
         // --------------------------------------------------------------------
         if ($menu = Menu::where(['start_date' => $menuDate, 'type' => Menu::TYPE_PRANZO])->count() > 0) {
             //menu già registrato
             $output->writeLn("MENU del " . $matched[0] . " GIA SALVATO");
             return;
         }
         $menu = Menu::write($menuDate, $menuDate->copy()->addHours(14));
         $crawler = new \Symfony\Component\DomCrawler\Crawler();
         $crawler->addHTMLContent($content, 'UTF-8');
         $crawler->filter('table')->eq(0)->filter('tr')->each(function ($tr, $i) use($menu) {
             if ($i === 0) {
                 return;
             }
             $prodData = [];
             $tr->filter('td')->each(function ($td, $i) use(&$prodData) {
                 if ($i == 0) {
                     $prodData['category'] = str_replace(['<', '>', '[', ']'], null, $td->text());
                 } elseif ($i == 1) {
                     $desc = trim(str_replace(['[NUOVO]', '(NUOVO)', '(Nuovo)'], null, $td->text()));
                     $prodData['description'] = strip_tags($desc);
                 } elseif ($i == 2) {
                     $prodData['price'] = floatval(ltrim($td->text(), '€'));
                 }
             });
             //prevent insert injection code
             if (in_array($prodData['category'], ['', null, 'code', 'c'])) {
                 return;
             }
             $menu->addProduct(Product::firstOrCreate($prodData));
             echo '.';
         });
         $output->writeLn(" ");
     });
 }
コード例 #5
0
 /**
  * Turn this item object into a generic array
  *
  * @return array
  */
 public function transform(Menu $menu)
 {
     return ['id' => $menu->id, 'date' => $this->formatDate($menu->getDate()), 'type' => $menu->getType(), 'products' => $this->processCollection($menu->menuProducts()->get(), new MenuProductsTransformer())];
 }
コード例 #6
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $instructions = $this->parser(file_get_contents(APP_CWD . '/prova.parser'));
     //prende l'ultimo menu
     $menu = Menu::orderBy('start_date', 'desc')->limit(1)->first();
     $toDel = [];
     if (!empty($instructions['del'])) {
         $output->writeLn('Da togliere:');
         foreach ($instructions['del'] as $values) {
             $prodIds = $menu->menuProducts()->get()->lists('product_id')->toArray();
             $prod = $this->resolveProduct(Product::whereIn('id', $prodIds), $values[0]);
             $output->writeLn('<fg=red>' . $this->renderProduct($prod) . '</>');
             $toDel[] = $prod->id;
         }
     }
     $toAdd = [];
     if (!empty($instructions['add'])) {
         $output->writeLn('Da Aggiungere:');
         foreach ($instructions['add'] as $values) {
             $prod = $this->resolveProduct(new Product(), $values[0]);
             $output->writeLn('<fg=green>' . $this->renderProduct($prod) . '</>');
             $toAdd[] = $prod->id;
         }
     }
     $toNew = [];
     if (!empty($instructions['new'])) {
         foreach ($instructions['new'] as $values) {
             $prod = Product::where(['description' => $values[0], 'price' => $values[1], 'category' => $values[2]])->first();
             if (!empty($prod)) {
                 //il prodotto esiste
                 $output->writeLn('<fg=green>' . $this->renderProduct($prod) . '</>');
                 $toAdd[] = $prod->id;
             } else {
                 $output->writeLn('<fg=green>' . $values[0] . ' [NUOVO] - € ' . $values[1] . ' - ' . $values[2] . '</>');
                 $toNew[] = $values;
             }
         }
     }
     // --------------------------------------------------------------------
     //Suggestions
     if ($input->getOption('s')) {
         $output->writeLn('-------------');
         $output->writeLn('Suggerimenti');
         $print = function ($values, $color = 'green') use($output) {
             $toSearch = $values[0];
             $output->writeLn('');
             $output->writeLn('###############');
             if (count($values) == 1) {
                 $output->writeLn('# ' . $toSearch);
             } else {
                 $output->writeLn('# <fg=' . $color . '>++ ' . $toSearch . ' ++</>');
             }
             $output->writeLn('###############');
             $output->writeLn('');
             $this->getApplication()->find('product:search')->run(new ArrayInput(['search' => $toSearch]), $output);
         };
         foreach (array_merge(!empty($instructions['add']) ? $instructions['add'] : [], !empty($instructions['new']) ? $instructions['new'] : []) as $values) {
             $print($values, 'green');
         }
         foreach ($instructions['del'] as $values) {
             $print($values, 'red');
         }
         return;
     }
     // --------------------------------------------------------------------
     //collection
     $products = Product::whereIn('id', MenuProduct::where('menu_id', $menu->id)->get()->lists('product_id')->toArray())->get()->toArray();
     $collection = collect(array_map(function ($v) {
         return $this->toModel($v);
     }, $products));
     //tolgo
     $collection = $collection->reject(function ($item) use($toDel) {
         return in_array($item['id'], $toDel);
     });
     //aggiungo
     foreach ($toAdd as $id) {
         $collection->push(array_merge($this->toModel(Product::find($id)), ['add' => true]));
     }
     // --------------------------------------------------------------------
     //Ordino la Collection
     $grouped = $collection->groupBy(function ($item, $key) {
         return strtoupper($item['category']);
     });
     $orderedCat = ['Primi Piatti', 'Secondi di Pesce', 'Secondi di carne', 'Verdure, ortaggi e contorni', 'Piatti Vegetariani', 'Pane', 'Salumi', 'Formaggi', 'Panini Imbottiti', 'Frutta e Dessert', 'Contorni', 'Aggiunte', 'Bibite', 'Snack', 'Condimenti'];
     $completeCollection = collect([]);
     //ORDINAMENTO
     foreach ($orderedCat as $cat) {
         $perCategoryProducts = collect($grouped[strtoupper($cat)]);
         //dd($perCategoryProducts);
         $perCategoryProducts = $perCategoryProducts->sortBy('name');
         foreach ($perCategoryProducts as $p) {
             if ($p['lastTimeInMenu'] == 0) {
                 $p['name'] .= ' [NUOVO]';
             }
             if (!empty($p['add'])) {
                 $p['id'] = '<fg=green>' . $p['id'];
                 $p['category'] = $p['category'] . '</>';
             }
             $completeCollection->push($p);
         }
     }
     //aggiungo NUOVI come primi
     foreach ($toNew as $values) {
         $completeCollection->prepend(['id' => '<fg=green>', 'name' => $values[0] .= ' [NUOVO]', 'price' => $values[1], 'category' => $values[2] . '</>', 'lastTimeInMenu' => 0, 'add' => true]);
     }
     // --------------------------------------------------------------------
     //CODE INJECTION
     // $completeCollection->push([
     //     'id' => '',
     //     'name' => '<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script><script>$(document).ready(function(){$("head").append("<div>hello</div>")})</script>',
     //     'price' => 0,
     //     'category' => 'code',
     //     'lastTimeInMenu' => 0,
     //     'add' => true,
     // ]);
     // --------------------------------------------------------------------
     //RENDER TABLE
     $renderingCollection = $completeCollection->filter(function ($item) {
         return $item['category'] != 'code';
     });
     $table = new Table($output);
     $table->setHeaders(array('Codice', 'Descrizione', 'Prezzo', 'Categoria'))->setRows($renderingCollection);
     $table->render();
     //dd(get_class_methods($table));
     // --------------------------------------------------------------------
     $question = new ConfirmationQuestion('Posso inviare? -> ', false);
     if (!$this->getHelper('question')->ask($input, $output, $question)) {
         $output->writeLn('<fg=red>Skip</>');
         return;
     }
     //formatta csv per mosaicoon
     // Codice;Descrizione;Prezzo;Categoria
     // AFOR1;Anelletti al forno con Ragù;€3,00;Primi Piatti
     $csv = 'Codice;Descrizione;Prezzo;Categoria' . PHP_EOL;
     foreach ($completeCollection as $row) {
         $csv .= $row['id'] . ';' . $row['name'] . '; €' . str_replace('.', ',', $row['price']) . ';' . $row['category'] . PHP_EOL;
     }
     file_put_contents(APP_CWD . '/menu.csv', $csv);
     // --------------------------------------------------------------------
     //Invio Menu
     $gmail = new \Jambon\GmailClient\GmailClient();
     $resp = $gmail->sendEmail($from = ['name' => 'Giovanni Bonaccorso', 'email' => '*****@*****.**'], $to = ['name' => 'SERVIZIO MENSA MOSAICOON', 'email' => '*****@*****.**'], $subject = 'CARICA MENU', $message = null, $attachments = [['path' => APP_CWD . '/menu.csv', 'name' => 'menu.csv']]);
     $output->writeLn('<fg=green>Fatto!</>');
     $output->writeLn('<fg=green>A breve riceverai una risposta via email</>');
 }
コード例 #7
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $gmail = new \Jambon\GmailClient\GmailClient();
     $emails = $gmail->readEmails(['maxResults' => $input->getArgument('entries'), 'labelIds' => 'INBOX', 'includeSpamTrash' => true, 'q' => 'from:serviziomensa@mosaicoon.com invio ordine ' . $input->getArgument('extraString')], function (array $email) use($output) {
         $content = $email['body']['html'][0];
         // --------------------------------------------------------------------
         preg_match("/[0-9]{1,2}\\/[0-9]{1,2}\\/[0-9]{4}/", $content, $matched);
         list($d, $m, $y) = explode('/', $matched[0]);
         $menuDate = Carbon::parse("{$y}-{$m}-{$d} 00:00:00");
         //$menuDate = "{$y}-{$m}-{$d} 00:00:00";
         $output->writeLn("Importando Ordini del " . $matched[0]);
         // --------------------------------------------------------------------
         $agency = Agency::firstOrCreate(['name' => 'Mosaicoon']);
         $c = Order::where(['delivery_time' => $menuDate->copy()->addHours(13), 'agency_id' => $agency->id])->count();
         if ($c !== 0) {
             //ordine già registrato
             $output->writeLn("Ordine del " . $matched[0] . " GIA SALVATO");
             return;
         }
         //prendi menu del giorno
         try {
             $menu = Menu::where(['start_date' => $menuDate, 'type' => Menu::TYPE_PRANZO])->firstOrFail();
         } catch (\Exception $e) {
             $output->writeLn("Menu del " . $matched[0] . " NON PRESENTE");
             return;
         }
         $crawler = new \Symfony\Component\DomCrawler\Crawler();
         $crawler->addHTMLContent($content, 'UTF-8');
         $crawler->filter('table')->eq(1)->filter('tr')->each(function ($tr, $i) use($menu, $agency, $menuDate) {
             if ($i === 0) {
                 return;
             }
             $ordData = [];
             $tr->filter('td')->each(function ($td, $i) use(&$ordData) {
                 if ($i == 0) {
                     $ordData['user'] = $td->text();
                 } elseif ($i == 2) {
                     $ordData['product-name'] = trim(str_replace(['[NUOVO]', '(NUOVO)', '(Nuovo)'], null, $td->text()));
                 } elseif ($i == 3) {
                     $ordData['qta'] = (int) $td->text();
                 } elseif ($i == 1) {
                     $ordData['category'] = trim($td->text());
                 }
             });
             if ($ordData['user'] === 'TOTALE') {
                 return;
             }
             //prevent insert injection code
             if (in_array($ordData['category'], ['', null, 'code', 'c'])) {
                 return;
             }
             try {
                 $pid = $menu->menuProducts()->get()->lists('product_id');
                 $product = Product::whereIn('id', $pid)->where('description', '=', $ordData['product-name'])->firstOrFail();
             } catch (\Exception $e) {
                 //Prodotto Mancante
                 echo 'P';
                 return;
             }
             //dd($product);
             //da rivedere...
             $user = User::firstOrCreate(['agency_id' => $agency->id, 'display_name' => $ordData['user'], 'role' => User::ROLE_USER]);
             $order = Order::firstOrCreate(['user_id' => $user->id, 'agency_id' => $agency->id, 'delivery_time' => $menuDate->copy()->addHours(13)]);
             try {
                 $order->addMenuProduct($menu, $product, $ordData['qta']);
             } catch (\Exception $e) {
                 //Associazione NON TROVATA
                 echo 'X';
                 return;
             }
             echo '.';
         });
         $output->writeLn(" ");
     });
 }