/**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $this->info("This is involves downloading and storing several million records. This may take several hours...");
     if ($this->confirm('Do you wish to continue?')) {
         $this->info("Downloading historical financials...");
         $numberOfStocks = Stock::count();
         foreach (Stock::lists('stock_code') as $key => $stockCode) {
             if (!Historicals::where(['stock_code' => $stockCode, 'date' => '2015-08-11'])->first()) {
                 $historicalSheetUrl = "http://real-chart.finance.yahoo.com/table.csv?s=" . $stockCode . ".AX&d=7&e=12&f=2015&g=d&a=7&b=11&c=2015&ignore=.csv";
                 if (get_headers($historicalSheetUrl, 1)[0] == 'HTTP/1.1 200 OK') {
                     file_put_contents('database/files/spreadsheet.txt', trim(str_replace("Date,Open,High,Low,Close,Volume,Adj Close", "", file_get_contents($historicalSheetUrl))));
                     $spreadSheetFile = fopen('database/files/spreadsheet.txt', 'r');
                     $dailyTradeRecord = array();
                     while (!feof($spreadSheetFile)) {
                         $line = fgets($spreadSheetFile);
                         $pieces = explode(',', $line);
                         array_push($dailyTradeRecord, array('stock_code' => $stockCode, 'date' => $pieces[0], 'open' => $pieces[1], 'high' => $pieces[2], 'low' => $pieces[3], 'close' => $pieces[4], 'volume' => $pieces[5], 'adj_close' => $pieces[6], 'created_at' => date("Y-m-d H:i:s"), 'updated_at' => date("Y-m-d H:i:s")));
                     }
                     //\DB::table('historicals')->where('stock_code', $stockCode)->delete();
                     \DB::table('historicals')->insert($dailyTradeRecord);
                 }
             }
             $this->info("Completed: " . $stockCode . " " . ($key + 1) . "/" . $numberOfStocks . " - " . round(($key + 1) * (100 / $numberOfStocks), 2) . "%");
         }
         $this->info("The historical financials have been downloaded.");
     }
 }
Пример #2
0
 /**
  * O método precisa informar uma lista de produtos
  * @return {view}
  */
 public function create()
 {
     $stocks = Stock::all();
     $customers = Customer::all();
     $employees = Employee::all();
     return view('pages.new_sale', ['stocks' => $stocks, 'customers' => $customers, 'employees' => $employees]);
 }
 public function stock($stockCode, $timeFrame, $dataType)
 {
     $graphData = Stock::getGraphData($stockCode, $timeFrame, $dataType);
     $prices = \Lava::DataTable();
     $prices->addStringColumn('Date')->addNumberColumn($dataType)->addNumberColumn('50 Day Moving Average')->addNumberColumn('200 Day Moving Average')->addRows($graphData);
     return $prices->toJson();
 }
Пример #4
0
 /**
  * @return \Illuminate\Routing\Route|null|string
  */
 public function ingnoreId()
 {
     $id = $this->route('stock');
     $item_id = $this->input('item_id');
     $supplier_id = $this->input('supplier_id');
     return Stock::where(compact('id', 'item_id', 'supplier_id'))->exists() ? $id : '';
 }
 private static function insertMetricRowsForNewStocks()
 {
     $stockCodes = Stock::lists('stock_code');
     foreach ($stockCodes as $stockCode) {
         StockMetrics::updateOrCreate(['stock_code' => $stockCode], []);
     }
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     if ($this->confirm('This process may take several hours, do you wish to continue? [y|N]')) {
         $uniqueStockCodes = Stock::all()->lists('stock_code');
         $numberOfStocks = count($uniqueStockCodes);
         foreach ($uniqueStockCodes as $stockKey => $stockCode) {
             $this->info("Processing Stock Code: " . $stockCode . " " . round(($stockKey + 1) * (100 / $numberOfStocks), 2) . "%");
             if (!FillHistoricalMovingAveragesCommand::alreadyFilled($stockCode)) {
                 foreach ([50, 200] as $timeFrame) {
                     $historicalDates = Historicals::where('stock_code', $stockCode)->orderBy('date', 'desc')->lists('date');
                     $numberOfDates = count($historicalDates);
                     foreach ($historicalDates as $dateKey => $date) {
                         $recordsInTimeFrame = Historicals::where('stock_code', $stockCode)->orderBy('date', 'desc')->skip($dateKey)->take($timeFrame)->lists('close');
                         $averageOfRecordsInTimeFrame = $recordsInTimeFrame->sum() / $recordsInTimeFrame->count();
                         if ($timeFrame == 50) {
                             Historicals::where(['stock_code' => $stockCode, 'date' => $date])->update(['fifty_day_moving_average' => $averageOfRecordsInTimeFrame]);
                         } elseif ($timeFrame == 200) {
                             Historicals::where(['stock_code' => $stockCode, 'date' => $date])->update(['two_hundred_day_moving_average' => $averageOfRecordsInTimeFrame]);
                         }
                         $this->line(round(($stockKey + 1) * (100 / $numberOfStocks), 2) . "% | Stock: " . $stockCode . " | " . $timeFrame . " Day | Date: " . $date . " " . round(($dateKey + 1) * (100 / $numberOfDates), 2) . "%");
                     }
                 }
             } else {
                 $this->info($stockCode . " was already filled, skipping...");
             }
         }
     }
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $this->info("Updating " . $this->option('mode') . " sector metrics. This may take several minutes...");
     $listOfSectors = Stock::getListOfSectors();
     array_push($listOfSectors, 'All');
     if ($this->option('testMode') == 'true') {
         $this->info("Running in test mode. Only Banks and Telcos will be updated.");
         $listOfSectors = ['Banks', 'Telecommunication Services'];
     }
     foreach ($listOfSectors as $sectorName) {
         $stocksInSector = Stock::where('sector', $sectorName)->lists('stock_code');
         if ($sectorName == 'All') {
             $stocksInSector = Stock::lists('stock_code');
         }
         if (count($stocksInSector) > 0) {
             $totalSectorMarketCap = SectorHistoricals::getTotalSectorMarketCap($stocksInSector);
             if (isTradingDay()) {
                 SectorHistoricals::updateOrCreate(['sector' => $sectorName, 'date' => date("Y-m-d")], ['sector' => $sectorName, 'date' => date("Y-m-d"), 'total_sector_market_cap' => $totalSectorMarketCap, 'day_change' => round(SectorHistoricals::getSectorPercentChange($sectorName, $stocksInSector), 2), 'average_sector_market_cap' => $totalSectorMarketCap / count($stocksInSector)]);
                 if ($this->option('mode') == 'full') {
                     foreach ($this->sectorMetrics as $metricName) {
                         SectorHistoricals::updateOrCreate(['sector' => $sectorName, 'date' => date("Y-m-d")], [$metricName => round(StockMetrics::getAverageMetric($metricName, $stocksInSector, $sectorName), 2)]);
                     }
                 }
             }
         }
     }
 }
