/**
  * 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)]);
                     }
                 }
             }
         }
     }
 }
Ejemplo n.º 2
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 : '';
 }
 /**
  * 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);
 }
Ejemplo n.º 4
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;
 }
 /**
  * Display the specified resource.
  *
  * @param  int  $id
  * @return Response
  */
 public function show(Request $request, $id)
 {
     if ($request->stockCodeFind) {
         return redirect('stocks/' . $request->stockCodeFind);
     }
     if (Stock::where('stock_code', $id)->first()) {
         $priceGraphData = Stock::getGraphData($id, 'last_month', 'Price');
         $prices = \Lava::DataTable();
         $prices->addStringColumn('Date')->addNumberColumn('Price')->addNumberColumn('50 Day Moving Average')->addNumberColumn('200 Day Moving Average')->addRows($priceGraphData);
         $stockPriceLava = \Lava::LineChart('StockPrice')->dataTable($prices)->customize(['explorer' => ['actions' => ['dragToZoom', 'rightClickToReset']]])->setOptions(['width' => 620, 'height' => 360, 'title' => 'Price of ' . strtoupper($id)]);
         $sector = Stock::where('stock_code', $id)->pluck('sector');
         $motRecentSectorHistoricalsDate = SectorHistoricals::getMostRecentSectorHistoricalsDate();
         return view('pages.individualstock')->with(['stockPriceLava' => $stockPriceLava, 'stock' => Stock::where('stock_code', $id)->first(), 'relatedStocks' => StockMetrics::getMetricsByStockList(Stock::getRelatedStocks($id), 'omit'), 'metrics' => StockMetrics::where('stock_code', $id)->first(), 'mostRecentStockHistoricals' => Historicals::where('stock_code', $id)->orderBy('date', 'DESC')->limit(1)->first(), 'sectorAverage' => SectorHistoricals::where(['sector' => $sector, 'date' => $motRecentSectorHistoricalsDate])->first()]);
     }
     return redirect('/');
 }
 /**
  * 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) . "%");
     }
 }
Ejemplo n.º 7
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]);
 }
Ejemplo n.º 8
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');
 }
Ejemplo n.º 9
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');
 }
 private function getStocksBySector($sectorRequest)
 {
     if ($sectorRequest == "All") {
         return Stock::distinct('sector')->lists('stock_code');
     }
     return Stock::where('sector', $sectorRequest)->lists('stock_code');
 }
Ejemplo n.º 11
0
 public function update($id, Request $request)
 {
     $this->validate($request, ['product' => 'array', 'total' => 'required']);
     //        dd($request->input());
     try {
         DB::transaction(function () use($id, $request) {
             $inputs = $request->input();
             $user = Auth::user();
             $time = time();
             $date = strtotime(date('d-m-Y'));
             $year = CommonHelper::get_current_financial_year();
             $transaction_type = Config::get('common.transaction_type.defect_receive');
             $balance_type = Config::get('common.balance_type_intermediate');
             //Defect table affected.
             $defect = Defect::find($id);
             $oldDefect = clone $defect;
             $defect->total = $inputs['total'];
             $defect->cash = $inputs['cash'];
             $defect->due_paid = $inputs['due_paid'];
             $defect->due = $inputs['due'];
             if (isset($inputs['is_replacement'])) {
                 $defect->is_replacement = $inputs['is_replacement'];
                 $defect->replacement = $inputs['new_total'];
             }
             $defect->remarks = $inputs['remarks'];
             $defect->updated_by = $user->id;
             $defect->updated_at = $time;
             $defect->update();
             $defect_amount = $inputs['cash'] + $inputs['due_paid'] + $inputs['due'];
             if ($defect_amount > 0) {
                 $journal = GeneralJournal::where('account_code', '=', 36000)->where('workspace_id', '=', $user->workspace_id)->where('reference_id', '=', $id)->where('transaction_type', '=', $transaction_type)->where('year', '=', $year)->first();
                 $journal->amount = $defect_amount;
                 $journal->updated_by = $user->id;
                 $journal->updated_at = $time;
                 $journal->update();
                 $workspace = WorkspaceLedger::where(['account_code' => 36000, 'workspace_id' => $user->workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 if ($oldDefect->total > $defect_amount) {
                     $workspace->balance += $oldDefect->total - $defect_amount;
                     //sub defect receive
                 } elseif ($oldDefect->total < $defect_amount) {
                     $workspace->balance += $defect_amount - $oldDefect->total;
                     //sub defect receive
                 }
                 $workspace->updated_by = $user->id;
                 $workspace->updated_at = $time;
                 $workspace->update();
             } else {
                 $journal = GeneralJournal::where('account_code', '=', 36000)->where('workspace_id', '=', $user->workspace_id)->where('reference_id', '=', $id)->where('transaction_type', '=', $transaction_type)->where('year', '=', $year)->first();
                 $journal->delete();
                 $workspace = WorkspaceLedger::where(['account_code' => 36000, 'workspace_id' => $user->workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance -= $oldDefect->cash + $oldDefect->due_paid + $oldDefect->due;
                 //sub defect receive
                 $workspace->updated_by = $user->id;
                 $workspace->updated_at = $time;
                 $workspace->update();
             }
             if (isset($inputs['delete_product'])) {
                 foreach ($inputs['delete_product'] as $product) {
                     $defectItem = DefectItem::where('defect_id', '=', $id)->where('product_id', '=', $product['product_id'])->first();
                     if ($defectItem) {
                         $defectItem->delete();
                     }
                 }
             }
             //Get Scrap Id
             $material = Material::where('name', '=', 'Scrap')->where('status', '=', 1)->first();
             //Old Defect Items
             foreach ($inputs['old_product'] as $product) {
                 $defectItem = DefectItem::where('defect_id', '=', $id)->where('product_id', '=', $product['product_id'])->first();
                 $oldDefectItem = clone $defectItem;
                 $defectItem->quantity = $product['receive_quantity'];
                 $defectItem->unit_type = $product['unit_type'];
                 $defectItem->unit_price = $product['unit_price'];
                 $defectItem->updated_by = $user->id;
                 $defectItem->updated_at = $time;
                 $defectItem->update();
                 //Material stock updated
                 $rawStock = RawStock::where('year', '=', $year)->where('stock_type', '=', Config::get('common.balance_type_intermediate'))->where('material_id', '=', $material->id)->first();
                 if ($product['unit_type'] == 1) {
                     if ($oldDefectItem->unit_type == 1) {
                         if ($oldDefectItem->quantity > $product['receive_quantity']) {
                             $rawStock->quantity -= ($oldDefectItem->quantity - $product['receive_quantity']) / $product['length'] * $product['weight'];
                         } elseif ($oldDefectItem->quantity < $product['receive_quantity']) {
                             $rawStock->quantity += ($product['receive_quantity'] - $oldDefectItem->quantity) / $product['length'] * $product['weight'];
                         }
                     } elseif ($oldDefectItem->unit_type == 2) {
                         $old_quantity = $oldDefectItem->quantity / $product['weight'] * $product['length'];
                         if ($old_quantity > $product['receive_quantity']) {
                             $rawStock->quantity -= ($old_quantity - $product['receive_quantity']) / $product['length'] * $product['weight'];
                         } elseif ($old_quantity < $product['receive_quantity']) {
                             $rawStock->quantity += ($product['receive_quantity'] - $old_quantity) / $product['length'] * $product['weight'];
                         }
                     }
                 } elseif ($product['unit_type'] == 2) {
                     if ($oldDefectItem->unit_type == 1) {
                         $old_quantity = $oldDefectItem->quantity / $product['length'] * $product['weight'];
                         if ($old_quantity > $product['receive_quantity']) {
                             $rawStock->quantity -= $old_quantity - $product['receive_quantity'];
                         } elseif ($old_quantity < $product['receive_quantity']) {
                             $rawStock->quantity += $product['receive_quantity'] - $old_quantity;
                         }
                     } elseif ($oldDefectItem->unit_type == 2) {
                         if ($oldDefectItem->quantity > $product['receive_quantity']) {
                             $rawStock->quantity -= $oldDefectItem->quantity - $product['receive_quantity'];
                         } elseif ($oldDefectItem->quantity < $product['receive_quantity']) {
                             $rawStock->quantity += $product['receive_quantity'] - $oldDefectItem->quantity;
                         }
                     }
                 }
                 $rawStock->updated_by = $user->id;
                 $rawStock->updated_at = $time;
                 $rawStock->update();
             }
             //New Defect Items
             if (!empty($inputs['product'])) {
                 foreach ($inputs['product'] as $product) {
                     $defectItem = new DefectItem();
                     $defectItem->defect_id = $id;
                     $defectItem->product_id = $product['product_id'];
                     $defectItem->quantity = $product['receive_quantity'];
                     $defectItem->unit_type = $product['unit_type'];
                     $defectItem->unit_price = $product['unit_price'];
                     $defectItem->created_by = $user->id;
                     $defectItem->created_at = $time;
                     $defectItem->save();
                     //Material stock updated
                     $rawStock = RawStock::where('year', '=', $year)->where('stock_type', '=', Config::get('common.balance_type_intermediate'))->where('material_id', '=', $material->id)->first();
                     if ($product['unit_type'] == 1) {
                         $rawStock->quantity += $product['receive_quantity'] / $product['length'] * $product['weight'];
                     } else {
                         $rawStock->quantity += $product['receive_quantity'];
                     }
                     $rawStock->updated_by = $user->id;
                     $rawStock->updated_at = $time;
                     $rawStock->update();
                 }
             }
             if ($inputs['cash'] && !$oldDefect->cash) {
                 //Cash
                 $journal = new GeneralJournal();
                 $journal->date = $date;
                 $journal->transaction_type = $transaction_type;
                 $journal->reference_id = $id;
                 $journal->year = $year;
                 $journal->account_code = 11000;
                 //Cash
                 $journal->dr_cr_indicator = Config::get('common.debit_credit_indicator.credit');
                 $journal->workspace_id = $user->workspace_id;
                 $journal->amount = $inputs['cash'];
                 $journal->created_by = $user->id;
                 $journal->created_at = $time;
                 $journal->save();
                 $workspace = WorkspaceLedger::where(['account_code' => 11000, 'workspace_id' => $user->workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance -= $inputs['cash'] - $oldDefect->cash;
                 //sub cash
                 $workspace->updated_by = $user->id;
                 $workspace->updated_at = $time;
                 $workspace->update();
             } elseif (!$inputs['cash'] && $oldDefect->cash) {
                 //Cash
                 $journal = GeneralJournal::where('account_code', '=', 11000)->where('workspace_id', '=', $user->workspace_id)->where('reference_id', '=', $id)->where('transaction_type', '=', $transaction_type)->where('year', '=', $year)->first();
                 $journal->delete();
                 $workspace = WorkspaceLedger::where(['account_code' => 11000, 'workspace_id' => $user->workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance += $oldDefect->cash;
                 //add cash
                 $workspace->updated_by = $user->id;
                 $workspace->updated_at = $time;
                 $workspace->update();
             } elseif ($inputs['cash'] > $oldDefect->cash) {
                 $workspace = WorkspaceLedger::where(['account_code' => 11000, 'workspace_id' => $user->workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 if ($workspace->balance < $inputs['cash'] - $oldDefect->cash) {
                     Session()->flash('warning_message', 'Insufficient cash balance!.');
                     throw new \Exception();
                 }
                 $workspace->balance -= $inputs['cash'] - $oldDefect->cash;
                 //sub cash
                 $workspace->updated_by = $user->id;
                 $workspace->updated_at = $time;
                 $workspace->update();
                 $journal = GeneralJournal::where('account_code', '=', 11000)->where('workspace_id', '=', $user->workspace_id)->where('reference_id', '=', $id)->where('transaction_type', '=', $transaction_type)->where('year', '=', $year)->first();
                 $journal->amount = $inputs['cash'];
                 $journal->updated_by = $user->id;
                 $journal->updated_at = $time;
                 $journal->update();
             } elseif ($inputs['cash'] < $oldDefect->cash) {
                 $journal = GeneralJournal::where('account_code', '=', 11000)->where('workspace_id', '=', $user->workspace_id)->where('reference_id', '=', $id)->where('transaction_type', '=', $transaction_type)->where('year', '=', $year)->first();
                 $journal->amount = $inputs['cash'];
                 $journal->updated_by = $user->id;
                 $journal->updated_at = $time;
                 $journal->update();
                 $workspace = WorkspaceLedger::where(['account_code' => 11000, 'workspace_id' => $user->workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance += $oldDefect->cash - $inputs['cash'];
                 //add cash
                 $workspace->updated_by = $user->id;
                 $workspace->updated_at = $time;
                 $workspace->update();
             }
             if ($inputs['due_paid'] && !$oldDefect->due_paid) {
                 //Due Pay
                 $journal = new GeneralJournal();
                 $journal->date = $date;
                 $journal->transaction_type = $transaction_type;
                 $journal->reference_id = $defect->id;
                 $journal->year = $year;
                 $journal->account_code = 12000;
                 //Account Receivable
                 $journal->dr_cr_indicator = Config::get('common.debit_credit_indicator.credit');
                 $journal->workspace_id = $user->workspace_id;
                 $journal->amount = $inputs['due_paid'];
                 $journal->created_by = $user->id;
                 $journal->created_at = $time;
                 $journal->save();
                 $workspace = WorkspaceLedger::where(['account_code' => 12000, 'workspace_id' => $user->workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance -= $inputs['due_paid'];
                 //sub account receivable
                 $workspace->updated_by = $user->id;
                 $workspace->updated_at = $time;
                 $workspace->update();
                 $personalAccount = PersonalAccount::where('person_type', '=', $oldDefect->customer_type)->where('person_id', '=', $inputs['customer_id'])->first();
                 $personalAccount->due -= $inputs['due_paid'];
                 //Sub due
                 $personalAccount->updated_by = $user->id;
                 $personalAccount->updated_at = $time;
                 $personalAccount->update();
             } elseif (!$inputs['due_paid'] && $oldDefect->due_paid) {
                 $journal = GeneralJournal::where('account_code', '=', 12000)->where('workspace_id', '=', $user->workspace_id)->where('reference_id', '=', $id)->where('transaction_type', '=', $transaction_type)->where('year', '=', $year)->first();
                 $journal->delete();
                 $workspace = WorkspaceLedger::where(['account_code' => 12000, 'workspace_id' => $user->workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance += $oldDefect->due_paid;
                 //add account receivable
                 $workspace->updated_by = $user->id;
                 $workspace->updated_at = $time;
                 $workspace->update();
                 $personalAccount = PersonalAccount::where('person_type', '=', $oldDefect->customer_type)->where('person_id', '=', $inputs['customer_id'])->first();
                 $personalAccount->due += $oldDefect->due_paid;
                 //add due
                 $personalAccount->updated_by = $user->id;
                 $personalAccount->updated_at = $time;
                 $personalAccount->update();
             } elseif ($inputs['due_paid'] > $oldDefect->due_paid) {
                 $journal = GeneralJournal::where('account_code', '=', 12000)->where('workspace_id', '=', $user->workspace_id)->where('reference_id', '=', $id)->where('transaction_type', '=', $transaction_type)->where('year', '=', $year)->first();
                 $journal->amount = $inputs['due_paid'];
                 $journal->updated_by = $user->id;
                 $journal->updated_at = $time;
                 $journal->update();
                 $workspace = WorkspaceLedger::where(['account_code' => 12000, 'workspace_id' => $user->workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance -= $inputs['due_paid'] - $oldDefect->due_paid;
                 //sub account receivable
                 $workspace->updated_by = $user->id;
                 $workspace->updated_at = $time;
                 $workspace->update();
                 $personalAccount = PersonalAccount::where('person_type', '=', $oldDefect->customer_type)->where('person_id', '=', $inputs['customer_id'])->first();
                 $personalAccount->due -= $inputs['due_paid'] - $oldDefect->due_paid;
                 //Sub due
                 $personalAccount->updated_by = $user->id;
                 $personalAccount->updated_at = $time;
                 $personalAccount->update();
             } elseif ($inputs['due_paid'] < $oldDefect->due_paid) {
                 $journal = GeneralJournal::where('account_code', '=', 12000)->where('workspace_id', '=', $user->workspace_id)->where('reference_id', '=', $id)->where('transaction_type', '=', $transaction_type)->where('year', '=', $year)->first();
                 $journal->amount = $inputs['due_paid'];
                 $journal->updated_by = $user->id;
                 $journal->updated_at = $time;
                 $journal->update();
                 $workspace = WorkspaceLedger::where(['account_code' => 12000, 'workspace_id' => $user->workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance += $oldDefect->due_paid - $inputs['due_paid'];
                 //add account receivable
                 $workspace->updated_by = $user->id;
                 $workspace->updated_at = $time;
                 $workspace->update();
                 $personalAccount = PersonalAccount::where('person_type', '=', $oldDefect->customer_type)->where('person_id', '=', $oldDefect->customer_id)->first();
                 $personalAccount->due += $oldDefect->due_paid - $inputs['due_paid'];
                 //add due
                 $personalAccount->updated_by = $user->id;
                 $personalAccount->updated_at = $time;
                 $personalAccount->update();
             }
             if ($inputs['due'] && !$oldDefect->due) {
                 // Due
                 $journal = new GeneralJournal();
                 $journal->date = $date;
                 $journal->transaction_type = $transaction_type;
                 $journal->reference_id = $defect->id;
                 $journal->year = $year;
                 $journal->account_code = 41000;
                 //Account Payable
                 $journal->dr_cr_indicator = Config::get('common.debit_credit_indicator.credit');
                 $journal->workspace_id = $user->workspace_id;
                 $journal->amount = $inputs['due'];
                 $journal->created_by = $user->id;
                 $journal->created_at = $time;
                 $journal->save();
                 $workspace = WorkspaceLedger::where(['account_code' => 41000, 'workspace_id' => $user->workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance += $inputs['due'];
                 //add account payable
                 $workspace->updated_by = $user->id;
                 $workspace->updated_at = $time;
                 $workspace->update();
                 $personalAccount = PersonalAccount::where('person_type', '=', $oldDefect->customer_type)->where('person_id', '=', $inputs['customer_id'])->first();
                 $personalAccount->balance += $inputs['due'];
                 //Add Balance
                 $personalAccount->updated_by = $user->id;
                 $personalAccount->updated_at = $time;
                 $personalAccount->update();
             } elseif (!$inputs['due'] && $oldDefect->due) {
                 // Due
                 $journal = GeneralJournal::where('account_code', '=', 41000)->where('workspace_id', '=', $user->workspace_id)->where('reference_id', '=', $id)->where('transaction_type', '=', $transaction_type)->where('year', '=', $year)->first();
                 $journal->delete();
                 $workspace = WorkspaceLedger::where(['account_code' => 41000, 'workspace_id' => $user->workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance -= $oldDefect->due;
                 //sub account payable
                 $workspace->updated_by = $user->id;
                 $workspace->updated_at = $time;
                 $workspace->update();
                 $personalAccount = PersonalAccount::where('person_type', '=', $oldDefect->customer_type)->where('person_id', '=', $inputs['customer_id'])->first();
                 $personalAccount->balance -= $oldDefect->due;
                 //Sub Balance
                 $personalAccount->updated_by = $user->id;
                 $personalAccount->updated_at = $time;
                 $personalAccount->update();
             } elseif ($inputs['due'] > $oldDefect->due) {
                 // Due
                 $journal = GeneralJournal::where('account_code', '=', 41000)->where('workspace_id', '=', $user->workspace_id)->where('reference_id', '=', $id)->where('transaction_type', '=', $transaction_type)->where('year', '=', $year)->first();
                 $journal->amount = $inputs['due'];
                 $journal->updated_by = $user->id;
                 $journal->updated_at = $time;
                 $journal->update();
                 $workspace = WorkspaceLedger::where(['account_code' => 41000, 'workspace_id' => $user->workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance += $inputs['due'] - $oldDefect->due;
                 //add account payable
                 $workspace->updated_by = $user->id;
                 $workspace->updated_at = $time;
                 $workspace->update();
                 $personalAccount = PersonalAccount::where('person_type', '=', $oldDefect->customer_type)->where('person_id', '=', $inputs['customer_id'])->first();
                 $personalAccount->balance += $inputs['due'] - $oldDefect->due;
                 //Add Balance
                 $personalAccount->updated_by = $user->id;
                 $personalAccount->updated_at = $time;
                 $personalAccount->update();
             } elseif ($inputs['due'] < $oldDefect->due) {
                 // Due
                 $journal = GeneralJournal::where('account_code', '=', 41000)->where('workspace_id', '=', $user->workspace_id)->where('reference_id', '=', $id)->where('transaction_type', '=', $transaction_type)->where('year', '=', $year)->first();
                 $journal->amount = $inputs['due'];
                 $journal->updated_by = $user->id;
                 $journal->updated_at = $time;
                 $journal->update();
                 $workspace = WorkspaceLedger::where(['account_code' => 41000, 'workspace_id' => $user->workspace_id, 'balance_type' => $balance_type, 'year' => $year])->first();
                 $workspace->balance -= $oldDefect->due - $inputs['due'];
                 //sub account payable
                 $workspace->updated_by = $user->id;
                 $workspace->updated_at = $time;
                 $workspace->update();
                 $personalAccount = PersonalAccount::where('person_type', '=', $oldDefect->customer_type)->where('person_id', '=', $inputs['customer_id'])->first();
                 $personalAccount->balance -= $oldDefect->due - $inputs['due'];
                 //sub Balance
                 $personalAccount->updated_by = $user->id;
                 $personalAccount->updated_at = $time;
                 $personalAccount->update();
             }
             if (isset($inputs['is_replacement']) && !$oldDefect->is_replacement) {
                 //Replacement
                 $defectReplacement = new SalesOrder();
                 $defectReplacement->workspace_id = $user->workspace_id;
                 $defectReplacement->defect_id = $defect->id;
                 $defectReplacement->order_type = Config::get('common.sales_order_type.replacement');
                 $defectReplacement->customer_id = $inputs['customer_id'];
                 $defectReplacement->customer_type = $oldDefect->customer_type;
                 $defectReplacement->total = $inputs['new_total'];
                 $defectReplacement->date = $time;
                 $defectReplacement->delivery_status = 1;
                 $defectReplacement->created_by = $user->id;
                 $defectReplacement->created_at = $time;
                 $defectReplacement->save();
                 foreach ($inputs['new_product'] as $new_product) {
                     $defectReplacementItem = new SalesOrderItem();
                     $defectReplacementItem->sales_order_id = $defectReplacement->id;
                     $defectReplacementItem->product_id = $new_product['product_id'];
                     $defectReplacementItem->sales_quantity = $new_product['sales_quantity'];
                     $defectReplacementItem->sales_unit_type = $new_product['sales_unit_type'];
                     $defectReplacementItem->unit_price = $new_product['unit_price'];
                     $defectReplacementItem->created_by = $user->id;
                     $defectReplacementItem->created_at = $time;
                     $defectReplacementItem->save();
                     $stock = Stock::where('product_id', '=', $new_product['product_id'])->where('stock_type', '=', $balance_type)->where('year', '=', $year)->first();
                     if ($new_product['sales_unit_type'] == 1) {
                         if ($stock->quantity < $new_product['sales_quantity']) {
                             Session()->flash('warning_message', 'Insufficient stock!.');
                             throw new \Exception();
                         }
                         $stock->quantity -= $new_product['sales_quantity'];
                         //Sub stock
                     } elseif ($new_product['sales_unit_type'] == 2) {
                         $sales_quantity = $new_product['sales_quantity'] / $new_product['weight'] * $new_product['length'];
                         if ($stock->quantity < $sales_quantity) {
                             Session()->flash('warning_message', 'Insufficient stock!.');
                             throw new \Exception();
                         }
                         $stock->quantity -= $sales_quantity;
                         //Sub stock
                     }
                     $stock->updated_by = $user->id;
                     $stock->updated_at = $time;
                     $stock->update();
                 }
             } elseif (isset($inputs['is_replacement']) && $oldDefect->is_replacement) {
                 $defectReplacement = SalesOrder::where('defect_id', '=', $id)->first();
                 $oldDefectReplacement = clone $defectReplacement;
                 $defectReplacement->total = $inputs['new_total'];
                 $defectReplacement->updated_by = $user->id;
                 $defectReplacement->updated_at = $time;
                 $defectReplacement->update();
                 if (isset($inputs['delete_replacement_product'])) {
                     foreach ($inputs['delete_replacement_product'] as $product) {
                         $defectReplacementItem = SalesOrderItem::where('sales_order_id', '=', $defectReplacement->id)->where('product_id', '=', $product['product_id'])->first();
                         if ($defectReplacementItem) {
                             $defectReplacementItem->delete();
                         }
                     }
                 }
                 //Old Product
                 foreach ($inputs['old_replacement_product'] as $new_product) {
                     $defectReplacementItem = SalesOrderItem::where('sales_order_id', '=', $defectReplacement->id)->where('product_id', '=', $new_product['product_id'])->first();
                     $oldDefectReplacementItem = clone $defectReplacementItem;
                     $defectReplacementItem->sales_quantity = $new_product['sales_quantity'];
                     $defectReplacementItem->sales_unit_type = $new_product['sales_unit_type'];
                     $defectReplacementItem->unit_price = $new_product['unit_price'];
                     $defectReplacementItem->updated_by = $user->id;
                     $defectReplacementItem->updated_at = $time;
                     $defectReplacementItem->update();
                     $stock = Stock::where('product_id', '=', $new_product['product_id'])->where('stock_type', '=', $balance_type)->where('year', '=', $year)->first();
                     if ($oldDefectReplacementItem->sales_unit_type == 1) {
                         if ($new_product['sales_unit_type'] == 1) {
                             if ($oldDefectReplacementItem->sales_quantity > $new_product['sales_quantity']) {
                                 $stock->quantity += $oldDefectReplacementItem->sales_quantity - $new_product['sales_quantity'];
                                 //Add stock
                             } elseif ($oldDefectReplacementItem->sales_quantity < $new_product['sales_quantity']) {
                                 $sales_quantity = $new_product['sales_quantity'] - $oldDefectReplacementItem->sales_quantity;
                                 if ($stock->quantity < $sales_quantity) {
                                     Session()->flash('warning_message', 'Insufficient stock!.');
                                     throw new \Exception();
                                 }
                                 $stock->quantity -= $sales_quantity;
                                 //Sub stock
                             }
                         } elseif ($new_product['sales_unit_type'] == 2) {
                             $new_sales_quantity = $new_product['sales_quantity'] / $new_product['weight'] * $new_product['length'];
                             if ($oldDefectReplacementItem->sales_quantity > $new_sales_quantity) {
                                 $stock->quantity += $oldDefectReplacementItem->sales_quantity - $new_sales_quantity;
                                 //Add stock
                             } elseif ($oldDefectReplacementItem->sales_quantity < $new_sales_quantity) {
                                 $sales_quantity = $new_sales_quantity - $oldDefectReplacementItem->sales_quantity;
                                 if ($stock->quantity < $sales_quantity) {
                                     Session()->flash('warning_message', 'Insufficient stock!.');
                                     throw new \Exception();
                                 }
                                 $stock->quantity -= $sales_quantity;
                                 //Sub stock
                             }
                         }
                     } elseif ($oldDefectReplacementItem->sales_unit_type == 2) {
                         if ($new_product['sales_unit_type'] == 1) {
                             $new_sales_quantity = $oldDefectReplacementItem->sales_quantity / $new_product['weight'] * $new_product['length'];
                             if ($new_sales_quantity > $new_product['sales_quantity']) {
                                 $stock->quantity += $new_sales_quantity - $new_product['sales_quantity'];
                                 $stock->quantity += $new_sales_quantity - $new_product['sales_quantity'];
                                 //Add stock
                             } elseif ($new_sales_quantity < $new_product['sales_quantity']) {
                                 $sales_quantity = $new_product['sales_quantity'] - $new_sales_quantity;
                                 //Sub stock
                                 if ($stock->quantity < $sales_quantity) {
                                     Session()->flash('warning_message', 'Insufficient stock!.');
                                     throw new \Exception();
                                 }
                                 $stock->quantity -= $sales_quantity;
                                 //Sub stock
                             }
                         } elseif ($new_product['sales_unit_type'] == 2) {
                             $old_sales_quantity = $oldDefectReplacementItem->sales_quantity / $new_product['weight'] * $new_product['length'];
                             $new_sales_quantity = $new_product['sales_quantity'] / $new_product['weight'] * $new_product['length'];
                             if ($old_sales_quantity > $new_sales_quantity) {
                                 $stock->quantity += $old_sales_quantity - $new_sales_quantity;
                                 //Add stock
                             } elseif ($old_sales_quantity < $new_sales_quantity) {
                                 $sales_quantity = $new_sales_quantity - $old_sales_quantity;
                                 if ($stock->quantity < $sales_quantity) {
                                     Session()->flash('warning_message', 'Insufficient stock!.');
                                     throw new \Exception();
                                 }
                                 $stock->quantity -= $sales_quantity;
                                 //Sub stock
                             }
                         }
                     }
                     $stock->updated_by = $user->id;
                     $stock->updated_at = $time;
                     $stock->update();
                 }
                 //New Product
                 if (!empty($inputs['new_product'])) {
                     foreach ($inputs['new_product'] as $new_product) {
                         $defectReplacementItem = new SalesOrderItem();
                         $defectReplacementItem->sales_order_id = $defectReplacement->id;
                         $defectReplacementItem->product_id = $new_product['product_id'];
                         $defectReplacementItem->sales_quantity = $new_product['sales_quantity'];
                         $defectReplacementItem->sales_unit_type = $new_product['sales_unit_type'];
                         $defectReplacementItem->unit_price = $new_product['unit_price'];
                         $defectReplacementItem->created_by = $user->id;
                         $defectReplacementItem->created_at = $time;
                         $defectReplacementItem->save();
                         $stock = Stock::where('product_id', '=', $new_product['product_id'])->where('stock_type', '=', $balance_type)->where('year', '=', $year)->first();
                         $stock->quantity -= $new_product['sales_quantity'];
                         //Sub stock
                         $stock->updated_by = $user->id;
                         $stock->updated_at = $time;
                         $stock->update();
                     }
                 }
             } elseif (!isset($inputs['is_replacement']) && $oldDefect->is_replacement) {
                 $defectReplacement = SalesOrder::where('defect_id', '=', $id)->first();
                 $oldDefectReplacement = clone $defectReplacement;
                 $defectReplacement->total = $inputs['new_total'];
                 $defectReplacement->updated_by = $user->id;
                 $defectReplacement->updated_at = $time;
                 $defectReplacement->update();
                 if (isset($inputs['delete_replacement_product'])) {
                     foreach ($inputs['delete_replacement_product'] as $product) {
                         $defectReplacementItem = SalesOrderItem::where('sales_order_id', '=', $defectReplacement->id)->where('product_id', '=', $product['product_id'])->first();
                         if ($defectReplacementItem) {
                             $defectReplacementItem->delete();
                         }
                     }
                 }
                 //Old Product
                 foreach ($inputs['old_replacement_product'] as $new_product) {
                     $defectReplacementItem = SalesOrderItem::where('sales_order_id', '=', $defectReplacement->id)->where('product_id', '=', $new_product['product_id'])->first();
                     $oldDefectReplacementItem = clone $defectReplacementItem;
                     $defectReplacementItem->sales_quantity = $new_product['sales_quantity'];
                     $defectReplacementItem->sales_unit_type = $new_product['sales_unit_type'];
                     $defectReplacementItem->unit_price = $new_product['unit_price'];
                     $defectReplacementItem->updated_by = $user->id;
                     $defectReplacementItem->updated_at = $time;
                     $defectReplacementItem->update();
                     $stock = Stock::where('product_id', '=', $new_product['product_id'])->where('stock_type', '=', $balance_type)->where('year', '=', $year)->first();
                     if ($oldDefectReplacementItem->sales_unit_type == 1) {
                         if ($new_product['sales_unit_type'] == 1) {
                             if ($oldDefectReplacementItem->sales_quantity > $new_product['sales_quantity']) {
                                 $stock->quantity += $oldDefectReplacementItem->sales_quantity - $new_product['sales_quantity'];
                                 //Add stock
                             } elseif ($oldDefectReplacementItem->sales_quantity < $new_product['sales_quantity']) {
                                 $sales_quantity = $new_product['sales_quantity'] - $oldDefectReplacementItem->sales_quantity;
                                 if ($stock->quantity < $sales_quantity) {
                                     Session()->flash('warning_message', 'Insufficient stock!.');
                                     throw new \Exception();
                                 }
                                 $stock->quantity -= $sales_quantity;
                                 //Sub stock
                             }
                         } elseif ($new_product['sales_unit_type'] == 2) {
                             $new_sales_quantity = $new_product['sales_quantity'] / $new_product['weight'] * $new_product['length'];
                             if ($oldDefectReplacementItem->sales_quantity > $new_sales_quantity) {
                                 $stock->quantity += $oldDefectReplacementItem->sales_quantity - $new_sales_quantity;
                                 //Add stock
                             } elseif ($oldDefectReplacementItem->sales_quantity < $new_sales_quantity) {
                                 $sales_quantity = $new_sales_quantity - $oldDefectReplacementItem->sales_quantity;
                                 if ($stock->quantity < $sales_quantity) {
                                     Session()->flash('warning_message', 'Insufficient stock!.');
                                     throw new \Exception();
                                 }
                                 $stock->quantity -= $sales_quantity;
                                 //Sub stock
                             }
                         }
                     } elseif ($oldDefectReplacementItem->sales_unit_type == 2) {
                         if ($new_product['sales_unit_type'] == 1) {
                             $new_sales_quantity = $oldDefectReplacementItem->sales_quantity / $new_product['weight'] * $new_product['length'];
                             if ($new_sales_quantity > $new_product['sales_quantity']) {
                                 $stock->quantity += $new_sales_quantity - $new_product['sales_quantity'];
                                 $stock->quantity += $new_sales_quantity - $new_product['sales_quantity'];
                                 //Add stock
                             } elseif ($new_sales_quantity < $new_product['sales_quantity']) {
                                 $sales_quantity = $new_product['sales_quantity'] - $new_sales_quantity;
                                 //Sub stock
                                 if ($stock->quantity < $sales_quantity) {
                                     Session()->flash('warning_message', 'Insufficient stock!.');
                                     throw new \Exception();
                                 }
                                 $stock->quantity -= $sales_quantity;
                                 //Sub stock
                             }
                         } elseif ($new_product['sales_unit_type'] == 2) {
                             $old_sales_quantity = $oldDefectReplacementItem->sales_quantity / $new_product['weight'] * $new_product['length'];
                             $new_sales_quantity = $new_product['sales_quantity'] / $new_product['weight'] * $new_product['length'];
                             if ($old_sales_quantity > $new_sales_quantity) {
                                 $stock->quantity += $old_sales_quantity - $new_sales_quantity;
                                 //Add stock
                             } elseif ($old_sales_quantity < $new_sales_quantity) {
                                 $sales_quantity = $new_sales_quantity - $old_sales_quantity;
                                 if ($stock->quantity < $sales_quantity) {
                                     Session()->flash('warning_message', 'Insufficient stock!.');
                                     throw new \Exception();
                                 }
                                 $stock->quantity -= $sales_quantity;
                                 //Sub stock
                             }
                         }
                     }
                     $stock->updated_by = $user->id;
                     $stock->updated_at = $time;
                     $stock->update();
                 }
             }
         });
     } catch (\Exception $e) {
         Session()->flash('error_message', 'Defect receive update not success. Please try again.');
         return Redirect::back();
     }
     Session()->flash('flash_message', 'Defect receive updated successfully.');
     return redirect('receive_defect');
 }
 public function otherStocksInSector($sectorName)
 {
     return view('layouts.partials.other-stocks-in-sector')->with(['selectedSector' => $sectorName, 'stocksInSector' => StockMetrics::getMetricsByStockList(Stock::where('sector', $sectorName)->lists('stock_code'), 'all')]);
 }
Ejemplo n.º 13
0
 public function store(Request $request)
 {
     $workspace_id = Auth::user()->workspace_id;
     $closedWorkspace = AccountClosing::where(['year' => CommonHelper::get_current_financial_year(), 'type' => 1, 'workspace_id' => $workspace_id])->lists('workspace_id');
     if (sizeof($closedWorkspace) == 0) {
         try {
             DB::transaction(function () use($request) {
                 $workspace_id = Auth::user()->workspace_id;
                 $levelZeros = ChartOfAccount::where(['parent' => 0, 'status' => 1])->select('id', 'name', 'code')->get();
                 foreach ($levelZeros as $levelZero) {
                     $workspaceData = WorkspaceLedger::where(['workspace_id' => $workspace_id, 'account_code' => $levelZero->code, 'balance_type' => Config::get('common.balance_type_intermediate'), 'year' => CommonHelper::get_current_financial_year()])->first();
                     $balance = isset($workspaceData->balance) ? $workspaceData->balance : 0;
                     $a[] = [$levelZero->id, $levelZero->code, '', $balance];
                 }
                 for ($ci = 0; isset($a[$ci][0]); $ci++) {
                     $nextLevels = ChartOfAccount::where(['parent' => $a[$ci][0], 'status' => 1])->get(['code', 'id']);
                     foreach ($nextLevels as $nextLevel) {
                         $NextLevelWorkspaceData = WorkspaceLedger::where(['workspace_id' => $workspace_id, 'account_code' => $nextLevel->code, 'balance_type' => Config::get('common.balance_type_intermediate'), 'year' => CommonHelper::get_current_financial_year()])->first();
                         $nextLevelBalance = isset($NextLevelWorkspaceData->balance) ? $NextLevelWorkspaceData->balance : 0;
                         $a[] = [$nextLevel->id, $nextLevel->code, $ci, $nextLevelBalance];
                     }
                 }
                 $ci = sizeof($a) - 1;
                 for (; $ci >= 0; $ci--) {
                     if (isset($a[$a[$ci][2]][3])) {
                         $contra = ChartOfAccount::where(['contra_status' => 1, 'id' => $a[$ci][0]])->first();
                         if ($contra) {
                             $a[$a[$ci][2]][3] -= $a[$ci][3];
                         } else {
                             $a[$a[$ci][2]][3] += $a[$ci][3];
                         }
                     }
                     // Closing Balance
                     $workspaceLedger = new WorkspaceLedger();
                     $workspaceLedger->workspace_id = $workspace_id;
                     $workspaceLedger->year = CommonHelper::get_current_financial_year();
                     $workspaceLedger->account_code = $a[$ci][1];
                     $workspaceLedger->balance_type = Config::get('common.balance_type_closing');
                     $workspaceLedger->balance = $a[$ci][3];
                     $workspaceLedger->created_by = Auth::user()->id;
                     $workspaceLedger->created_at = time();
                     $workspaceLedger->save();
                     if (substr($a[$ci][1], 0, 1) == 1 || substr($a[$ci][1], 0, 1) == 4 || substr($a[$ci][1], 0, 1) == 6) {
                         // Initial Balance Next Year
                         $workspaceLedger = new WorkspaceLedger();
                         $workspaceLedger->workspace_id = $workspace_id;
                         $workspaceLedger->year = CommonHelper::get_next_financial_year();
                         $workspaceLedger->account_code = $a[$ci][1];
                         $workspaceLedger->balance_type = Config::get('common.balance_type_opening');
                         $workspaceLedger->balance = $a[$ci][3];
                         $workspaceLedger->created_by = Auth::user()->id;
                         $workspaceLedger->created_at = time();
                         $workspaceLedger->save();
                         // Intermediate Balance Next Year
                         $workspaceLedger = new WorkspaceLedger();
                         $workspaceLedger->workspace_id = $workspace_id;
                         $workspaceLedger->year = CommonHelper::get_next_financial_year();
                         $workspaceLedger->account_code = $a[$ci][1];
                         $workspaceLedger->balance_type = Config::get('common.balance_type_intermediate');
                         $workspaceLedger->balance = $a[$ci][3];
                         $workspaceLedger->created_by = Auth::user()->id;
                         $workspaceLedger->created_at = time();
                         $workspaceLedger->save();
                     } else {
                         // Initial Balance Next Year
                         $workspaceLedger = new WorkspaceLedger();
                         $workspaceLedger->workspace_id = $workspace_id;
                         $workspaceLedger->year = CommonHelper::get_next_financial_year();
                         $workspaceLedger->account_code = $a[$ci][1];
                         $workspaceLedger->balance_type = Config::get('common.balance_type_opening');
                         $workspaceLedger->balance = 0;
                         $workspaceLedger->created_by = Auth::user()->id;
                         $workspaceLedger->created_at = time();
                         $workspaceLedger->save();
                         // Intermediate Balance Next Year
                         $workspaceLedger = new WorkspaceLedger();
                         $workspaceLedger->workspace_id = $workspace_id;
                         $workspaceLedger->year = CommonHelper::get_next_financial_year();
                         $workspaceLedger->account_code = $a[$ci][1];
                         $workspaceLedger->balance_type = Config::get('common.balance_type_intermediate');
                         $workspaceLedger->balance = 0;
                         $workspaceLedger->created_by = Auth::user()->id;
                         $workspaceLedger->created_at = time();
                         $workspaceLedger->save();
                     }
                 }
                 // Workspace Account Close Info
                 $accountClosing = new AccountClosing();
                 $accountClosing->workspace_id = $workspace_id;
                 $accountClosing->year = CommonHelper::get_current_financial_year();
                 $accountClosing->save();
                 // Workspace Stock Closing
                 $existingStocks = Stock::where(['stock_type' => Config::get('common.balance_type_intermediate'), 'workspace_id' => $workspace_id, 'year' => CommonHelper::get_current_financial_year()])->get();
                 if (sizeof($existingStocks) > 0) {
                     foreach ($existingStocks as $existingStock) {
                         // Current Year Closing Balance
                         $stock = new Stock();
                         $stock->year = CommonHelper::get_current_financial_year();
                         $stock->stock_type = Config::get('common.balance_type_closing');
                         $stock->workspace_id = $workspace_id;
                         $stock->product_id = $existingStock->product_id;
                         $stock->quantity = $existingStock->quantity;
                         $stock->created_by = Auth::user()->id;
                         $stock->created_at = time();
                         $stock->save();
                         // Next Year Opening Balance
                         $stock = new Stock();
                         $stock->year = CommonHelper::get_next_financial_year();
                         $stock->stock_type = Config::get('common.balance_type_opening');
                         $stock->workspace_id = $workspace_id;
                         $stock->product_id = $existingStock->product_id;
                         $stock->quantity = $existingStock->quantity;
                         $stock->created_by = Auth::user()->id;
                         $stock->created_at = time();
                         $stock->save();
                         // Next Year Intermediate Balance
                         $stock = new Stock();
                         $stock->year = CommonHelper::get_next_financial_year();
                         $stock->stock_type = Config::get('common.balance_type_intermediate');
                         $stock->workspace_id = $workspace_id;
                         $stock->product_id = $existingStock->product_id;
                         $stock->quantity = $existingStock->quantity;
                         $stock->created_by = Auth::user()->id;
                         $stock->created_at = time();
                         $stock->save();
                     }
                 }
             });
         } catch (\Exception $e) {
             Session()->flash('error_message', 'Workspace Account Closing Not Done!');
             return redirect('workspace_closing');
         }
         Session()->flash('flash_message', 'Workspace Account Closed Successfully!');
         return redirect('workspace_closing');
     } else {
         Session()->flash('warning_message', 'Workspace Account Closed Already For This Year!');
         return redirect('workspace_closing');
     }
 }
Ejemplo n.º 14
0
 public function store(Request $request)
 {
     try {
         DB::transaction(function () use($request) {
             $workspace_id = $request->workspace_id;
             if ($workspace_id > 0) {
                 $currentYear = CommonHelper::get_current_financial_year();
                 $closingStatus = DB::table('account_closings')->where(['year' => $currentYear, 'workspace_id' => $workspace_id])->value('status');
                 $existingYearDetail = DB::table('financial_years')->where('year', $currentYear)->first();
                 if ($closingStatus == 1) {
                     if ($existingYearDetail->end_date > strtotime(date('Y-m-d'))) {
                         // Delete Workspace Closing Balance Data of Current Year
                         WorkspaceLedger::where(['workspace_id' => $workspace_id, 'balance_type' => Config::get('common.balance_type_closing'), 'year' => CommonHelper::get_current_financial_year()])->delete();
                         // Delete Next Year Opening Balance Data
                         WorkspaceLedger::where(['workspace_id' => $workspace_id, 'balance_type' => Config::get('common.balance_type_opening'), 'year' => CommonHelper::get_next_financial_year()])->delete();
                         // Delete Next Year Intermediate Balance Data
                         WorkspaceLedger::where(['workspace_id' => $workspace_id, 'balance_type' => Config::get('common.balance_type_intermediate'), 'year' => CommonHelper::get_next_financial_year()])->delete();
                         //  Delete Stock Table Current Year Closing Balance Data
                         Stock::where(['workspace_id' => $workspace_id, 'stock_type' => Config::get('common.balance_type_closing'), 'year' => CommonHelper::get_current_financial_year()])->delete();
                         // Delete Next Year Opening Balance Data
                         Stock::where(['workspace_id' => $workspace_id, 'stock_type' => Config::get('common.balance_type_opening'), 'year' => CommonHelper::get_next_financial_year()])->delete();
                         // Delete Stock Table Next Year Intermediate Balance Data
                         Stock::where(['workspace_id' => $workspace_id, 'stock_type' => Config::get('common.balance_type_intermediate'), 'year' => CommonHelper::get_next_financial_year()])->delete();
                         // Delete Account Closing Data
                         AccountClosing::where(['workspace_id' => $workspace_id, 'year' => CommonHelper::get_current_financial_year(), 'type' => 1])->delete();
                     } else {
                         Session()->flash('warning_message', 'Alert: Time Over!');
                         throw new \Exception('error');
                     }
                 } else {
                     Session()->flash('warning_message', 'Alert: Workspace Not Closed Yet!');
                     throw new \Exception('error');
                 }
             } else {
                 // Total System is being rolled back to the previous year
                 // Delete General Ledger Current Year Closing Data
                 GeneralLedger::where(['balance_type' => Config::get('common.balance_type_closing'), 'year' => CommonHelper::get_previous_financial_year()])->delete();
                 // Delete General Ledger Next Year Opening Data
                 GeneralLedger::where(['balance_type' => Config::get('common.balance_type_opening'), 'year' => CommonHelper::get_current_financial_year()])->delete();
                 // Delete General Journal Table Current Year Data
                 GeneralJournal::where(['year' => CommonHelper::get_current_financial_year()])->delete();
                 // Delete Account Closing Data
                 AccountClosing::where(['year' => CommonHelper::get_previous_financial_year(), 'type' => 2])->delete();
                 //  Delete Raw Stock Table Previous Year Closing Balance Data
                 RawStock::where(['stock_type' => Config::get('common.balance_type_closing'), 'year' => CommonHelper::get_previous_financial_year()])->delete();
                 //  Delete Raw Stock Table Current Year Opening Balance Data
                 RawStock::where(['stock_type' => Config::get('common.balance_type_opening'), 'year' => CommonHelper::get_current_financial_year()])->delete();
                 //  Delete Raw Stock Table Current Year Intermediate Balance Data
                 RawStock::where(['stock_type' => Config::get('common.balance_type_intermediate'), 'year' => CommonHelper::get_current_financial_year()])->delete();
                 // Workspaces Rollback
                 $workspaces = Workspace::where('status', '=', 1)->get();
                 foreach ($workspaces as $workspace) {
                     $workspace_id = $workspace->id;
                     // Delete Workspace Closing Balance Data of Current Year
                     WorkspaceLedger::where(['workspace_id' => $workspace_id, 'balance_type' => Config::get('common.balance_type_closing'), 'year' => CommonHelper::get_previous_financial_year()])->delete();
                     // Delete Next Year Opening Balance Data
                     WorkspaceLedger::where(['workspace_id' => $workspace_id, 'balance_type' => Config::get('common.balance_type_opening'), 'year' => CommonHelper::get_current_financial_year()])->delete();
                     // Delete Next Year Intermediate Balance Data
                     WorkspaceLedger::where(['workspace_id' => $workspace_id, 'balance_type' => Config::get('common.balance_type_intermediate'), 'year' => CommonHelper::get_current_financial_year()])->delete();
                     //  Delete Stock Table Current Year Closing Balance Data
                     Stock::where(['workspace_id' => $workspace_id, 'stock_type' => Config::get('common.balance_type_closing'), 'year' => CommonHelper::get_previous_financial_year()])->delete();
                     // Delete Next Year Opening Balance Data
                     Stock::where(['workspace_id' => $workspace_id, 'stock_type' => Config::get('common.balance_type_opening'), 'year' => CommonHelper::get_current_financial_year()])->delete();
                     // Delete Stock Table Next Year Intermediate Balance Data
                     Stock::where(['workspace_id' => $workspace_id, 'stock_type' => Config::get('common.balance_type_intermediate'), 'year' => CommonHelper::get_current_financial_year()])->delete();
                     // Delete Account Closing Data
                     AccountClosing::where(['workspace_id' => $workspace_id, 'year' => CommonHelper::get_previous_financial_year(), 'type' => 1])->delete();
                 }
                 // Fiscal Year Table Operations
                 $previous = CommonHelper::get_previous_financial_year();
                 $current = CommonHelper::get_current_financial_year();
                 // Previous Year Activate
                 DB::table('financial_years')->where('year', $previous)->update(['status' => 1]);
                 // Delete Current Financial Year
                 FinancialYear::where(['year' => $current])->delete();
             }
         });
     } catch (\Exception $e) {
         Session()->flash('error_message', 'Rollback not done!');
         return redirect('rollback');
     }
     Session()->flash('flash_message', 'Rollback Successfully done!');
     return redirect('rollback');
 }
Ejemplo n.º 15
0
 /**
  * @param $id
  * @param Request $request
  * @return \Illuminate\Http\JsonResponse
  */
 public function deleteProduct($id)
 {
     $product = Product::where('id', $id);
     $stock = Stock::where('product_id', '=', $id);
     if ($stock->count()) {
         return response()->json(['deleted' => false, 'stock' => true]);
     } else {
         if ($product->delete()) {
             return response()->json(['deleted' => true, 'stock' => false]);
         }
         return response()->json(['deleted' => false]);
     }
 }