Пример #1
1
 /**
  * [currency description]
  * @param  [type] $value    [description]
  * @param  [type] $currency [description]
  * @return [type]           [description]
  */
 public static function currency($value, $currency)
 {
     $number = \Cake\I18n\Number::currency($value, $currency);
     $formattedValue = preg_split('/(R\\$)/', $number);
     return 'R$ ' . $formattedValue[1];
 }
Пример #2
1
 public function pebble_data_request($order_id)
 {
     $this->layout = null;
     $order = $this->Orders->get($order_id, ["contain" => ["Products", "OrdersProducts", "OrderStatus", "Users"]]);
     $order->pebble_cancel_secret_key = md5($order->id);
     $this->Orders->save($order);
     $total_price = Number::currency($order->total_price, "USD");
     $data = ["user_name" => $order->user->name, "order_id" => $order->id, "order_status" => $order->order_status->name, "total_price" => $total_price, "pebble_cancel_secret_key" => $order->pebble_cancel_secret_key];
     echo json_encode($data);
     exit;
 }
 /**
  * compteResultat method
  *
  * @param string|null $id Client id.
  * @return void
  * @throws \Cake\Network\Exception\NotFoundException When record not found.
  */
 public function compteResultat($id = null)
 {
     if ($id == null) {
         $id = $this->Auth->user()['id_client'];
     }
     $tab = [];
     $tab['exploitation']['produit'] = $this->Operations->getCompteResultat($id, 'produit_exploitation');
     $tab['exploitation']['charge'] = $this->Operations->getCompteResultat($id, 'charge_exploitation');
     $tab['financier']['produit'] = $this->Operations->getCompteResultat($id, 'produit_financier');
     $tab['financier']['charge'] = $this->Operations->getCompteResultat($id, 'charge_financier');
     $tab['exceptionnel']['produit'] = $this->Operations->getCompteResultat($id, 'produit_exceptionnel');
     $tab['exceptionnel']['charge'] = $this->Operations->getCompteResultat($id, 'charge_exceptionnel');
     $tab['resultat']['exploitation'] = $tab['exploitation']['produit'] - $tab['exploitation']['charge'];
     $tab['resultat']['financier'] = $tab['financier']['produit'] - $tab['financier']['charge'];
     $tab['resultat']['exceptionnel'] = $tab['exceptionnel']['produit'] - $tab['exceptionnel']['charge'];
     $tab['resultat']['net'] = $tab['resultat']['exceptionnel'] + $tab['resultat']['financier'] + $tab['resultat']['exploitation'];
     $query = $this->Operations->find('all');
     $equilibre = $query->select(['sum' => $query->func()->sum('montant')])->where(['id_client' => $id])->first()['sum'];
     if ($equilibre == 0) {
         $this->Flash->success('Vos opérations sont bien équilibrées.');
     } else {
         $this->Flash->error('Vos opérations ne sont pas équilibrées. Différences de ' . Number::currency(abs($equilibre)));
     }
     $this->set('tab', $tab);
 }
Пример #4
0
 /**
  * Subscribe to a Premium offer.
  *
  * @return \Cake\Network\Response
  */
 public function subscribe()
 {
     $this->loadComponent('Transaction');
     $this->loadModel('PremiumOffers');
     $this->loadModel('PremiumDiscounts');
     $offer = $this->PremiumOffers->find('offerByPeriod', ['period' => $this->request->data['period']]);
     if (!$offer) {
         $this->Flash->error(__("This offer does not exist."));
         return $this->redirect(['action' => 'index']);
     }
     //Check the discount code.
     $discountPercentage = null;
     if (!empty($this->request->data['discount'])) {
         $discount = $this->PremiumDiscounts->find('discountByCodeAndOffer', ['code' => $this->request->data['discount'], 'offer_id' => $offer->id]);
         if (is_null($discount) || !$this->PremiumDiscounts->isDiscountValid($discount)) {
             $this->Flash->error(__("Your discount code isn't valid or has already been used."));
             return $this->redirect(['action' => 'index']);
         } else {
             $discountPercentage = $discount->discount;
         }
     }
     $price = Number::format($offer->price, ['locale' => 'en_US']);
     $tax = Number::format($offer->tax, ['locale' => 'en_US']);
     $custom = ['user_id' => $this->request->session()->read('Auth.User.id'), 'offer_id' => $offer->id, 'period' => $offer->period, 'discount_id' => isset($discount) ? $discount->id : null];
     $paypalUrl = $this->Transaction->getPaypalUrl($price, $tax, __n('Premium {0} month', 'Premium {0} months', $offer->period, $offer->period), http_build_query($custom), $discountPercentage);
     if (!$paypalUrl) {
         $this->Flash->error(__("Unable to get the Paypal URL, please contact an administrator or try again later."));
         return $this->redirect(['action' => 'index']);
     }
     $this->redirect($paypalUrl);
 }