Пример #8
0
 /**
  * Импортирует курсы сразу для всех индексов
  */
 public function actionCandels()
 {
     $rows = Stock::query()->all();
     foreach ($rows as $row) {
         $stock_id = $row['id'];
         $this->log('Попытка получить данные для: ' . $row['name']);
         $importer = ['params' => ['market' => $row['finam_market'], 'em' => $row['finam_em'], 'code' => $row['finam_code']]];
         $class = new \app\service\DadaImporter\Finam($importer);
         $date = new \DateTime();
         $date->sub(new \DateInterval('P7D'));
         $data = $class->importCandels($date->format('Y-m-d'));
         // стратегия: Если данные есть то, они не трогаются
         $dateArray = ArrayHelper::getColumn($data, 'date');
         sort($dateArray);
         $rows2 = StockKurs::query(['between', 'date', $dateArray[0], $dateArray[count($dateArray) - 1]])->andWhere(['stock_id' => $stock_id])->all();
         $dateArrayRows = ArrayHelper::getColumn($rows2, 'date');
         $new = [];
         foreach ($data as $row) {
             if (!in_array($row['date'], $dateArrayRows)) {
                 $new[] = [$stock_id, $row['date'], $row['open'], $row['high'], $row['low'], $row['close'], $row['volume'], $row['close']];
             }
         }
         if (count($new) > 0) {
             \Yii::info('Импортированы данные: ' . VarDumper::dumpAsString($new), 'cap\\importer\\index');
             $this->log('Импортированы данные: ' . VarDumper::dumpAsString($new));
             StockKurs::batchInsert(['stock_id', 'date', 'open', 'high', 'low', 'close', 'volume', 'kurs'], $new);
         } else {
             $this->log('Нечего импортировать');
         }
     }
 }
Пример #9
0
 public function getProducts($id)
 {
     $stock = Stock::find($id);
     $stockProducts = $stock->stockProducts;
     $products = [];
     foreach ($stockProducts as $sp) {
         $products[] = $sp->product;
     }
     return $products;
 }
 public function show(SearchRequest $request)
 {
     $stocks = StockMetrics::getMetricsByStockList($this->search->getSearchResults($request), $request->omitCondition);
     if ($request->viewType == 'partial') {
         if ($request->section == 'sectorDayGain' || $request->section == 'sectorDayLoss') {
             return view('layouts.partials.sector-day-change-display')->with(['sectorChanges' => SectorHistoricals::getSectorDayChanges($request->section), 'title' => SectorHistoricals::getSectorDayChangeTitle($request->section)]);
         }
         return view('layouts.partials.stock-list-display')->with(['stocks' => $stocks]);
     }
     return view('pages.stocks')->with(['stocks' => $stocks, 'stockSectors' => Stock::getSectorDropdown(), 'stockSectorName' => $request->stockSector]);
 }
Пример #11
0
 public function add($stock_id)
 {
     if ($this->validate()) {
         $stock = Stock::find($stock_id);
         $request = Request::insert(['stock_id' => $stock_id, 'month' => $this->monthCounter]);
         Application::mail(User::find(Yii::$app->params['chat']['consultant_id'])->getEmail(), 'Запрос на добавление услуги', 'request', ['stock' => $stock, 'user' => \Yii::$app->user->identity, 'request' => $request]);
         return true;
     } else {
         return false;
     }
 }
