Пример #1
1
 protected function storeFull($json)
 {
     $categories = json_decode($json, true);
     // grab categories from the database
     $dbCategories = collect(DB::table('categories')->get(['cSlug']))->keyBy('cSlug')->toArray();
     // grab an array of columns in the categories table
     $columns = DB::select('select COLUMN_NAME as `column` from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = \'fmtc_categories\'');
     // set the counters for reporting
     $insertCount = 0;
     $removeCount = 0;
     // walk through the categories from a merchant feed
     $jsonCategoryIds = [];
     foreach ($categories as $category) {
         // is the category missing from the database?
         if (!isset($dbCategories[$category['cSlug']])) {
             // insert it (this is faster than building an insert queue and bulk inserting)
             DB::table('categories')->insert($this->formatForInsertion($category, $columns));
             $insertCount++;
         }
         // collect an array of ids to aid in the remove	queue
         $jsonCategoryIds[] = $category['cSlug'];
     }
     // remove old categories showing up in the database but not in the new merchant feed.
     $removeQueue = array_diff(array_keys($dbCategories), $jsonCategoryIds);
     $removeCount = count($removeQueue);
     foreach ($removeQueue as $categoryId) {
         DB::table('categories')->where('cSlug', $categoryId)->delete();
     }
     //---- debugging
     // debug($removeCount . ' removed');
     // debug($insertCount . ' inserted');
     //-----
     return true;
 }
Пример #2
0
 public function category($idCategory)
 {
     $getCategory = $this->model_thread->get_category($idCategory);
     foreach ($getCategory as $cat) {
         $data['category'] = $cat->category_name;
     }
     $user = sentinel()->getUser();
     $daerahUser = $user->profile->desa_id;
     if ($this->checkTA() == TRUE) {
         $data['addTopic'] = anchor('topic/create', '<i class="fa fa-plus"></i> Topic Baru', 'class="btn btn-primary btn-sm"');
         $data['dashTopic'] = anchor('topic/', 'Your Topics', 'class="btn btn-primary btn-sm"');
         $data['draftSide'] = $this->model_thread->get_all_drafts($user->id);
         $data['tenagaAhli'] = $user->id;
         $data['threadSide'] = $this->model_thread->get_all_threads($daerahUser, $user->id);
         $threads = collect($this->model_thread->get_threads_category($idCategory, $user->id));
     } else {
         $data['threadSide'] = $this->model_thread->get_threads_by_user($daerahUser, $user->id);
         $threads = collect($this->model_thread->get_threads_category_by_user($idCategory, $user->id, $daerahUser));
     }
     $data['categoryUser'] = $this->model_thread->get_all_category_user();
     $data['authorSide'] = $this->model_thread->get_thread_from_author($user->id);
     $data['comments'] = $this->model_thread->get_count_reply();
     $data['visitors'] = $this->model_visitor->get_visitors();
     $data['categoriesHead'] = $getCategory;
     $data['categoriesSide'] = $this->model_thread->get_categories();
     $data['topics'] = $this->model_topic->get_approved_topics();
     $data['closeThreads'] = $this->model_thread->get_close_threads($user->id);
     $data['threadMembers'] = $this->model_thread->get_thread_members();
     $data['commentsSide'] = $this->model_thread->get_comments_from_author($user->id);
     $data['userID'] = $user->id;
     $data['threads'] = pagination($threads, 10, 'thread/category/' . $idCategory, 'bootstrap_md');
     $this->load->view('thread/all_threads', $data);
 }