Пример #5
0
 /**
  * tearDown method
  *
  * @return void
  */
 public function tearDown()
 {
     parent::tearDown();
     unset($this->Number);
     I18n::locale($this->locale);
     Number::defaultCurrency(false);
 }
Пример #6
0
 /**
  * Initialization hook method.
  *
  * Use this method to add common initialization code like loading components.
  *
  * e.g. `$this->loadComponent('Security');`
  *
  * @return void
  */
 public function initialize()
 {
     parent::initialize();
     $this->loadComponent('RequestHandler');
     $this->loadComponent('Flash');
     $this->loadComponent('Auth', ['loginRedirect' => ['controller' => 'Annonces', 'action' => 'index'], 'logoutRedirect' => ['controller' => 'Users', 'action' => 'login'], 'authenticate' => ['Form' => ['fields' => ['username' => 'username', 'password' => 'password']]]]);
     Number::defaultCurrency('EUR');
 }
Пример #7
0
 /**
  * Re-count the number of user and find the latest user and write it in the Cache.
  *
  * @param \Cake\Event\Event $event The event that was fired.
  *
  * @return array|false
  */
 public function newUserStats(Event $event)
 {
     $this->Users = TableRegistry::get('Users');
     $totalUsers = $this->Users->find()->count();
     $totalUsers = Number::format($totalUsers);
     $lastRegistered = $this->Users->find('short')->order(['Users.created' => 'DESC'])->first();
     $data = [];
     $data['TotalUsers'] = $totalUsers;
     $data['LastRegistered'] = $lastRegistered;
     if ($this->_writeCache($data, 'Users')) {
         return $data;
     }
     return false;
 }
Пример #8
0
 /**
  * Index page.
  *
  * @return void
  */
 public function home()
 {
     $this->loadModel('Users');
     $this->loadModel('PremiumTransactions');
     $usersCount = Number::format($this->Users->find()->where(['end_subscription >' => new Time()])->count());
     $premiumTransactions = $this->PremiumTransactions->find()->select(['price'])->hydrate(false)->toArray();
     $amountTotal = array_sum(Hash::extract($premiumTransactions, '{n}.price'));
     $registeredDiscounts = $this->PremiumTransactions->find()->where(function ($exp) {
         return $exp->isNotNull('premium_discount_id');
     })->count();
     $discounts = $this->PremiumTransactions->find()->contain(['PremiumDiscounts', 'PremiumOffers'])->where(function ($exp) {
         return $exp->isNotNull('premium_discount_id');
     })->toArray();
     $discountAmountTotal = [];
     foreach ($discounts as $discount) {
         array_push($discountAmountTotal, $discount->discount);
     }
     $discountAmountTotal = array_sum($discountAmountTotal);
     $this->set(compact('usersCount', 'amountTotal', 'registeredDiscounts', 'discountAmountTotal'));
 }
 protected function float($field, $options = [])
 {
     return Number::format($this->helper->entity->{$field}, $this->helper->CrudData->attributes($field, 'number'));
 }
Пример #10
0
 /**
  * test config()
  *
  * @return void
  */
 public function testConfig()
 {
     $result = $this->Number->currency(15000, 'INR', ['locale' => 'en_IN']);
     $this->assertEquals('₹ 15,000.00', $result);
     Number::config('en_IN', \NumberFormatter::CURRENCY, ['pattern' => '¤ #,##,##0']);
     $result = $this->Number->currency(15000, 'INR', ['locale' => 'en_IN']);
     $this->assertEquals('₹ 15,000', $result);
 }
Пример #11
0
 /**
  * Get the summary for the panel.
  *
  * @return string
  */
 public function summary()
 {
     $time = Number::precision(DebugTimer::requestTime(), 2) . ' s';
     $memory = Number::toReadableSize(DebugMemory::getPeak());
     return "{$time} / {$memory}";
 }