Пример #12
0
 /**
  * Актвирует услугу
  *
  * @return array
  * [
  *   'stock'      => \app\models\Stock
  *   'dateFinish' => string - дата до которого оплачена услуга в формате 'yyyy-mm-dd'
  * ]
  */
 public function activate()
 {
     $stock_id = $this->getField('stock_id');
     $stock = Stock::find($stock_id);
     $monthCounter = $this->getField('month');
     $dateFinish = \app\models\UserStock::add(\Yii::$app->user->getId(), $stock_id, $monthCounter, $this->getField('datetime'));
     $dateFinishStr = Yii::$app->formatter->asDate($dateFinish);
     WalletHistory::insert("Услуга включена, акция: {$stock->getName()}, месяцев: {$monthCounter}, до: {$dateFinishStr}");
     self::delete();
     return ['stock' => $stock, 'dateFinish' => $dateFinish];
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     if ($this->option('testMode') == 'true') {
         $this->info("[Test Mode]");
         foreach (['TLS', 'CBA'] as $stockCode) {
             $priceOneWeekAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subWeek()));
             $lastTrade = StockMetrics::where('stock_code', $stockCode)->pluck('last_trade');
             $weekChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceOneWeekAgo);
             StockGains::updateOrCreate(['stock_code' => $stockCode], ['stock_code' => $stockCode, 'week_change' => $weekChange, 'updated_at' => date("Y-m-d H:i:s")]);
         }
     } else {
         $this->info("Calculating the stock changes... This may take several minutes.");
         $stockCodes = Stock::lists('stock_code');
         $numberOfStocks = Stock::count();
         //For Calculation of YTD gain
         $firstTradingDateOfYear = CalculateStockChangeCommand::getFirstTradingDateOfYear();
         foreach ($stockCodes as $key => $stockCode) {
             $lastTrade = StockMetrics::where('stock_code', $stockCode)->pluck('last_trade');
             $priceOneWeekAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subWeek()));
             $weekChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceOneWeekAgo);
             $priceTwoWeeksAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subWeeks(2)));
             $twoWeekChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceTwoWeeksAgo);
             $priceOneMonthAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subMonth()));
             $oneMonthChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceOneMonthAgo);
             $priceTwoMonthsAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subMonths(2)));
             $twoMonthChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceTwoMonthsAgo);
             $priceThreeMonthsAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subMonths(3)));
             $threeMonthChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceThreeMonthsAgo);
             $priceSixMonthsAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subMonths(6)));
             $sixMonthChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceSixMonthsAgo);
             $priceAtStartOfYear = CalculateStockChangeCommand::getPriceAtDate($stockCode, $firstTradingDateOfYear);
             $thisYearChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceAtStartOfYear);
             $priceOneYearAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subYear()));
             $oneYearChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceOneYearAgo);
             $priceTwoYearsAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subYears(2)));
             $twoYearChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceTwoYearsAgo);
             $priceThreeYearsAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subYears(3)));
             $threeYearChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceThreeYearsAgo);
             $priceFiveYearsAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subYears(5)));
             $fiveYearChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceFiveYearsAgo);
             $priceTenYearsAgo = CalculateStockChangeCommand::getPriceAtDate($stockCode, getDateFromCarbonDate(Carbon::now()->subYears(10)));
             $tenYearChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $priceTenYearsAgo);
             if (Historicals::where('stock_code', $stockCode)->first()) {
                 $oldestDate = Historicals::where('stock_code', $stockCode)->orderBy('date', 'asc')->take(1)->lists('date');
                 $oldestPriceAvailable = CalculateStockChangeCommand::getPriceAtDate($stockCode, substr($oldestDate, 2, -2));
                 $allTimeChange = CalculateStockChangeCommand::getPercentChange($lastTrade, $oldestPriceAvailable);
             } else {
                 $allTimeChange = 0;
             }
             StockGains::updateOrCreate(['stock_code' => $stockCode], ['stock_code' => $stockCode, 'week_change' => $weekChange, 'two_week_change' => $twoWeekChange, 'month_change' => $oneMonthChange, 'two_month_change' => $twoMonthChange, 'three_month_change' => $threeMonthChange, 'six_month_change' => $sixMonthChange, 'this_year_change' => $thisYearChange, 'year_change' => $oneYearChange, 'two_year_change' => $twoYearChange, 'three_year_change' => $threeYearChange, 'five_year_change' => $fiveYearChange, 'ten_year_change' => $tenYearChange, 'all_time_change' => $allTimeChange, 'updated_at' => date("Y-m-d H:i:s")]);
             $this->info("Completed: " . $stockCode . " " . ($key + 1) . "/" . $numberOfStocks . " - " . round(($key + 1) * (100 / $numberOfStocks), 2) . "%");
         }
     }
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     $companyListFromASX = UpdateStockListCommand::getCompanyList($this->option('testMode'));
     $numberOfStocks = count($companyListFromASX);
     foreach ($companyListFromASX as $key => $companyRow) {
         if ($companyRow != null) {
             $stockCode = explode(',"', explode('",', $companyRow)[1])[0];
             Stock::updateOrCreate(['stock_code' => $stockCode], ['stock_code' => explode(',"', explode('",', $companyRow)[1])[0], 'company_name' => formatCompanyName($stockCode, substr(explode('",', $companyRow)[0], 1)), 'sector' => substr(explode(',"', explode('",', $companyRow)[1])[1], 0, -2), 'updated_at' => date("Y-m-d H:i:s")]);
             $this->info("Updating... " . round(($key + 1) * (100 / $numberOfStocks), 2) . "%");
         }
     }
     $this->info('The list of stocks was updated successfully!');
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $providedDate = $this->ask("Which date would you like to get the sector historicals for? ('yyyy-mm-dd')");
     $historicalsAtDate = Historicals::where('date', $providedDate)->get();
     $sectors = \DB::table('stocks')->select(\DB::raw('DISTINCT sector'))->lists('sector');
     foreach ($sectors as $sector) {
         $stocksInSector = Stock::where('sector', $sector)->lists('stock_code');
         FillSectorHistoricalsCommand::calculateDayGain($stocksInSector, $sector, $providedDate);
     }
     $allStockCodes = Stock::lists('stock_code');
     FillSectorHistoricalsCommand::calculateDayGain($allStockCodes, "All", $providedDate);
     $this->info("Sector historicals have been filled for: " . $providedDate);
 }