Пример #3
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store(Request $request)
 {
     // error_log("------------------------------------------------------");
     $Mailer = new Email();
     $Mailer->email = $request['email'];
     /* $validator class with method fails() */
     $validator = Validator::make($request->all(), ['email' => 'required|email']);
     /* $isNewEmail =
                true: no email found in db
                false: duplicate email found in db
        */
     $isNewEmail = collect($Mailer->where('email', $Mailer->email)->get())->isEmpty() ? true : false;
     if ($validator->fails()) {
         error_log(json_encode(['error' => ['invalid_email' => $request->all()]]));
         return response()->json(['error' => 'E-mail is invalid'])->setCallback($request->input('callback'));
     } elseif (!$isNewEmail) {
         error_log(json_encode(['error' => ['duplicate_email' => $request->all()]]));
         return response()->json(['error' => 'E-mail is marked as being subscribed'])->setCallback($request->input('callback'));
         return redirect('/')->withErrors($validator)->withInput();
     } else {
         error_log(json_encode(['mailer' => ['newEmail' => $Mailer]]));
         // soon
         $Scribe = $this->subscribe($Mailer->email);
         // soon
         error_log(json_encode(['scribe' => $Scribe]));
         $Mailer->save();
         return response()->json(['success' => true])->setCallback($request->input('callback'));
     }
 }
Пример #4
0
 public function getEjercicioRm($rm)
 {
     $ejercicio_rm = collect(['rm' => $rm->rm]);
     $ejercicio_rm->put('objetivo', $rm->objetivo->objetivo);
     $ejercicio_rm->put('cog', $rm->cog->cog);
     $ejercicio_rm->put('d_cog', $rm->cog->d_cog);
     $ejercicio_rm->put('presupuestado', $rm->monto);
     $compensado_origen = CompensaOrigen::where('rm_id', $rm->id)->sum('monto');
     $compensado_destino = CompensaDestino::where('rm_id', $rm->id)->sum('monto');
     $compensado = round($compensado_destino, 2) - round($compensado_origen, 2);
     $ejercicio_rm->put('compensado', $compensado);
     $rm_objeto = Rm::find($rm->id);
     $ejercido = $this->getMontoEjercido($rm_objeto);
     $ejercicio_rm->put('ejercido', $ejercido);
     $reintegros_df = $this->getMontoReintegrosDF($rm_objeto);
     $ejercicio_rm->put('reintegros_df', $reintegros_df);
     //-- Reservado --//
     $reqs_id = Req::where('proyecto_id', $rm->proyecto_id)->where('estatus', 'Autorizada')->lists('id')->all();
     $reservado_reqs = round($rm_objeto->articulos()->whereIn('req_id', $reqs_id)->sum('articulo_rm.monto'), 2);
     $solicitudes_id = Solicitud::where('proyecto_id', $rm->proyecto_id)->where('estatus', 'Autorizada')->lists('id')->all();
     $reservado_solicitudes = round($rm_objeto->solicitudes()->whereIn('solicitud_id', $solicitudes_id)->sum('rm_solicitud.monto'), 2);
     $reservado = $reservado_reqs + $reservado_solicitudes;
     $ejercicio_rm->put('reservado', $reservado);
     $saldo = $ejercicio_rm->get('presupuestado') + $ejercicio_rm->get('compensado') - $ejercicio_rm->get('ejercido') - $ejercicio_rm->get('reservado');
     $ejercicio_rm->put('saldo', round($saldo, 2));
     return $ejercicio_rm;
 }
Пример #5
0
 /**
  * Create a workout.
  *
  * @todo Array-validate the instances.
  *
  * @param Request $request
  * @return Model
  */
 public function create(Request $request)
 {
     $this->validate($request, ['date' => 'required|date', 'name' => 'sometimes|max:100', 'done' => 'required|boolean', 'instances' => 'array']);
     $workout = $this->user->workouts()->create($request->except('instances'));
     $instances = $workout->instances()->createMany($request->get('instances'));
     return $workout->setRelation('instances', collect($instances));
 }
 public function timeLine()
 {
     $tags = Auth::user()->tags()->get();
     $posts = collect([]);
     foreach ($tags as $tag) {
         foreach ($tag->post()->get() as $post) {
             if (!Auth::user()->type) {
                 if (!$post->private) {
                     $posts->push($post);
                 } else {
                     if ($post->user_id == Auth::id()) {
                         $posts->push($post);
                     }
                 }
             } else {
                 $posts->push($post);
             }
         }
     }
     $posts = new Paginator($posts->unique('id'), 10);
     if (strpos(redirect()->back()->getTargetUrl(), 'login') === false) {
         return view('welcome', compact('posts', 'tags'));
     } else {
         return view('welcome', compact('posts', 'tags'))->with('message', 'Welcome ' . Auth::user()->fullName());
     }
 }