Пример #12
0
 /**
  * Check if the discount is valid.
  *
  * @param array $custom The custom data passed to Paypal.
  * @param float $mcGross Price paid by the buyer.
  * @param float $tax The tax added to the price.
  * @param float $discount The discount applied to the price without taxes.
  *
  * @return bool
  */
 protected function _isDiscountValid($custom, $mcGross, $tax, $discount)
 {
     $discount = Number::format($discount, ['precision' => 2, 'locale' => 'en_US']);
     if ($discount == 0.0 && !isset($custom['discount_id'])) {
         return true;
     }
     $this->_controller->loadModel('PremiumDiscounts');
     $checkDiscount = $this->_controller->PremiumDiscounts->find('discountByIdAndOffer', ['id' => $custom['discount_id'], 'offer_id' => $custom['offer_id']]);
     if (!$checkDiscount) {
         return false;
     }
     $total = $mcGross - $tax + $discount;
     $offerDiscount = Number::format(round($checkDiscount->discount / 100, 2) * $total, ['precision' => 2, 'locale' => 'en_US']);
     if ($offerDiscount != $discount) {
         Log::error(__('The discount offer {0} does not match with the Paypal discount {1}.', $offerDiscount, $discount), 'paypal');
         return false;
     }
     //Update the discount.
     $this->_updateDiscount($checkDiscount);
     return true;
 }
Пример #13
0
 /**
  * Returns a formatted-for-humans file size.
  *
  * @param int $size Size in bytes
  * @return string Human readable size
  * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/number.html#NumberHelper::toReadableSize
  */
 public static function _toReadableSize($size, $decimals = '.')
 {
     $size = parent::toReadableSize($size);
     if ($decimals !== '.') {
         $size = str_replace('.', $decimals, $size);
     }
     return $size;
 }
Пример #14
0
 /**
  * Index page.
  *
  * @return void
  */
 public function home()
 {
     if (Configure::read('Analytics.enabled') === true) {
         $httpAdapter = new CurlHttpAdapter();
         $client = new Client(Configure::read('Analytics.client_id'), Configure::read('Analytics.private_key'), $httpAdapter);
         $service = new Service($client);
         $statistics = Cache::remember('statistics', function () use($service) {
             $statistics = new Query(Configure::read('Analytics.profile_id'));
             $statistics->setStartDate(new \DateTime(Configure::read('Analytics.start_date')))->setEndDate(new \DateTime())->setMetrics(array('ga:visits', 'ga:visitors', 'ga:pageviews', 'ga:pageviewsPerVisit', 'ga:avgtimeOnSite', 'ga:visitBounceRate', 'ga:percentNewVisits'));
             return $service->query($statistics);
         }, 'analytics');
         $browsers = Cache::remember('browsers', function () use($service) {
             $browsers = new Query(Configure::read('Analytics.profile_id'));
             $browsers->setStartDate(new \DateTime(Configure::read('Analytics.start_date')))->setEndDate(new \DateTime())->setDimensions(array('ga:browser'))->setMetrics(array('ga:pageviews'))->setSorts(array('ga:pageviews'))->setFilters(array('ga:browser==Chrome,ga:browser==Firefox,ga:browser==Internet Explorer,ga:browser==Safari,ga:browser==Opera'));
             return $service->query($browsers);
         }, 'analytics');
         $continents = Cache::remember('continents', function () use($service) {
             $continentsRows = new Query(Configure::read('Analytics.profile_id'));
             $continentsRows->setStartDate(new \DateTime(Configure::read('Analytics.start_date')))->setEndDate(new \DateTime())->setDimensions(array('ga:continent'))->setMetrics(array('ga:visitors'))->setSorts(array('ga:visitors'))->setFilters(array('ga:continent==Africa,ga:continent==Americas,ga:continent==Asia,ga:continent==Europe,ga:continent==Oceania'));
             $continentsRows = $service->query($continentsRows);
             $color = new Color("1abc9c");
             $light = 1;
             $continents = [];
             foreach (array_reverse($continentsRows->getRows()) as $continentRow) {
                 $continent = [];
                 $continent['label'] = $continentRow[0];
                 $continent['data'] = $continentRow[1];
                 $continent['color'] = '#' . $color->lighten($light);
                 array_push($continents, $continent);
                 $light += 10;
             }
             return $continents;
         }, 'analytics');
         $graphVisitors = Cache::remember('graphVisitors', function () use($service) {
             $graphVisitors = new Query(Configure::read('Analytics.profile_id'));
             $graphVisitors->setStartDate(new \DateTime('-7 days'))->setEndDate(new \DateTime())->setDimensions(array('ga:date'))->setMetrics(array('ga:visits', 'ga:pageviews'))->setSorts(array('ga:date'));
             return $service->query($graphVisitors);
         }, 'analytics');
         $this->set(compact('statistics', 'browsers', 'continents', 'graphVisitors'));
     }
     $this->loadModel('Users');
     //UsersGraph
     $usersGraphCount = $this->Users->find('all')->select(['date' => 'DATE_FORMAT(created,\'%d-%m-%Y\')', 'count' => 'COUNT(id)'])->group('DATE(created)')->order(['date' => 'desc'])->where(['UNIX_TIMESTAMP(DATE(created)) >' => (new \DateTime('-8 days'))->getTimestamp()])->toArray();
     $usersGraph = array();
     //Fill the new array with the date of the 8 past days and give them the value 0.
     for ($i = 0; $i < 8; $i++) {
         $date = new \DateTime("{$i} days ago");
         $usersGraph[$date->format('d-m-Y')] = 0;
     }
     //Foreach value that we got in the database, parse the array by the key date,
     //and if the key exist, attribute the new value.
     foreach ($usersGraphCount as $user) {
         $usersGraph[$user->date] = intval($user->count);
     }
     $usersGraph = array_reverse($usersGraph);
     $usersCount = Number::format($this->Users->find()->count());
     $this->loadModel('BlogArticles');
     $articlesCount = Number::format($this->BlogArticles->find()->count());
     $this->loadModel('BlogArticlesComments');
     $commentsCount = Number::format($this->BlogArticlesComments->find()->count());
     $this->loadModel('BlogCategories');
     $categoriesCount = Number::format($this->BlogCategories->find()->count());
     $this->set(compact('usersCount', 'articlesCount', 'commentsCount', 'categoriesCount', 'usersGraph'));
 }