Пример #16
0
 /**
  * Creates data provider instance with search query applied
  *
  * @param array $params
  *
  * @return ActiveDataProvider
  */
 public function search($params)
 {
     $query = Stock::find();
     $dataProvider = new ActiveDataProvider(['query' => $query]);
     $this->load($params);
     if (!$this->validate()) {
         // uncomment the following line if you do not want to return any records when validation fails
         // $query->where('0=1');
         return $dataProvider;
     }
     $query->andFilterWhere(['idproducto' => $this->idproducto, 'stock' => $this->stock]);
     return $dataProvider;
 }
Пример #17
0
 public static function getRelatedStocks($stockCode)
 {
     $otherStocksInSector = Stock::where('sector', Stock::where('stock_code', $stockCode)->pluck('sector'))->lists('stock_code');
     if (count($otherStocksInSector) > 10) {
         $individualMarketCap = StockMetrics::where('stock_code', $stockCode)->pluck('market_cap');
         $relatedStocks = StockMetrics::whereIn('stock_code', $otherStocksInSector)->where('stock_code', '!=', $stockCode)->where('market_cap', '<=', $individualMarketCap * 10)->where('market_cap', '>=', $individualMarketCap / 10)->lists('stock_code');
         //If Mkt Cap conditions leave too few left, just return $otherStocksInSector
         if (count($relatedStocks) < 5) {
             return $otherStocksInSector;
         }
         return $relatedStocks;
     }
     return $otherStocksInSector;
 }
Пример #18
0
 public function up()
 {
     $this->execute('ALTER TABLE galaxysss_4.cap_stock CHANGE finam_code finam_code varchar(20);');
     $arr = \app\models\Stock::query()->all();
     foreach ($arr as $item) {
         $stock = new \app\models\Stock($item);
         foreach (\app\service\DadaImporter\Data::$importerData as $data) {
             if ($item['id'] == $data['stock_id']) {
                 $params = $data['params'];
                 $stock->update(['finam_em' => $params['em'], 'finam_market' => $params['market'], 'finam_code' => $params['code']]);
             }
         }
     }
 }
 private static function getStockCodeParameter($testMode = 'false')
 {
     if ($testMode != 'true') {
         date_default_timezone_set("Australia/Sydney");
         //Limit of 100 at a time due to yahoo's url length limit
         $stockCodeList = Stock::whereNotIn('stock_code', Historicals::distinct()->where('date', date("Y-m-d"))->lists('stock_code'))->take(100)->lists('stock_code');
         $stockCodeParameter = "";
         foreach ($stockCodeList as $stockCode) {
             $stockCodeParameter .= "+" . $stockCode . ".AX";
         }
         return substr($stockCodeParameter, 1);
     } else {
         return "TLS.AX+CBA.AX";
     }
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $this->info("Locating and storing company summaries...");
     $stocks = Stock::lists('stock_code');
     $numberOfStocks = count($stocks);
     foreach ($stocks as $key => $stockCode) {
         //Check if there is already a summary
         if (Stock::where('stock_code', $stockCode)->pluck('business_summary') == null) {
             $pageContents = file_get_contents("https://au.finance.yahoo.com/q/pr?s=" . $stockCode . ".AX");
             if (strpos($pageContents, "</th></tr></table><p>") && strpos($pageContents, '</p><p><a href="/q/ks?s=' . $stockCode . '.AX"><b>')) {
                 $businessSummary = explode('</p><p><a href="/q/ks?s=' . $stockCode . '.AX"><b>', explode("</th></tr></table><p>", $pageContents)[1]);
                 if (strlen($businessSummary[0]) > 0) {
                     $stock = Stock::where('stock_code', $stockCode)->first();
                     $stock->business_summary = $businessSummary[0];
                     $stock->save();
                 }
             }
         }
         $this->info("Completed: " . $stockCode . " " . ($key + 1) . "/" . $numberOfStocks . " - " . round(($key + 1) * (100 / $numberOfStocks), 2) . "%");
     }
 }
Пример #21
0
 public function actionGenerarcupon($id)
 {
     $cupon = new Cupones();
     $request = Yii::$app->request;
     $cupon->idusuario = \Yii::$app->user->identity->id;
     $cupon->idproducto = $id;
     $hoy = date('Y-m-d');
     $cupon->fecha = $hoy;
     $producto = Productos::findOne($id);
     $producto->vendidos += 1;
     $cupon->save();
     $producto->update();
     $Models = Stock::findOne($id);
     if ($Models != null) {
         $Models->stock--;
         if ($Models == 0) {
             $producto = Productos::findOne($id);
             $producto->activo = 0;
         }
         $Models->save();
     }
     return $this->redirect(['view', 'id' => $cupon->id]);
 }
Пример #22
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getStocks()
 {
     return $this->hasMany(Stock::className(), ['id_almacen' => 'id']);
 }