Пример #7
0
 public function rechazadas($q)
 {
     $url = 'https://docs.google.com/spreadsheets/d/1qxVqiUQNXyl26pY7f16OP5oWSCbp4wmykwgAJi762bc/pub?output=csv';
     $headers = false;
     $list = array();
     // open file for reading
     if (($handle = fopen($url, "r")) !== FALSE) {
         while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
             if ($headers) {
                 $totalrows = count($data) - 1;
                 $temp = array();
                 for ($row = 0; $row <= $totalrows; $row++) {
                     $temp[$headers[$row]] = $data[$row];
                 }
                 $list[] = $temp;
             } else {
                 $headers = $data;
             }
         }
         fclose($handle);
     }
     $collection = collect($list)->reject(function ($r) use($q) {
         return !(strpos(strtolower($r['materia_resumen']), strtolower($q)) > -1);
     });
     $resp = array('q' => $q, 'list' => $collection);
     return response()->json($resp);
 }
Пример #8
0
 /**
  * Remove unused avatar files from disk.
  *
  * @return void
  */
 private function purgeOldAvatars()
 {
     // Build up a list of all avatar images
     $avatars = glob(public_path() . '/upload/*/*.*');
     // Remove the public_path() from the path so that they match values in the DB
     array_walk($avatars, function (&$avatar) {
         $avatar = str_replace(public_path(), '', $avatar);
     });
     $all_avatars = collect($avatars);
     // Get all avatars currently assigned
     $current_avatars = DB::table('users')->whereNotNull('avatar')->lists('avatar');
     // Compare the 2 collections get a list of avatars which are no longer assigned
     $orphan_avatars = $all_avatars->diff($current_avatars);
     $this->info('Found ' . $orphan_avatars->count() . ' orphaned avatars');
     // Now loop through the avatars and delete them from storage
     foreach ($orphan_avatars as $avatar) {
         $avatarPath = public_path() . $avatar;
         // Don't delete recently created files as they could be temp files from the uploader
         if (filemtime($avatarPath) > strtotime('-15 minutes')) {
             $this->info('Skipping ' . $avatar);
             continue;
         }
         if (!unlink($avatarPath)) {
             $this->error('Failed to delete ' . $avatar);
         } else {
             $this->info('Deleted ' . $avatar);
         }
     }
 }
 /**
  * Get collection of all campaigns or a set of campaigns by ids from cache or
  * default to api request.
  *
  * @param  array  $ids
  * @return \Illuminate\Support\Collection
  */
 public function getAll(array $ids = [])
 {
     // @TODO: This is messy and needs another pass to simplify.
     if ($ids) {
         $keys = array_map([$this, 'setPrefix'], $ids);
         $campaigns = $this->retrieveMany($keys);
         if (!$campaigns) {
             $parameters['ids'] = implode(',', $ids);
             $campaigns = $this->phoenix->getAllCampaigns($parameters);
             $campaigns = collect($campaigns);
             if ($campaigns) {
                 $group = $campaigns->keyBy(function ($item) {
                     return $this->setPrefix($item->id);
                 })->all();
                 $this->storeMany($group);
             }
         } else {
             $campaigns = $this->resolveMissingItems($campaigns);
             $campaigns = collect(array_values($campaigns));
         }
         return $campaigns;
     }
     // @TODO: not sure if the following is actually a thing that is possible.
     // $campaigns = $this->phoenix->getAllCampaigns(['count' => 'all']);
     return new Collection();
 }