Пример #15
0
 /**
  * Save file
  * @param null $order_id
  */
 public function file($order_id = null)
 {
     $file_data = $this->request->data('file');
     $file_name = new File($file_data['name']);
     $name = preg_replace('/\\s+/', '_', $file_name->name()) . '.' . $file_name->ext();
     if (!move_uploaded_file($file_data['tmp_name'], 'files/' . $name)) {
         throw new InternalErrorException(json_encode($file_data));
     }
     $fileObj = $this->Files->newEntity(['name' => $name, 'order_id' => $order_id, 'size' => Number::toReadableSize($file_data['size'])]);
     $file = $this->Files->save($fileObj);
     $this->set('row', $file);
     $this->set('_serialize', ['row']);
 }
Пример #16
0
 /**
  * Display some statistics about Finished Jobs.
  *
  * @return void
  */
 public function stats()
 {
     $this->out('Jobs currenty in the Queue:');
     $types = $this->QueuedTasks->getTypes()->toArray();
     foreach ($types as $type) {
         $this->out("      " . str_pad($type, 20, ' ', STR_PAD_RIGHT) . ": " . $this->QueuedTasks->getLength($type));
     }
     $this->hr();
     $this->out('Total unfinished Jobs      : ' . $this->QueuedTasks->getLength());
     $this->hr();
     $this->out('Finished Job Statistics:');
     $data = $this->QueuedTasks->getStats();
     foreach ($data as $item) {
         $this->out(" " . $item['jobtype'] . ": ");
         $this->out("   Finished Jobs in Database: " . $item['num']);
         $this->out("   Average Job existence    : " . str_pad(Number::precision($item['alltime']), 8, ' ', STR_PAD_LEFT) . 's');
         $this->out("   Average Execution delay  : " . str_pad(Number::precision($item['fetchdelay']), 8, ' ', STR_PAD_LEFT) . 's');
         $this->out("   Average Execution time   : " . str_pad(Number::precision($item['runtime']), 8, ' ', STR_PAD_LEFT) . 's');
     }
 }
Пример #17
0
 /**
  * Get the discount of the transaction.
  *
  * @return float
  */
 protected function _getDiscount()
 {
     return Number::format($this->premium_discount->discount * $this->premium_offer->price / 100, ['precision' => 2, 'locale' => 'en_US']);
 }