Пример #23
0
 /**
  * Рисует графики с прошлым и будущим
  *
  * @param int $id идентификатор курса
  *
  * @return string
  */
 public function actionStock_item3($id)
 {
     $item = \app\models\Stock::find($id);
     $start = (new \DateTime())->sub(new \DateInterval('P31D'));
     $end = (new \DateTime())->sub(new \DateInterval('P1D'));
     $isPaid = Yii::$app->user->identity->isPaid($id);
     $defaultParams = ['start' => $start, 'end' => $end, 'formatX' => 'd.m'];
     $params = ArrayHelper::merge($defaultParams, ['rows' => [\app\models\StockKurs::query(['stock_id' => $id])->andWhere(['between', 'date', $start->format('Y-m-d'), $end->format('Y-m-d')])->all()]]);
     $lineArrayKurs = \app\service\GraphExporter::convert($params);
     $params = ArrayHelper::merge($defaultParams, ['rows' => [\app\models\StockPrognosisRed::query(['stock_id' => $id])->andWhere(['between', 'date', $start->format('Y-m-d'), $end->format('Y-m-d')])->select(['date', 'delta as kurs'])->all()]]);
     $lineArrayRed = \app\service\GraphExporter::convert($params);
     $params = ArrayHelper::merge($defaultParams, ['rows' => [\app\models\StockPrognosisBlue::query(['stock_id' => $id])->andWhere(['between', 'date', $start->format('Y-m-d'), $end->format('Y-m-d')])->select(['date', 'delta as kurs'])->all()]]);
     $lineArrayBlue = \app\service\GraphExporter::convert($params);
     $lineArrayPast = \app\service\GraphUnion::convert(['x' => $lineArrayRed['x'], 'y' => [$lineArrayKurs['y'][0], $lineArrayRed['y'][0], $lineArrayBlue['y'][0]]]);
     if ($isPaid) {
         $start = new \DateTime();
         $end = (new \DateTime())->add(new \DateInterval('P30D'));
         $defaultParams = ['start' => $start, 'end' => $end];
         $params = ArrayHelper::merge($defaultParams, ['rows' => [\app\models\StockPrognosisRed::query(['stock_id' => $id])->andWhere(['between', 'date', $start->format('Y-m-d'), $end->format('Y-m-d')])->select(['date', 'delta as kurs'])->all()]]);
         $lineArrayRed = \app\service\GraphExporter::convert($params);
         $params = ArrayHelper::merge($defaultParams, ['rows' => [\app\models\StockPrognosisBlue::query(['stock_id' => $id])->andWhere(['between', 'date', $start->format('Y-m-d'), $end->format('Y-m-d')])->select(['date', 'delta as kurs'])->all()]]);
         $lineArrayBlue = \app\service\GraphExporter::convert($params);
         $lineArrayFuture = \app\service\GraphUnion::convert(['x' => $lineArrayRed['x'], 'y' => [$lineArrayRed['y'][0], $lineArrayBlue['y'][0]]]);
     } else {
         $lineArrayFuture = null;
     }
     return $this->render(['item' => $item, 'lineArrayPast' => $lineArrayPast, 'lineArrayFuture' => $lineArrayFuture, 'isPaid' => $isPaid]);
 }
 public function actionPrognosis_edit($id)
 {
     return $this->render(['items' => \app\models\StockPrognosis::query(['stock_id' => $id])->orderBy(['date' => SORT_DESC])->all(), 'item' => \app\models\Stock::find($id)]);
 }
Пример #25
0
 /**
  * @param Request $request
  * @return \Illuminate\Http\JsonResponse
  */
 public function deleteStock($id, Request $request)
 {
     $stock = Stock::where('id', $id);
     if ($stock->delete()) {
         return response()->json(['deleted' => true]);
     }
     return response()->json(['deleted' => false]);
 }
Пример #26
0
 public function store(Request $request)
 {
     try {
         DB::transaction(function () use($request) {
             $inputs = $request->input();
             $user = Auth::user();
             $time = time();
             $year = CommonHelper::get_current_financial_year();
             $order_quantity = 0;
             $deliver_quantity = 0;
             $products = Product::whereIn('id', array_keys($inputs['quantity']))->get()->toArray();
             //                dd($products);
             foreach ($inputs['quantity'] as $key => $value) {
                 if ($value > 0) {
                     $salesDelivery = SalesDeliveryDetail::firstOrNew(['sales_order_id' => $inputs['sales_order_id'], 'product_id' => $key]);
                     if ($salesDelivery->id) {
                         $salesDelivery->updated_by = $user->id;
                         $salesDelivery->updated_at = $time;
                         $d_quantity = $salesDelivery->delivered_quantity += $inputs['deliver_now'][$key];
                         $salesDelivery->last_delivered_quantity = $inputs['deliver_now'][$key];
                         $salesDelivery->save();
                     } else {
                         $salesDelivery->sales_order_id = $inputs['sales_order_id'];
                         $salesDelivery->created_by = $user->id;
                         $salesDelivery->created_at = $time;
                         $salesDelivery->status = 2;
                         //Partial Delivery
                         $salesDelivery->product_id = $key;
                         $salesDelivery->order_quantity = $value;
                         $d_quantity = $salesDelivery->delivered_quantity = $inputs['deliver_now'][$key];
                         $salesDelivery->last_delivered_quantity = $inputs['deliver_now'][$key];
                         $salesDelivery->save();
                     }
                     if ($d_quantity == $value) {
                         $salesDelivery->status = 4;
                         //product delivery completed
                         $salesDelivery->save();
                         $salesOrderItem = SalesOrderItem::firstOrNew(['sales_order_id' => $inputs['sales_order_id'], 'product_id' => $key]);
                         $salesOrderItem->status = 4;
                         // Sales item Delivery Completed
                         $salesOrderItem->save();
                     } else {
                         $salesDelivery->status = 2;
                         //Partial Delivery
                         $salesDelivery->save();
                         $salesOrderItem = SalesOrderItem::firstOrNew(['sales_order_id' => $inputs['sales_order_id'], 'product_id' => $key]);
                         $salesOrderItem->status = 2;
                         //Partial Delivery
                         $salesOrderItem->save();
                     }
                     $deliver_quantity += $d_quantity;
                     $order_quantity += $value;
                     $quantity_delivered = $inputs['deliver_now'][$key];
                     $stocks = Stock::where(['year' => $year, 'stock_type' => Config::get('common.balance_type_intermediate'), 'workspace_id' => $user->workspace_id, 'product_id' => $key])->first();
                     if ($inputs['unit_type'][$key] == 2) {
                         foreach ($products as $item) {
                             if ($item['id'] == $key) {
                                 $quantity_delivered = $quantity_delivered / $item['weight'] * $item['length'];
                                 break;
                             }
                         }
                     }
                     if ($stocks->quantity < $quantity_delivered) {
                         Session()->flash('warning_message', 'Insufficient stock.');
                         throw new \Exception();
                     }
                     $stocks->quantity -= $quantity_delivered;
                     $stocks->updated_by = $user->id;
                     $stocks->updated_at = $time;
                     $stocks->update();
                 }
                 if ($deliver_quantity == $order_quantity) {
                     $salesOrder = SalesOrder::find($inputs['sales_order_id']);
                     $salesOrder->status = 4;
                     // Sales Delivery Completed
                     $salesOrder->save();
                 } else {
                     $salesOrder = SalesOrder::find($inputs['sales_order_id']);
                     $salesOrder->status = 2;
                     //Partial Delivery
                     $salesOrder->save();
                 }
             }
         });
     } catch (\Exception $e) {
         Session()->flash('error_message', 'Products delivered failed.');
         return Redirect::back();
     }
     Session()->flash('flash_message', 'Products delivered successfully.');
     return redirect('salesDelivery');
 }