Пример #10
0
 /**
  * Module constructor.
  *
  * @param string $name
  * @param Application $application
  * @param array $options
  */
 public function __construct($name, Application $application, array $options = [])
 {
     $this->name = $name;
     $this->options = collect($options);
     $this->laravel = $application;
     $this->config = $application['modular.config'];
 }
 /**
  * Check the server requirements.
  *
  * @param  array  $requirements
  *
  * @return \Illuminate\Support\Collection
  */
 private function checkRequirements(array $requirements)
 {
     $requirements = array_combine($requirements, $requirements);
     return collect($requirements)->transform(function ($requirement) {
         return extension_loaded($requirement);
     });
 }
Пример #12
0
 public function article()
 {
     $cat_slider = config('privatepage_slider');
     $cat_1 = config('privatepage_category_1');
     $cat_2 = config('privatepage_category_2');
     $cat_3 = config('privatepage_category_3');
     $cat_4 = config('privatepage_category_4');
     $privatepage_slider_title = Model\Portal\Category::find($cat_slider);
     $privatepage_slider = Model\Portal\Article::categoryId($cat_slider);
     $privatepage_category_1_title = Model\Portal\Category::find($cat_1);
     $privatepage_category_1_a = Model\Portal\Article::onlyRegistered()->categoryId($cat_1)->take(3)->latest('date');
     $privatepage_category_1_b = Model\Portal\Article::onlyRegistered()->categoryId($cat_1)->take(3)->skip(2)->latest('date');
     $privatepage_category_2_title = Model\Portal\Category::find($cat_2);
     $privatepage_category_2_a = Model\Portal\Article::onlyRegistered()->categoryId($cat_2)->take(3)->latest('date');
     $privatepage_category_2_b = Model\Portal\Article::onlyRegistered()->categoryId($cat_2)->take(3)->skip(2)->latest('date');
     $privatepage_category_3_title = Model\Portal\Category::find($cat_3);
     $privatepage_category_3_a = Model\Portal\Article::onlyRegistered()->categoryId($cat_3)->take(3)->latest('date');
     $privatepage_category_3_b = Model\Portal\Article::onlyRegistered()->categoryId($cat_3)->take(3)->skip(2)->latest('date');
     $privatepage_category_4_title = Model\Portal\Category::find($cat_4);
     $privatepage_category_4_a = Model\Portal\Article::onlyRegistered()->categoryId($cat_4)->take(3)->latest('date');
     $privatepage_category_4_b = Model\Portal\Article::onlyRegistered()->categoryId($cat_4)->take(3)->skip(2)->latest('date');
     $data = array('privatepage_slider_title' => $privatepage_slider_title ? $privatepage_slider_title->name : '', 'privatepage_slider' => $privatepage_slider->count() ? $privatepage_slider->take(9)->latest('date')->get() : collect([]), 'privatepage_category_1_title' => $privatepage_category_1_title ? $privatepage_category_1_title->name : 'No Category', 'privatepage_category_1_a' => $privatepage_category_1_a->count() ? $privatepage_category_1_a->get() : collect([]), 'privatepage_category_1_b' => $privatepage_category_1_b->count() ? $privatepage_category_1_a->get() : collect([]), 'privatepage_category_2_title' => $privatepage_category_2_title ? $privatepage_category_2_title->name : 'No Category', 'privatepage_category_2_a' => $privatepage_category_2_a->count() ? $privatepage_category_2_a->get() : collect([]), 'privatepage_category_2_b' => $privatepage_category_2_b->count() ? $privatepage_category_2_b->get() : collect([]), 'privatepage_category_3_title' => $privatepage_category_3_title ? $privatepage_category_3_title->name : 'No Category', 'privatepage_category_3_a' => $privatepage_category_3_a->count() ? $privatepage_category_3_a->get() : collect([]), 'privatepage_category_3_b' => $privatepage_category_3_b->count() ? $privatepage_category_3_b->get() : collect([]), 'privatepage_category_4_title' => $privatepage_category_4_title ? $privatepage_category_4_title->name : 'No Category', 'privatepage_category_4_a' => $privatepage_category_4_a->count() ? $privatepage_category_4_a->get() : collect([]), 'privatepage_category_4_b' => $privatepage_category_4_b->count() ? $privatepage_category_4_b->get() : collect([]), 'links' => $this->Mod_link->read());
     $latests = Model\Portal\Article::registered()->latest('date')->limit(15)->get();
     $data['latest'] = $latests;
     $this->template->set('active', 'artikel');
     $this->template->set('sidebar', FALSE);
     $this->template->set_layout('privatepage');
     $this->template->build('articlePrivate', $data);
 }