Пример #18
0
 /**
  * Get the number of likes formatted.
  *
  * @return string
  */
 protected function _getLikeCountFormat()
 {
     return Number::format($this->like_count);
 }
Пример #19
0
 protected function _getDuration()
 {
     $seconds = $this->_properties['time_out']->toUnixString() - $this->_properties['time_in']->toUnixString();
     return Number::precision($seconds / HOUR, 2);
 }
Пример #20
0
 /**
  * Lists database backups
  * @return void
  * @uses DatabaseBackup\Utility\Backup::index()
  */
 public function index()
 {
     try {
         //Gets alla files
         $files = Backup::index();
         $this->out(__d('database_backup', 'Backup files found: {0}', count($files)));
         if (!empty($files)) {
             //Re-indexes and filters
             $files = array_map(function ($file) {
                 return [$file->filename, $file->compression, Number::toReadableSize($file->size), $file->datetime];
             }, $files);
             $this->helper('table')->output(array_merge([[__d('database_backup', 'Filename'), __d('database_backup', 'Compression'), __d('database_backup', 'Size'), __d('database_backup', 'Datetime')]], $files));
         }
     } catch (InternalErrorException $e) {
         $this->abort($e->getMessage());
     }
 }
Пример #21
0
 /**
  * Getter/setter for default currency
  *
  * @param string|bool $currency Default currency string to be used by currency()
  * if $currency argument is not provided. If boolean false is passed, it will clear the
  * currently stored value
  * @return string Currency
  */
 public function defaultCurrency($currency)
 {
     return $this->_engine->defaultCurrency($currency);
 }
Пример #22
0
 /**
  * Get the number of articles formatted.
  *
  * @return string
  */
 protected function _getArticleCountFormat()
 {
     return Number::format($this->article_count);
 }
Пример #23
0
 /**
  * Formats a number into locale specific ordinal suffix.
  *
  * @param int|float $value An integer
  * @param array $options An array with options.
  * @return string formatted number
  */
 public function ordinal($value, array $options = [])
 {
     return $this->_engine->ordinal($value, $options);
 }
 /**
  * Validates the error value that comes with the file input file.
  *
  * @param array $value
  * @param array $options.
  * @return boolean True on success, if false the error message is set to the models field and also set in $this->_uploadError
  */
 public function uploadErrors($value, $options = array())
 {
     $defaults = ['allowNoFileError' => true];
     if (is_array($options)) {
         $options = array_merge($defaults, $options);
     } else {
         $options = $defaults;
     }
     if (isset($value['error']) && !is_null($value['error'])) {
         switch ($value['error']) {
             case UPLOAD_ERR_OK:
                 return true;
             case UPLOAD_ERR_INI_SIZE:
                 $this->_uploadError = __d('file_storage', 'The uploaded file exceeds limit of %s.', Number::toReadableSize(ini_get('upload_max_filesize')));
                 return false;
             case UPLOAD_ERR_FORM_SIZE:
                 $this->_uploadError = __d('file_storage', 'The uploaded file is to big, please choose a smaller file or try to compress it.');
                 return false;
             case UPLOAD_ERR_PARTIAL:
                 $this->_uploadError = __d('file_storage', 'The uploaded file was only partially uploaded.');
                 return false;
             case UPLOAD_ERR_NO_FILE:
                 if ($options['allowNoFileError'] === false) {
                     $this->_uploadError = __d('file_storage', 'No file was uploaded.');
                     return false;
                 }
                 return true;
             case UPLOAD_ERR_NO_TMP_DIR:
                 $this->_uploadError = __d('file_storage', 'The remote server has no temporary folder for file uploads. Please contact the site admin.');
                 return false;
             case UPLOAD_ERR_CANT_WRITE:
                 $this->_uploadError = __d('file_storage', 'Failed to write file to disk. Please contact the site admin.');
                 return false;
             case UPLOAD_ERR_EXTENSION:
                 $this->_uploadError = __d('file_storage', 'File upload stopped by extension. Please contact the site admin.');
                 return false;
             default:
                 $this->_uploadError = __d('file_storage', 'Unknown File Error. Please contact the site admin.');
                 return false;
         }
         return false;
     }
     $this->_uploadError = '';
     return true;
 }