Пример #27
0
 /**
  * Updates an existing Productos model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param string $id
  * @return mixed
  */
 public function actionUpdate($id)
 {
     $model = $this->findModel($id);
     $img_model = new UploadForm();
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
         $request = Yii::$app->request;
         $id_producto = $model->id;
         $fotos = Fotos::find()->where(['idProducto' => $id_producto])->all();
         foreach ($fotos as $foto) {
             Fotos::deleteFoto($foto);
         }
         $img_model->imageFiles = UploadedFile::getInstances($img_model, 'imageFiles');
         if ($img_model->upload($model->id)) {
             if ($model->tipo == 0) {
                 return $this->redirect(['view', 'id' => $model->id]);
             } else {
                 if ($model->tipo == 1) {
                     $porTiempo = Temporales::find()->where(['idproducto' => $model->id])->one();
                     $porTiempo->fecha = $request->post('fecha');
                     $porTiempo->idproducto = $model->id;
                     $porTiempo->save();
                     return $this->redirect(['view', 'id' => $model->id]);
                 } else {
                     $stock = Stock::find()->where(['idproducto' => $model->id])->one();
                     $cantidad = $request->post('cant');
                     $stock->stock = $cantidad;
                     $stock->idproducto = $model->id;
                     $stock->save();
                     return $this->redirect(['view', 'id' => $model->id]);
                 }
             }
         }
     } else {
         return $this->render('update', ['model' => $model, 'img_model' => $img_model]);
     }
 }
Пример #28
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function lotUsage(UsageRequest $request)
 {
     $usage = Usage::findOrFail($request->id);
     $usage->stock_id = $request->stock_id;
     $usage->quantity_used = $request->quantity_used;
     $usage->date_of_usage = $request->date_of_usage;
     $usage->issued_by = $request->issued_by;
     $usage->received_by = $request->received_by;
     $usage->remarks = $request->remarks;
     $usage->user_id = Auth::user()->id;
     $url = session('SOURCE_URL');
     if ($usage->quantity_used > Stock::find((int) $usage->stock_id)->quantity()) {
         return redirect()->back()->with('message', trans('messages.insufficient-stock'))->withInput($request->all());
     } else {
         if ($usage->quantity_used > Topup::find((int) $usage->request_id)->quantity_ordered) {
             return redirect()->back()->with('message', trans('messages.issued-greater-than-ordered'))->withInput($request->all());
         } else {
             $usage->save();
             return redirect()->to($url)->with('message', trans('messages.record-successfully-updated'))->with('active_stock', $usage->stock->id);
         }
     }
 }
Пример #29
0
 public function update($id, ProductionRegisterRequest $request)
 {
     try {
         DB::transaction(function () use($request, $id) {
             $user = Auth::user();
             $existingRegister = DB::table('production_registers')->where('id', $id)->first();
             $productionRegister = ProductionRegister::findOrFail($id);
             $productionRegister->date = $request->input('date');
             $productionRegister->production = $request->input('production');
             $productionRegister->updated_by = Auth::user()->id;
             $productionRegister->updated_at = time();
             $productionRegister->update();
             $existingStock = DB::table('stocks')->where(['year' => CommonHelper::get_current_financial_year(), 'stock_type' => Config::get('common.balance_type_intermediate'), 'workspace_id' => $user->workspace_id, 'product_id' => $existingRegister->product_id])->first();
             $product_length = DB::table('products')->where('id', $id)->value('length');
             if ($existingRegister->production != $request->input('production')) {
                 if ($existingRegister->production > $request->input('production')) {
                     $difference = $existingRegister->production - $request->input('production');
                     $stock = Stock::findOrFail($existingStock->id);
                     $stock->quantity = $existingStock->quantity - $difference * $product_length;
                     $stock->updated_by = Auth::user()->id;
                     $stock->updated_at = time();
                     $stock->update();
                 } elseif ($existingRegister->production < $request->input('production')) {
                     $difference = $request->input('production') - $existingRegister->production;
                     $stock = Stock::findOrFail($existingStock->id);
                     $stock->quantity = $existingStock->quantity + $difference * $product_length;
                     $stock->updated_by = Auth::user()->id;
                     $stock->updated_at = time();
                     $stock->update();
                 }
             }
         });
     } catch (\Exception $e) {
         Session()->flash('error_message', 'Production Register not updated!');
         return redirect('productionRegisters');
     }
     Session()->flash('flash_message', 'Production Register has been updated!');
     return redirect('productionRegisters');
 }