Пример #13
0
 /**
  * @param $limits
  *
  * @return $this
  */
 public function limits($limits)
 {
     $this->limitations = collect($limits);
     $listener = new DoorkeeperListener();
     $listener->compare($this);
     return $this;
 }
Пример #14
0
 /**
  * Page Dashboard.
  */
 public function dashboard()
 {
     $nbacteurs = Actors::count();
     $nbcommentaires = Comments::count();
     $nbmovies = Movies::count();
     $nbseances = Sessions::count();
     $manager = new \MongoDB\Driver\Manager('mongodb://localhost:27017');
     $collection = new \MongoDB\Collection($manager, 'laravel', 'videos');
     $videos = collect($collection->find()->toArray())->shuffle();
     $collection = new \MongoDB\Collection($manager, 'laravel', 'stats');
     $youtubeinfo = collect($collection->find(['origin' => 'Youtube'])->toArray())->first();
     $collection = new \MongoDB\Collection($manager, 'laravel', 'stats');
     $tweeterinfo = collect($collection->find(['origin' => 'Twitter', 'type' => 'infos'])->toArray())->first();
     $actor = new Actors();
     // Je récpere mon modèle
     $comment = new Comments();
     // Je récpere mon modèle
     $movie = new Movies();
     // Je récpere mon modèle
     $session = new Sessions();
     // Je récpere mon modèle
     $user = new User();
     // Je récpere mon modèle
     $avgacteurs = $actor->getAvgActors();
     $avgnotecommentaire = $comment->getAvgNote();
     $avgnotepresse = $movie->getAvgNotePresse();
     $avghour = $session->getAvgHourDate();
     $seances = $session->getNextSession();
     $users = $user->getLastUsers();
     return view('Main/dashboard', ['avgnotecommentaire' => $avgnotecommentaire->avgnote, 'avgnotepresse' => $avgnotepresse->avgpress, 'avgacteurs' => $avgacteurs->age, 'videos' => $videos, 'video' => $videos[0], 'youtubeinfo' => $youtubeinfo->data, 'tweeterinfo' => $tweeterinfo['data'][0], 'youtubeinfodateupdated' => $youtubeinfo->created, 'tweeterinfodateupdated' => $tweeterinfo['created_at'], 'avghour' => $avghour->avghour, 'nbacteurs' => $nbacteurs, 'nbcommentaires' => $nbcommentaires, 'nbmovies' => $nbmovies, 'nbseances' => $nbseances, 'seances' => $seances, 'users' => $users]);
 }
 protected static function eventsToBeRecorded() : Collection
 {
     if (isset(static::$recordEvents)) {
         return collect(static::$recordEvents);
     }
     return collect(['created', 'updated', 'deleted']);
 }
Пример #16
0
 public function __invoke($keys, $value)
 {
     foreach ((array) $keys as $key) {
         $value = collect($value)->get($key);
     }
     return $value;
 }