Пример #30
0
 public function store(Request $request)
 {
     $this->validate($request, ['customer_id' => 'required', 'product' => 'required|array', 'total' => 'required|numeric', 'return_type' => 'required']);
     try {
         DB::transaction(function () use($request) {
             $inputs = $request->input();
             $user_id = Auth::user()->id;
             $workspace_id = Auth::user()->workspace_id;
             $balance_type = Config::get('common.balance_type_intermediate');
             $transaction_type = Config::get('common.transaction_type.sales_return');
             $time = time();
             $date = strtotime(date('d-m-Y'));
             $year = CommonHelper::get_current_financial_year();
             $data['customer_id'] = $inputs['customer_id'];
             $data['workspace_id'] = $workspace_id;
             $data['customer_type'] = $inputs['customer_type'];
             $data['total_amount'] = $inputs['total'];
             if ($inputs['return_type'] == 3) {
                 $data['due'] = $inputs['total'];
             } elseif ($inputs['return_type'] == 4) {
                 $data['due'] = $inputs['total'] - $inputs['due_paid'];
             }
             if (isset($inputs['due_paid'])) {
                 $data['due_paid'] = $inputs['due_paid'];
             }
             $data['return_type'] = $inputs['return_type'];
             $data['date'] = $time;
             $data['created_by'] = $user_id;
             $data['created_at'] = $time;
             $sales_return_id = DB::table('sales_return')->insertGetId($data);
             unset($data);
             $data['sales_return_id'] = $sales_return_id;
             $data['created_by'] = $user_id;
             $data['created_at'] = $time;
             foreach ($inputs['product'] as $product) {
                 $data['product_id'] = $product['product_id'];
                 $data['quantity'] = $product['quantity_returned'];
                 $data['unit_price'] = $product['unit_price'];
                 $data['unit_type'] = $product['unit_type'];
                 DB::table('sales_return_details')->insert($data);
                 $quantity_returned = $product['quantity_returned'];
                 $stock = Stock::where('year', '=', $year)->where('stock_type', '=', $balance_type)->where('product_id', '=', $product['product_id'])->first();
                 if ($product['unit_type'] == 2) {
                     $quantity_returned = $product['quantity_returned'] / $product['weight'] * $product['length'];
                 }
                 $stock->quantity += $quantity_returned;
                 $stock->updated_by = $user_id;
                 $stock->updated_at = $time;
                 $stock->update();
             }
             if ($inputs['return_type'] == 1) {
                 //For Cash
                 // Update Workspace Ledger
                 $workspace = WorkspaceLedger::where(['account_code' => 11000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 if ($workspace->balance < $inputs['total']) {
                     Session()->flash('warning_message', 'Insufficient cash balance!');
                     throw new \Exception();
                 }
                 $workspace->balance -= $inputs['total'];
                 //Subtract Cash
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
                 $workspace = WorkspaceLedger::where(['account_code' => 32000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance += $inputs['total'];
                 //Add Product Sales Return
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
                 //Insert data into General Journal
                 $journal = new GeneralJournal();
                 $journal->date = $date;
                 $journal->transaction_type = $transaction_type;
                 $journal->reference_id = $sales_return_id;
                 $journal->year = $year;
                 $journal->account_code = 11000;
                 //Cash
                 $journal->workspace_id = $workspace_id;
                 $journal->amount = $inputs['total'];
                 $journal->dr_cr_indicator = Config::get('common.debit_credit_indicator.credit');
                 $journal->created_by = $user_id;
                 $journal->created_at = $time;
                 $journal->save();
                 $journal = new GeneralJournal();
                 $journal->date = $date;
                 $journal->transaction_type = $transaction_type;
                 $journal->reference_id = $sales_return_id;
                 $journal->year = $year;
                 $journal->account_code = 32000;
                 //Product Sales Return
                 $journal->dr_cr_indicator = Config::get('common.debit_credit_indicator.debit');
                 $journal->workspace_id = $workspace_id;
                 $journal->amount = $inputs['total'];
                 $journal->created_by = $user_id;
                 $journal->created_at = $time;
                 $journal->save();
             } elseif ($inputs['return_type'] == 2) {
                 // For Pay due
                 // Update Workspace Ledger
                 $workspace = WorkspaceLedger::where(['account_code' => 12000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance -= $inputs['total'];
                 //Subtract Account Receivable
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
                 $workspace = WorkspaceLedger::where(['account_code' => 32000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance += $inputs['total'];
                 //Add Product Sales Return
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
                 //Insert data into General Journal
                 $journal = new GeneralJournal();
                 $journal->date = $date;
                 $journal->transaction_type = $transaction_type;
                 $journal->reference_id = $sales_return_id;
                 $journal->year = $year;
                 $journal->account_code = 12000;
                 //Account Receivable
                 $journal->workspace_id = $workspace_id;
                 $journal->amount = $inputs['total'];
                 $journal->dr_cr_indicator = Config::get('common.debit_credit_indicator.credit');
                 $journal->created_by = $user_id;
                 $journal->created_at = $time;
                 $journal->save();
                 $journal = new GeneralJournal();
                 $journal->date = $date;
                 $journal->transaction_type = $transaction_type;
                 $journal->reference_id = $sales_return_id;
                 $journal->year = $year;
                 $journal->account_code = 32000;
                 //Product Sales Return
                 $journal->dr_cr_indicator = Config::get('common.debit_credit_indicator.debit');
                 $journal->workspace_id = $workspace_id;
                 $journal->amount = $inputs['total'];
                 $journal->created_by = $user_id;
                 $journal->created_at = $time;
                 $journal->save();
                 // Update Personal Account
                 $personal = PersonalAccount::where('person_id', $inputs['customer_id'])->where('person_type', $inputs['customer_type'])->first();
                 $personal->due -= $inputs['due_paid'];
                 if ($inputs['total'] > $inputs['due_paid']) {
                     $personal->balance += $inputs['total'] - $inputs['due_paid'];
                 }
                 $personal->updated_by = $user_id;
                 $personal->updated_at = $time;
                 $personal->save();
             } elseif ($inputs['return_type'] == 3) {
                 //For Due
                 // Update Workspace Ledger
                 $workspace = WorkspaceLedger::where(['account_code' => 41000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance += $inputs['total'];
                 //Add Account Payable
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
                 $workspace = WorkspaceLedger::where(['account_code' => 32000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance += $inputs['total'];
                 //Add Product Sales Return
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
                 //Insert data into General Journal
                 $journal = new GeneralJournal();
                 $journal->date = $date;
                 $journal->transaction_type = $transaction_type;
                 $journal->reference_id = $sales_return_id;
                 $journal->year = $year;
                 $journal->account_code = 41000;
                 //Account Payable
                 $journal->workspace_id = $workspace_id;
                 $journal->amount = $inputs['total'];
                 $journal->dr_cr_indicator = Config::get('common.debit_credit_indicator.credit');
                 $journal->created_by = $user_id;
                 $journal->created_at = $time;
                 $journal->save();
                 $journal = new GeneralJournal();
                 $journal->date = $date;
                 $journal->transaction_type = $transaction_type;
                 $journal->reference_id = $sales_return_id;
                 $journal->year = $year;
                 $journal->account_code = 32000;
                 //Product Sales Return
                 $journal->dr_cr_indicator = Config::get('common.debit_credit_indicator.debit');
                 $journal->workspace_id = $workspace_id;
                 $journal->amount = $inputs['total'];
                 $journal->created_by = $user_id;
                 $journal->created_at = $time;
                 $journal->save();
                 //Update Personal Account
                 $personal = PersonalAccount::where('person_id', $inputs['customer_id'])->where('person_type', $inputs['customer_type'])->first();
                 $personal->balance += $inputs['total'];
                 $personal->updated_by = $user_id;
                 $personal->updated_at = $time;
                 $personal->save();
             } elseif ($inputs['return_type'] == 4) {
                 //For Pay Due & Cash Return
                 // Update Workspace Ledger
                 $workspace = WorkspaceLedger::where(['account_code' => 11000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 if ($workspace->balance < $inputs['total'] - $inputs['due_paid']) {
                     Session()->flash('warning_message', 'Insufficient cash balance!');
                     throw new \Exception();
                 }
                 $workspace->balance -= $inputs['total'] - $inputs['due_paid'];
                 //Subtract Cash
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
                 $workspace = WorkspaceLedger::where(['account_code' => 32000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance += $inputs['total'];
                 //Add Product Sales Return
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
                 $workspace = WorkspaceLedger::where(['account_code' => 12000, 'workspace_id' => $workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance -= $inputs['due_paid'];
                 //Subtract Account Receivable
                 $workspace->updated_by = $user_id;
                 $workspace->updated_at = $time;
                 $workspace->save();
                 //Insert data into General Journal
                 $journal = new GeneralJournal();
                 $journal->date = $date;
                 $journal->transaction_type = $transaction_type;
                 $journal->reference_id = $sales_return_id;
                 $journal->year = $year;
                 $journal->account_code = 11000;
                 //Cash
                 $journal->workspace_id = $workspace_id;
                 $journal->amount = $inputs['total'] - $inputs['due_paid'];
                 $journal->dr_cr_indicator = Config::get('common.debit_credit_indicator.credit');
                 $journal->created_by = $user_id;
                 $journal->created_at = $time;
                 $journal->save();
                 $journal = new GeneralJournal();
                 $journal->date = $date;
                 $journal->transaction_type = $transaction_type;
                 $journal->reference_id = $sales_return_id;
                 $journal->year = $year;
                 $journal->account_code = 32000;
                 //Product Sales Return
                 $journal->dr_cr_indicator = Config::get('common.debit_credit_indicator.debit');
                 $journal->workspace_id = $workspace_id;
                 $journal->amount = $inputs['total'];
                 $journal->created_by = $user_id;
                 $journal->created_at = $time;
                 $journal->save();
                 $journal = new GeneralJournal();
                 $journal->date = $date;
                 $journal->transaction_type = $transaction_type;
                 $journal->reference_id = $sales_return_id;
                 $journal->year = $year;
                 $journal->account_code = 12000;
                 // Account Receivable
                 $journal->workspace_id = $workspace_id;
                 $journal->amount = $inputs['due_paid'];
                 $journal->dr_cr_indicator = Config::get('common.debit_credit_indicator.credit');
                 $journal->created_by = $user_id;
                 $journal->created_at = $time;
                 $journal->save();
                 //Update Personal Account
                 $personal = PersonalAccount::where('person_id', $inputs['customer_id'])->where('person_type', $inputs['customer_type'])->first();
                 $personal->due -= $inputs['due_paid'];
                 $personal->updated_by = $user_id;
                 $personal->updated_at = $time;
                 $personal->save();
             }
         });
     } catch (\Exception $e) {
         Session()->flash('error_message', 'Sales Returned Failed.');
         return Redirect::back();
     }
     Session()->flash('flash_message', 'Sales Returned Successful.');
     return redirect('sales_return');
 }