Пример #17
0
 public function getBasked(Products $products, Slider $slider, Delivery $delivery)
 {
     if (Session::get('product')) {
         $this->data['delivery'] = $delivery->getDeliveryActive();
         $productsBasked = Session::get('product');
         $this->data['countProducts'] = collect($productsBasked);
         $productsId = '';
         $k = 0;
         foreach ($productsBasked as $id) {
             if ($k == 0) {
                 $productsId = $id['id'];
                 $k++;
             } else {
                 $productsId = $productsId . ' ,' . $id['id'];
             }
         }
         $this->data['bascedProducts'] = collect($products->getBascedProducts($productsId));
     } else {
         $this->data['bascedErrr'] = 'Корзина пуста';
     }
     $this->data['slides'] = $slider->getActive();
     $this->data['products'] = $products->getActive();
     if (\Auth::user()) {
         $this->data['name'] = \Auth::user()->name;
         $this->data['address'] = \Auth::user()->address;
         $this->data['email'] = \Auth::user()->email;
         $this->data['number'] = \Auth::user()->number;
     }
     return view('pages.cart', $this->data);
 }
Пример #18
0
 public function sequence($item)
 {
     $collections = collect($this->paginator->items());
     $index = $collections->search($item) + 1;
     $start = (request('page', 1) - 1) * $this->paginator->perPage();
     return $start + $index;
 }
Пример #19
0
 /**
  * Get all of the current views for the Spark installation.
  *
  * @return \Illuminate\Support\Collection
  */
 protected function newViewsInUpdate()
 {
     $views = collect((new Filesystem())->allFiles($this->downloadPath . '/resources/views'));
     return $views->reject(function ($view) {
         return file_exists($this->publishedViewPath($view));
     });
 }
Пример #20
0
 public function index()
 {
     $lectures = Lessontype::join('ocena', 'ocena.lessonTypeId', '=', 'lessontypes.id')->where('userId', Auth::user()->id)->groupBy('lessontypes.id')->get(array('lessonTypeId'));
     $les = Lessontype::all('id');
     $data1 = array();
     $data2 = array();
     foreach ($lectures as $key => $value) {
         $data1[] = $value->lessonTypeId;
     }
     foreach ($les as $key => $value) {
         $data2[] = $value->id;
     }
     $data1;
     $data2;
     $collection1 = collect($data1);
     $collection2 = collect($data2);
     $diff = $collection2->diff($collection1);
     $data3 = array();
     foreach ($diff as $key => $value) {
         $data3[] = $value;
     }
     $data3;
     $users = Auth::user();
     $lessonNo = Lessontype::whereIn('id', $data3)->get();
     $lessonYes = Lessontype::join('ocena', 'lessontypes.id', '=', 'lessonTypeId')->selectRaw('lessontypes.*, SUM(ocena.jedinica) as total')->groupBy('lessontypes.id')->get();
     return View::make('dashboard', compact('users', 'les', 'lessonYes', 'lessonNo'));
 }
 public static function createForSingleMonitor(array $monitorConfig) : Collection
 {
     return collect($monitorConfig['disks'])->map(function ($diskName) use($monitorConfig) {
         $backupDestination = BackupDestination::create($diskName, $monitorConfig['name']);
         return (new BackupDestinationStatus($backupDestination, $diskName))->setMaximumAgeOfNewestBackupInDays($monitorConfig['newestBackupsShouldNotBeOlderThanDays'])->setMaximumStorageUsageInMegabytes($monitorConfig['storageUsedMayNotBeHigherThanMegabytes']);
     });
 }
Пример #22
0
 /**
  * Update the business service types.
  *
  * @param Business $business
  * @param Request  $request
  *
  * @return Response
  */
 public function update(Business $business, Request $request)
 {
     logger()->info(__METHOD__);
     logger()->info(sprintf('businessId:%s', $business->id));
     $this->authorize('manageServices', $business);
     // BEGIN
     $servicetypeSheet = $request->input('servicetypes');
     $regex = '/(?P<name>[a-zA-Z\\d\\-\\ ]+)\\:(?P<description>[a-zA-Z\\d\\ ]+)/im';
     preg_match_all($regex, $servicetypeSheet, $matches, PREG_SET_ORDER);
     $publishing = collect($matches)->map(function ($item) {
         $data = array_only($item, ['name', 'description']);
         $data['slug'] = str_slug($data['name']);
         return $data;
     });
     foreach ($business->servicetypes as $servicetype) {
         if (!$this->isPublished($servicetype, $publishing)) {
             $servicetype->delete();
         }
     }
     foreach ($publishing as $servicetypeData) {
         $servicetype = ServiceType::firstOrNew($servicetypeData);
         $business->servicetypes()->save($servicetype);
     }
     flash()->success(trans('servicetype.msg.update.success'));
     return redirect()->route('manager.business.service.index', [$business]);
 }
Пример #23
0
 public function createOrder(User $user, Seller $seller, Collection $cartItems, Address $address = null, PaymentMethod $paymentMethod = null, $shippingOptions = [])
 {
     if ($address) {
         $address->setFeeType($seller);
     }
     // prepare order item models
     $orderItems = collect([]);
     foreach ($cartItems as $cartItem) {
         $orderItems->push($this->getOrderItemRepository()->getNew(compact('address', 'cartItem') + ['shippingOption' => $shippingOptions[$cartItem->id] ?? null]));
         $product = $cartItem->getProduct();
         $variant = $cartItem->getVariant();
         if (!is_null($product->stock)) {
             $product->stock = $product->stock - $cartItem->quantity;
             $product->save();
         }
         if ($variant and !is_null($variant->stock)) {
             $variant->stock = $variant->stock - $cartItem->quantity;
             $variant->save();
         }
         $this->getCartItemRepository()->delete($cartItem);
     }
     // prepare the order model
     $order = $this->getOrderRepository()->getNew(compact('seller', 'user', 'orderItems', 'address', 'paymentMethod'));
     // associate and persist
     list($saved, $order) = $this->getOrderRepository()->save($order);
     if ($saved) {
         foreach ($orderItems as $orderItem) {
             /** @var OrderItem $orderItem */
             $this->getOrderItemRepository()->save($orderItem->setOrder($order));
         }
     }
     return $order;
 }
 /**
  * Calculate the checksum of the file
  * As defined in the UOB documentation
  * @return String
  */
 public function getCheckSum()
 {
     $headers = [];
     $checksum = 0;
     $hashcode_index = 1;
     $record_no = 1;
     $lines = [];
     $batch_header = new UOBBatchHeader($this->beneficiaries, $this->configKey);
     $lines[] = $batch_header->getLine();
     foreach ($this->beneficiaries as $beneficiary) {
         $beneficiary_lines = UOBBeneficiaryFactory::create($beneficiary, $this->configKey);
         $lines[] = collect($beneficiary_lines->getLines())->first();
     }
     $batch_trailer = new UOBBatchTrailer($this->beneficiaries, $this->configKey);
     $lines[] = $batch_trailer->getLine();
     foreach ($lines as $line) {
         // printf("\nLine with value %s has length of %d", substr($line -> getString(),0, 100), strlen($line -> getString()));
         $string = $line->getString();
         $record_no++;
         $column_no = 1;
         for ($i = 0; $i < 900; $i++) {
             $byte_code = ord($string[$i]);
             if ($hashcode_index > 23) {
                 $hashcode_index = 1;
             }
             $checksum += $record_no + ($record_no + $column_no) * $byte_code * $this->getHashCodeArray($hashcode_index);
             $hashcode_index++;
             $column_no++;
         }
     }
     return $checksum;
 }
Пример #25
0
 /**
  * Parse an array of episodes into a collection of Episode models
  * @param  Array $episodes The array of episodes to parse
  * @return \Illuminate\Support\Collection 
  */
 private function parseEpisodes($episodes)
 {
     $episodes = collect($episodes);
     return $episodes->map(function ($episode) {
         return new Episode(['title' => array_get($episode, 'title'), 'subtitle' => array_get($episode, 'subtitle'), 'synopsis' => array_get($episode, 'synopses.medium'), 'release_date' => array_get($episode, 'release_date_time')]);
     });
 }
 public function Chart()
 {
     $yesterday = Carbon::now();
     $start = $yesterday->copy()->addDays(-7);
     $end = $yesterday->copy();
     // for query
     $startBetween = $start->format('Y-m-d');
     $endBetween = $end->format('Y-m-d');
     $dates = [];
     while ($start->lte($end)) {
         $dates[] = $start->copy();
         $start->addDay();
     }
     $dates = collect($dates)->forPage(1, 7);
     $reports = \App\Order::ReportGroup("(orders.`tanggal` BETWEEN '{$startBetween}' AND '{$endBetween}')", "GROUP BY tanggal");
     $reports = ConvertRawQueryToArray($reports);
     $dataLastWeek = [];
     $dataLabelLastWeek = [];
     foreach ($dates as $date) {
         $idx = array_search($date->format("Y-m-d"), array_column($reports, "tanggal"));
         $val = 0;
         if (false !== $idx) {
             $d = $reports[$idx];
             $val = $d['jumlah'];
         }
         $dataLabelLastWeek[] = $date->format('d M Y');
         $dataLastWeek[] = $val;
     }
     return ['label' => $dataLabelLastWeek, 'data' => $dataLastWeek];
 }
Пример #27
0
function tree_element($entry, $key, $all_entries, $crud)
{
    if (!isset($entry->tree_element_shown)) {
        // mark the element as shown
        $all_entries[$key]->tree_element_shown = true;
        $entry->tree_element_shown = true;
        // show the tree element
        echo '<li id="list_' . $entry->id . '">';
        echo '<div><span class="disclose"><span></span></span>' . $entry->{$crud['reorder_label']} . '</div>';
        // see if this element has any children
        $children = [];
        foreach ($all_entries as $key => $subentry) {
            if ($subentry->parent_id == $entry->id) {
                $children[] = $subentry;
            }
        }
        $children = collect($children)->sortBy('lft');
        // if it does have children, show them
        if (count($children)) {
            echo '<ol>';
            foreach ($children as $key => $child) {
                $children[$key] = tree_element($child, $child->id, $all_entries, $crud);
            }
            echo '</ol>';
        }
        echo '</li>';
    }
    return $entry;
}
 /**
  * @return String A string representation of the model
  */
 public function getString()
 {
     $line_strings = collect($this->lines)->map(function ($line) {
         return $line->getString();
     })->toArray();
     return implode("\r\n", $line_strings);
 }
Пример #29
0
 /**
  * Lists reporting jobs that have been scheduled for a channel or content owner.
  * Each resource in the response contains an id property, which specifies the ID
  * that YouTube uses to uniquely identify the job. You need that ID to retrieve
  * the list of reports that have been generated for the job or to delete the job.
  *
  * @param array $optParams
  *                              onBehalfOfContentOwner string
  *                              pageSize number
  *                              pageToken string
  *                              includeSystemManaged boolean
  *
  * @return array[JobResourceCollection, nextPageToken(string)]
  */
 public function all($optParams = [])
 {
     $response = $this->service->httpClient->get('/jobs', $optParams);
     return [collect($response->body['jobs'])->map(function ($job) {
         return new JobResource($job);
     }), $response->body['nextPageToken']];
 }
Пример #30
0
 public function index()
 {
     $data['users'] = sentinel()->findRoleBySlug('ta')->users->pluck('email', 'id')->toArray();
     $forum = collect(Model\Forum\Category::all());
     $data['categories'] = pagination($forum, '5', 'forum/category');
     $this->template->build('category_index', $data);
 }