예제 #1
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store(SaleRequest $request)
 {
     $sales = new Sale();
     $sales->customer_id = Input::get('customer_id');
     $sales->user_id = Auth::user()->id;
     $sales->payment_type = Input::get('payment_type');
     $sales->comments = Input::get('comments');
     $sales->save();
     // process sale items
     $saleItems = SaleTemp::all();
     foreach ($saleItems as $value) {
         $saleItemsData = new SaleItem();
         $saleItemsData->sale_id = $sales->id;
         $saleItemsData->item_id = $value->item_id;
         $saleItemsData->cost_price = $value->cost_price;
         $saleItemsData->selling_price = $value->selling_price;
         $saleItemsData->quantity = $value->quantity;
         $saleItemsData->total_cost = $value->total_cost;
         $saleItemsData->total_selling = $value->total_selling;
         $saleItemsData->save();
         //process inventory
         $items = Item::find($value->item_id);
         if ($items->type == 1) {
             $inventories = new Inventory();
             $inventories->item_id = $value->item_id;
             $inventories->user_id = Auth::user()->id;
             $inventories->in_out_qty = -$value->quantity;
             $inventories->remarks = 'SALE' . $sales->id;
             $inventories->save();
             //process item quantity
             $items->quantity = $items->quantity - $value->quantity;
             $items->save();
         } else {
             $itemkits = ItemKitItem::where('item_kit_id', $value->item_id)->get();
             foreach ($itemkits as $item_kit_value) {
                 $inventories = new Inventory();
                 $inventories->item_id = $item_kit_value->item_id;
                 $inventories->user_id = Auth::user()->id;
                 $inventories->in_out_qty = -($item_kit_value->quantity * $value->quantity);
                 $inventories->remarks = 'SALE' . $sales->id;
                 $inventories->save();
                 //process item quantity
                 $item_quantity = Item::find($item_kit_value->item_id);
                 $item_quantity->quantity = $item_quantity->quantity - $item_kit_value->quantity * $value->quantity;
                 $item_quantity->save();
             }
         }
     }
     //delete all data on SaleTemp model
     SaleTemp::truncate();
     $itemssale = SaleItem::where('sale_id', $saleItemsData->sale_id)->get();
     Session::flash('message', 'You have successfully added sales');
     //return Redirect::to('receivings');
     return view('sale.complete')->with('sales', $sales)->with('saleItemsData', $saleItemsData)->with('saleItems', $itemssale);
 }
예제 #2
0
 public function getPartydue($invoiceId)
 {
     $totalPrice = 0;
     $totalAmount = 0;
     $sale = Sale::where('invoice_id', '=', $invoiceId)->first();
     $saleDetails = SAleDetail::where('invoice_id', '=', $invoiceId)->get();
     $transactions = Transaction::where('invoice_id', '=', $invoiceId)->where('payment_method', '=', 'Check')->where('type', '=', 'Receive')->where('cheque_status', '=', 1)->get();
     foreach ($saleDetails as $saleDetail) {
         $totalPrice = $totalPrice + $saleDetail->price * $saleDetail->quantity;
     }
     $totalPrice -= $sale->discount_percentage;
     foreach ($transactions as $transaction) {
         $totalAmount = $totalAmount + $transaction->amount;
     }
     $transactions2 = Transaction::where('invoice_id', '=', $invoiceId)->where('type', '=', 'Receive')->where('payment_method', '!=', 'Check')->get();
     foreach ($transactions2 as $transaction) {
         $totalAmount = $totalAmount + $transaction->amount;
     }
     $due = $totalPrice - $totalAmount;
     if ($due > 0) {
         return "Due is {$due}";
     } else {
         return 'No due';
     }
 }
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index()
 {
     $exclude = \App\EventCheckin::lists('sale_checkin_id');
     $ticketsales = \App\Sale::where('created_at', '>', \Carbon::parse('1/31/2016'))->whereNotIn('cart_id', $exclude)->with('cartsBySale', 'cartsBySale.product')->get();
     $checkedin = \App\Sale::where('created_at', '>', \Carbon::parse('1/31/2016'))->WhereIn('cart_id', $exclude)->with('cartsBySale', 'cartsBySale.product')->get();
     return view('orders.index', compact('ticketsales', 'checkedin'));
 }
예제 #4
0
 /**
  * Display a listing of the resource.
  *
  * @return \Illuminate\Http\Response
  */
 public function index()
 {
     $first = date('Y-m-d', mktime(0, 0, 0, date('m'), 1, date('Y')));
     $last = date('Y-m-t', mktime(0, 0, 0, date('m'), 1, date('Y')));
     $inventory_value = Inventory::select(DB::Raw('SUM(products.cost_price * inventories.quantity) as total_value'))->join('products', 'products.id', '=', 'inventories.product_id')->get();
     $top_product = Sale::select('products.title', 'sales.product_id', DB::raw('count(sales.product_id) as sales_count'))->join('products', 'products.id', '=', 'sales.product_id')->whereBetween('sales.created_at', array($first, $last))->groupBy('sales.product_id')->orderBy('sales_count', 'desc')->take(10)->get();
     return view('dashboard/dashboard')->with('top_product', $top_product)->with('total_value', $inventory_value);
 }
 function newsale(Request $request)
 {
     $values = $request->all();
     $sale = Sale::create($values);
     $sales = Sale::all();
     $items = Item::all();
     $vendors = Vendor::all();
     return view('stockmaster.sales', ['vendors' => $vendors, 'newsale' => $sale, 'items' => $items, 'user' => Auth::user()]);
 }
예제 #6
0
 /**
  * Get the total income
  *
  */
 public function income()
 {
     $income = 0;
     $sales = Sale::get();
     foreach ($sales as $sale) {
         $income += $sale->total;
     }
     return $income;
 }
예제 #7
0
 /**
  * Show the application dashboard to the user.
  *
  * @return Response
  */
 public function index()
 {
     $items = Item::where('type', 1)->count();
     $item_kits = Item::where('type', 2)->count();
     $customers = Customer::count();
     $suppliers = Supplier::count();
     $receivings = Receiving::count();
     $sales = Sale::count();
     $employees = User::count();
     return view('home')->with('items', $items)->with('item_kits', $item_kits)->with('customers', $customers)->with('suppliers', $suppliers)->with('receivings', $receivings)->with('sales', $sales)->with('employees', $employees);
 }
 public function addSales()
 {
     $activeTab = 'sales';
     $task_types = TaskType::all();
     $saleTypes = SaleType::all();
     $user = Auth::user();
     $today_target = 140;
     $add_sales = $this->doubleValue(Input::get('sales'));
     if (empty($add_sales) || $add_sales <= 0) {
         $today_total = $this->getTodaysStats();
         $message = '<strong>Oh snap!</strong>. Please enter a value of 1 or above.  You entered \'' . Input::get('point') . '\'. Try submitting again.';
         $isErr = true;
         return view('myStat.add', compact('user', 'today_total', 'task_types', 'tasks', 'activeTab', 'isErr', 'message', 'today_target', 'saleTypes'));
     } else {
         $saleType = SaleType::findOrfail(Input::get('saleType_id'));
         $salesAudit = new SaleAudit();
         $salesAudit->sale = $add_sales;
         if (stripos(Input::get('sales'), '-') !== false) {
             $salesAudit->sale = -1 * $salesAudit->sale;
         }
         $salesAudit->user_id = Auth::user()->id;
         $salesAudit->company_id = Auth::user()->company_id;
         $salesAudit->saleType_id = $saleType->id;
         $salesAudit->date = new \DateTime();
         $salesAudit->save();
         $salesID = Input::get('saleType_id') . $user->id . date("mdY");
         $salesEntity = Sale::find($salesID);
         if ($salesEntity != null) {
             $salesEntity->sale = $salesEntity->sale + $salesAudit->sale;
             $salesEntity->update();
         } else {
             $salesEntity = new Sale();
             $salesEntity->id = $salesID;
             $salesEntity->month = date("m");
             $salesEntity->year = date("Y");
             $salesEntity->user_id = $user->id;
             $salesEntity->saleType_id = Input::get('saleType_id');
             $salesEntity->company_id = $user->company_id;
             $salesEntity->sale = $salesAudit->sale;
             $salesEntity->save();
         }
         $message = 'You have added <strong>' . number_format($salesAudit->sale, 2) . ' points</strong> to <strong>' . $saleType->name . '</strong>.';
         $today_total = $this->getTodaysStats();
         $isErr = false;
         return view('myStat.add', compact('user', 'today_total', 'task_types', 'tasks', 'activeTab', 'isErr', 'message', 'today_target', 'saleTypes'));
     }
 }
예제 #9
0
 public static function viewDetail($params, $currentUser, $con)
 {
     // check role's permission
     $permission = RolePermissionQuery::create()->select('read_sales')->findOneById($currentUser->role_id, $con);
     if (!$permission || $permission != 1) {
         throw new \Exception('Akses ditolak. Anda tidak mempunyai izin untuk melakukan operasi ini.');
     }
     $sales = Sale::seeker($params, $currentUser, $con);
     $logData['data'] = $sales['data'];
     $logData['detail'] = $sales['detail'];
     // log history
     $salesHistory = new SalesHistory();
     $salesHistory->setUserId($currentUser->id)->setSalesId($params->id)->setTime(time())->setOperation('viewDetail')->setData(json_encode($logData))->save($con);
     $results['success'] = true;
     $results['data'] = $sales['data'];
     $results['detail'] = $sales['detail'];
     return $results;
 }
예제 #10
0
             // Deposits for reservations.
         // Deposits for reservations.
         case 9:
             $sales += $transaction->Amount;
             $cash += $transaction->Amount;
             break;
         case 10:
             $creditSales += $transaction->Amount;
             $sales += $transaction->Amount;
             break;
     }
 }
 $sold = array();
 // Get only sales transactions.
 foreach (CashboxTransaction::where('CashboxId', '=', $cashbox->Id)->where('Type', '=', 1)->get() as $transaction) {
     foreach (Sale::where('TransactionId', '=', $transaction->Id)->get() as $sale) {
         // Go through sale breackdown.
         foreach (SaleBreakdown::where('SaleId', '=', $sale->Id)->get() as $salebreakdown) {
             // Extract Product or Service.
             // TODO: Get only stock from user's branch.
             $product = Stock::where('Code', '=', $salebreakdown->Code)->first();
             if ($product) {
                 // Check if we have already sold this product.
                 if (array_key_exists($product->Code, $sold)) {
                     $sold[$salebreakdown->Code]['Quantity'] += $salebreakdown->Quantity;
                 } else {
                     $sold[$salebreakdown->Code] = array('Description' => $product->Description, 'Quantity' => $salebreakdown->Quantity);
                 }
             } else {
                 $service = Service::where('Code', '=', $salebreakdown->Code)->first();
                 if ($service) {
예제 #11
0
 /**
  * Get cash
  */
 public function cash()
 {
     $startingCash = config('default.starting_cash');
     $stockCost = Stock::dateRangeTo($this->to)->sum('cost');
     $amountLoaned = abs(Payment::dateRangeTo($this->to)->where('amount', '<', 0)->sum('amount'));
     $amountPaid = Payment::dateRangeTo($this->to)->where('amount', '>', 0)->sum('amount');
     $cashSales = Sale::dateRangeTo($this->to)->where('user_id', null)->get();
     $totalCashSales = 0;
     foreach ($cashSales as $cashSale) {
         $totalCashSales += $cashSale->total;
     }
     $initialBalances = User::dateRangeTo($this->to)->sum('initial_balance');
     $paymentsToBank = Bank::dateRangeTo($this->to)->sum('amount');
     return $startingCash + $amountPaid + $totalCashSales + $initialBalances - $stockCost - $amountLoaned - $paymentsToBank;
 }
 /**
  * Function that uses a reservation. It creates a transaction for the remainder of the money and makes the sale.
  *
  * @return Response
  */
 public function useReservation()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('id' => 'required'));
     if ($validator->fails()) {
         return response()->json(['error' => 'No se recibieron los datos necesarios!']);
     }
     // Check that user is part of authorized staff.
     if (Auth::user()->Type != 1) {
         $response['state'] = 'No Autorizado';
         $response['error'] = 'Usuario no autorizado!';
         return response()->json($response);
     }
     // Get user branch.
     $worker = Worker::find(Auth::user()->TypeId);
     $userBranch = $worker->BranchId;
     $salePrice = 0;
     // Get the cashbox.
     $cashbox = Cashbox::where('UserId', '=', Auth::user()->Id)->where('Close', '=', NULL)->first();
     // Check that we actually have a cashbox open.
     if (!$cashbox) {
         $response['state'] = 'Error';
         $response['error'] = 'La caja no esta abierta o por lo tanto no se puede realizar la transaccion!';
         return response()->json($response);
     }
     // Get the reservation.
     $reservation = Reservation::find(Input::get('id'));
     // Make sure the reservation hasn't been used yet.
     if ($reservation->State == 'used' || $reservation->State == 'credit') {
         $response['state'] = 'Error';
         $response['error'] = 'Esta reservacion ya ha sido utilizada!';
         return response()->json($response);
     }
     // Now make sure the reservation hasn't been deleted.
     if ($reservation->State == 'delete') {
         $response['state'] = 'Error';
         $response['error'] = 'Esta reservacion fue eliminada!';
         return response()->json($response);
     }
     // Now make sure the reservation hasn't expired.
     if ($reservation->State == 'late') {
         $response['state'] = 'Error';
         $response['error'] = 'Esta reservacion ya ha expirado!';
         return response()->json($response);
     }
     // Get the reservation breakdown.
     $reservationBreakdown = ReservationBreakdown::where('ReservationId', '=', Input::get('id'))->get();
     // Loop through all items.
     foreach ($reservationBreakdown as $breakdown) {
         // Check if it is a product.
         $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $userBranch)->first();
         if (!$product) {
             // Check if it is a service.
             $service = Service::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $userBranch)->first();
             if (!$service) {
                 $response['state'] = 'Error';
                 $response['error'] = 'No se reconocio uno de los productos o servicios!';
                 return response()->json($response);
             }
             // Make sure there are enough materials in system and withdraw them.
             $materials = json_decode($service->Materials);
             foreach ($materials as $materialCode => $quantity) {
                 $stock = Stock::where('Code', '=', $materialCode)->where('BranchId', '=', $userBranch);
                 // If we have enough in stock withdraw it.
                 if ($stock->Quantity >= $quantity * $breakdown->Quantity) {
                     $stock->Quantity -= $quantity * $breakdown->Quantity;
                     $stock->save();
                 } else {
                     // Return all items and materials withdrawn so far.
                     $this->returnItems($reservationBreakdown, $breakdown->Code);
                     $response['state'] = 'Error';
                     $response['error'] = 'No hay suficientes materiales o productos!';
                     return response()->json($response);
                 }
             }
             // TODO: Check if any special functions need to be executed.
         } else {
             // Check quantity being taken is not greater than existing quantity in system.
             if ($product->Quantity >= $breakdown->Quantity) {
                 // Reduce products from stock.
                 $product->Quantity -= $breakdown->Quantity;
                 $product->save();
             } else {
                 // Return all items and materials withdrawn so far.
                 $this->returnItems($reservationBreakdown, $breakdown->Code);
                 $response['state'] = 'Error';
                 $response['info'] = $breakdown;
                 $response['product'] = $product;
                 $response['error'] = 'No hay suficientes materiales o productos!';
                 return response()->json($response);
             }
         }
     }
     // Make transaction for remaining reservation debt.
     $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 1, 'Amount' => $reservation->Value + $reservation->Tax - $reservation->Discount - $reservation->Deposit, 'Reason' => 'Venta con Reservacion.'));
     // Make sale.
     $sale;
     // TODO: Payment can also be with credit card.
     $sale = Sale::create(array('WorkerId' => $worker->Id, 'Value' => $reservation->Value - $reservation->Discount, 'Tax' => $reservation->Tax, 'Card' => false, 'TransactionId' => $transaction->Id, 'BranchId' => $userBranch, 'Credit' => 0, 'CreditorId' => $reservation->CreditorId, 'CreditorType' => $reservation->CreditorType, 'Cancelled' => 1));
     // Now add sales breakdown.
     foreach ($reservationBreakdown as $breakdown) {
         // Check if product.
         $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $userBranch)->first();
         if (!$product) {
             // Get service cost.
             $service = Service::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $userBranch)->first();
             $materials = json_decode($service->Materials);
             $cost = 0;
             foreach ($materials as $materialCode => $quantity) {
                 $material = Stock::where('Code', '=', $materialCode)->where('BranchId', '=', $userBranch)->first();
                 $cost += $material->AverageCost * $quantity;
             }
             SaleBreakdown::create(array('SaleId' => $sale->Id, 'Code' => $breakdown->Code, 'Quantity' => $breakdown->Quantity, 'Cost' => $cost * $breakdown->Quantity, 'Price' => $breakdown->Price));
         } else {
             SaleBreakdown::create(array('SaleId' => $sale->Id, 'Code' => $breakdown->Code, 'Quantity' => $breakdown->Quantity, 'Cost' => $product->AverageCost * $breakdown->Quantity, 'Price' => $breakdown->Price));
         }
     }
     // Now update the reservation.
     $reservation->State = 'used';
     $reservation->save();
     $response['state'] = 'Success';
     $response['saleId'] = $sale->Id;
     // Return response.
     return response()->json($response);
 }
예제 #13
0
 /**
  * Function that pays tab with a cash transaction.
  *
  * @return Response
  */
 public function payBill()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('items' => 'required', 'institution' => 'required', 'discount' => 'required', 'card' => 'required', 'credit' => 'required', 'authCode' => 'required'));
     $response = array();
     if ($validator->fails()) {
         $response['state'] = 'Error';
         $response['error'] = 'No se proporciono toda la informacion necesaria para realizar transaccion!';
         return response()->json($response);
     }
     // Check that user is part of authorized staff.
     if (Auth::user()->Type != 1) {
         // If they are unauthorized no point in returning anything.
         return response()->json(array());
     }
     // Get user branch.
     $worker = Worker::find(Auth::user()->TypeId);
     $userBranch = $worker->BranchId;
     $branch = Branch::find($userBranch);
     $salePrice = 0;
     // Get the cashbox.
     $cashbox = Cashbox::where('UserId', '=', Auth::user()->Id)->where('Close', '=', NULL)->first();
     // Check that we actually have a cashbox open.
     if (!$cashbox) {
         $response['state'] = 'Error';
         $response['error'] = 'La caja no esta abierta o por lo tanto no se puede realizar la transaccion!';
         return response()->json($response);
     }
     // Check discount is not greater than what user is allowed.
     $permissions = json_decode(UserLevel::find(Auth::user()->UserLevel)->Permissions);
     if (Input::get('discount') > $permissions->permissions->sales->discount->limit) {
         // Check if we have an auth code we can use.
         if (Input::get('authCode') == 0) {
             $response['state'] = 'Error';
             $response['error'] = 'No tiene permiso para otorgar este descuento!';
             return response()->json($response);
         }
         $request = Request::find(Input::get('authCode'));
         if ($request->Used == 1) {
             $response['state'] = 'Error';
             $response['error'] = 'No tiene permiso para otorgar este descuento!';
             return response()->json($response);
         }
         if ($request->Amount != Input::get('discount')) {
             $response['state'] = 'Error';
             $response['error'] = 'No tiene permiso para otorgar este descuento!';
             return response()->json($response);
         }
         $request->Used = 1;
         $request->save();
     }
     // Get client.
     $client = Client::where('Cedula', '=', Input::get('client'))->first();
     // Get institution if defined.
     $institution;
     if (Input::get('institution') != 0) {
         $institution = Institution::find(Input::get('institution'));
         if (!$institution) {
             $response['state'] = 'Error';
             $response['error'] = 'La institucion definida no fue encontrada en el sistema!';
             return response()->json($response);
         }
     }
     // Loop through all items.
     $items = json_decode(Input::get('items'));
     foreach ($items as $code => $info) {
         // Check if it is a product.
         $product = Stock::where('Code', '=', $code)->where('BranchId', '=', $userBranch)->first();
         if (!$product) {
             // Check if it is a service.
             $service = Service::where('Code', '=', $code)->where('BranchId', '=', $userBranch)->first();
             if (!$service) {
                 $response['state'] = 'Error';
                 $response['error'] = 'No se reconocio uno de los productos o servicios!';
                 return response()->json($response);
             }
             // Make sure there are enough materials in system and withdraw them.
             $materials = json_decode($service->Materials);
             foreach ($materials as $materialCode => $quantity) {
                 $stock = Stock::where('Code', '=', $materialCode)->where('BranchId', '=', $userBranch)->first();
                 // If we have enough in stock withdraw it.
                 if ($stock->Quantity >= $quantity * $info->quantity) {
                     $stock->Quantity -= $quantity * $info->quantity;
                     $stock->save();
                 } else {
                     // Return all items and materials withdrawn so far.
                     $this->returnItems($items, $code);
                     $response['state'] = 'Error';
                     $response['error'] = 'No hay suficientes materiales o productos!';
                     return response()->json($response);
                 }
             }
             // Add price to total of factura.
             $salePrice += $service->Price * $info->quantity;
             // TODO: Check if any special functions need to be executed.
         } else {
             // Check quantity being taken is not greater than existing quantity in system.
             if ($product->Quantity >= $info->quantity) {
                 // Reduce products from stock.
                 $product->Quantity -= $info->quantity;
                 $product->save();
             } else {
                 // Return all items and materials withdrawn so far.
                 $this->returnItems($items, $code);
                 $response['state'] = 'Error';
                 $response['error'] = 'No hay suficientes materiales o productos!';
                 return response()->json($response);
             }
             // Add price to total of factura.
             $salePrice += $product->Price * $info->quantity;
         }
     }
     $subTotal = $salePrice;
     $discount = $salePrice * (Input::get('discount') / 100);
     // Give discount.
     $salePrice = $salePrice * (1 - Input::get('discount') / 100);
     // Calculate tax if required.
     $tax = 0;
     if (json_decode($branch->DefaultExpenses)->regimen == 'cuotageneral') {
         if (Input::get('institution') != 0) {
             if (!$institution->Excempt) {
                 $tax = $salePrice * 0.15;
             }
         } else {
             if (!$client || !$client->Excempt) {
                 $tax = $salePrice * 0.15;
             }
         }
     }
     // Save client information.
     $clientInfo = array();
     if (Input::get('institution') != 0) {
         // Save institution information.
         $clientInfo = array('Name' => $institution->Name, 'Address' => $institution->Address, 'Id' => $institution->RUC);
     } else {
         // Save institution information.
         if ($client) {
             $clientInfo = array('Name' => $client->Name, 'Address' => $client->Address, 'Id' => $client->Cedula);
         }
     }
     // Check if credit that creditor has enough credit available,
     // otherwise check that enough cash is being paid.
     $change = 0;
     if (Input::get('credit') == 1) {
         if (Input::get('institution') != 0) {
             // Get institution debt.
             $debt = 0;
             $pendingBills = Sale::where('CreditorId', '=', $institution->Id)->where('CreditorType', '=', 2)->where('Cancelled', '=', false)->get();
             foreach ($pendingBills as $pendingBill) {
                 $debt += $pendingBill->Value + $pendingBill->Tax;
             }
             // Check they have enough credit available.
             if ($debt + $salePrice + $tax > $institution->CreditLimit) {
                 $this->returnItems($items, '');
                 $response['state'] = 'Error';
                 $response['error'] = 'Esta institucion no tiene suficiente credito disponible para cancelar esta factura!';
                 return response()->json($response);
             }
         } else {
             if (!$client) {
                 $response['state'] = 'Error';
                 $response['error'] = 'No se definio un cliente para asignar factura a credito!';
                 return response()->json($response);
             }
             // Get client debt.
             $debt = 0;
             $pendingBills = Sale::where('CreditorId', '=', $client->Id)->where('CreditorType', '=', 1)->where('Cancelled', '=', false);
             foreach ($pendingBills as $pendingBill) {
                 $debt += $pendingBill->Value + $pendingBill->Tax;
             }
             // Check they have enough credit available.
             if ($debt + $salePrice + $tax > $client->CreditLimit) {
                 $this->returnItems($items, '');
                 $response['state'] = 'Error';
                 $response['error'] = 'Este cliente no tiene suficiente credito disponible para cancelar esta factura!';
                 return response()->json($response);
             }
         }
     } else {
         // Check enough cash is being paid.
         $change = Input::get('cash') - ($salePrice + $tax);
         if ($change < 0) {
             $this->returnItems($items, '');
             $response['state'] = 'Error';
             $response['error'] = 'Debe pagar con un valor igual o mayor al costo de lo facturado!';
             return response()->json($response);
         }
     }
     // Make cashbox transaction.
     $transaction;
     if (Input::get('credit') == 1) {
         $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 10, 'Amount' => $salePrice + $tax, 'Reason' => 'Venta de Credito.'));
     } else {
         $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 1, 'Amount' => $salePrice + $tax, 'Reason' => 'Venta.'));
     }
     // Make sale.
     $card = 0;
     if (Input::get('card') != 0) {
         $config = Configuration::find(0);
         $card = $salePrice * ($config->POS / 100);
     }
     $sale;
     $type = 'contado';
     if (Input::get('credit') == 1) {
         $type = 'credito';
         if (Input::get('institution') != 0) {
             // Creditor Type 1 = Client, 2 = Institution.
             $sale = Sale::create(array('WorkerId' => $worker->Id, 'Value' => $salePrice, 'Tax' => $tax, 'Card' => $card, 'TransactionId' => $transaction->Id, 'BranchId' => $userBranch, 'Credit' => 1, 'CreditorId' => Input::get('institution'), 'CreditorType' => 2, 'Cancelled' => 0));
         } else {
             $sale = Sale::create(array('WorkerId' => $worker->Id, 'Value' => $salePrice, 'Tax' => $tax, 'Card' => $card, 'TransactionId' => $transaction->Id, 'BranchId' => $userBranch, 'Credit' => 1, 'CreditorId' => $client->Id, 'CreditorType' => 1, 'Cancelled' => 0));
         }
     } else {
         if (Input::get('institution') != 0) {
             // Creditor Type 1 = Client, 2 = Institution.
             $sale = Sale::create(array('WorkerId' => $worker->Id, 'Value' => $salePrice, 'Tax' => $tax, 'Card' => $card, 'TransactionId' => $transaction->Id, 'BranchId' => $userBranch, 'Credit' => 0, 'CreditorId' => Input::get('institution'), 'CreditorType' => 2, 'Cancelled' => 1));
         } else {
             if (!$client) {
                 $sale = Sale::create(array('WorkerId' => $worker->Id, 'Value' => $salePrice, 'Tax' => $tax, 'Card' => $card, 'TransactionId' => $transaction->Id, 'BranchId' => $userBranch, 'Credit' => 0, 'CreditorId' => 0, 'CreditorType' => 1, 'Cancelled' => 1));
             } else {
                 $sale = Sale::create(array('WorkerId' => $worker->Id, 'Value' => $salePrice, 'Tax' => $tax, 'Card' => $card, 'TransactionId' => $transaction->Id, 'BranchId' => $userBranch, 'Credit' => 0, 'CreditorId' => $client->Id, 'CreditorType' => 1, 'Cancelled' => 1));
             }
         }
     }
     // Now add sales breakdown.
     foreach ($items as $code => $info) {
         // Check if product.
         $product = Stock::where('Code', '=', $code)->where('BranchId', '=', $userBranch)->first();
         if (!$product) {
             // Get service cost.
             $service = Service::where('Code', '=', $code)->where('BranchId', '=', $userBranch)->first();
             $materials = json_decode($service->Materials);
             $cost = 0;
             foreach ($materials as $materialCode => $quantity) {
                 $material = Stock::where('Code', '=', $materialCode)->where('BranchId', '=', $userBranch)->first();
                 $cost += $material->AverageCost * $quantity;
             }
             SaleBreakdown::create(array('SaleId' => $sale->Id, 'Code' => $code, 'Quantity' => $info->quantity, 'Cost' => $cost, 'Price' => $service->Price));
         } else {
             SaleBreakdown::create(array('SaleId' => $sale->Id, 'Code' => $code, 'Quantity' => $info->quantity, 'Cost' => $product->AverageCost, 'Price' => $product->Price));
         }
     }
     // Return success message and bill information.
     $response['state'] = 'Success';
     $response['change'] = $change;
     $response['billInfo'] = array('SubTotal' => $subTotal, 'Discount' => $discount, 'Tax' => $tax, 'Total' => $salePrice + $tax, 'SaleId' => $sale->Id, 'Date' => date('d/m/Y'), 'Type' => $type);
     $response['clientInfo'] = $clientInfo;
     $response['total'] = $salePrice + $tax;
     return response()->json($response);
 }
예제 #14
0
                                    <th>Bank Name</th>
                                    <th>Cheque No</th>
                                    <th>Cheque Date</th>
                                    <th>Amount</th>
                                    <th>Received by</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                                </thead>
                                <tbody>
                                <?php 
$slNo = 1;
?>
                                @foreach($register as $reg)
                                    <?php 
$sale = \App\Sale::where('invoice_id', '=', $reg->invoice_id)->first();
$partyname = \App\Party::find($sale->party_id);
$time = strtotime($reg->cheque_date);
$newformat = date('d', $time);
$today = date('d', time());
?>
                                    <tr>
                                        <td <?php 
if ($newformat >= $today - 2 && $newformat <= $today + 2) {
    echo "class='blink'";
}
?>
>{{$slNo}}</td>
                                        <td <?php 
if ($newformat >= $today - 2 && $newformat <= $today + 2) {
    echo "class='blink'";
예제 #15
0
            <div class="control-group span4">
              <label class="control-label" for="expenseMonth">Mes:</label>
              <div class="controls">
                <select id="expenseMonth">
                  @for($i = 1; $i<13; $i++)
                    <option value="{{ $i }}">{{ $i }}</option>
                  @endfor
                </select>
              </div>
            </div>
            <div class="control-group span5">
              <label class="control-label" for="expenseYear">Año:</label>
              <div class="controls">
                <select id="expenseYear">
                <?php 
$first = Sale::first();
$startDate = date('Y-m-d');
if ($first) {
    $startDate = $first->Created;
}
?>
                  @for($i = date('Y', strtotime($startDate)); $i < date('Y', strtotime("+3 Years")); $i++)
                    <option value="{{ $i }}">{{ $i }}</option>
                  @endfor
                </select>
              </div>
            </div>
            <div class="control-group span2">
              <button type="button" class="btn btn-success" id="expenseSearch">
                <i class="icon-search"></i> Buscar
              </button>
예제 #16
0
 /**
  * Remove the specified resource from storage.
  *
  * @param  int  $id
  * @return \Illuminate\Http\Response
  */
 public function destroy($id)
 {
     Sale::destroy($id);
     return $this->index();
 }
<?php

use App\Sale;
use App\Client;
use App\Institution;
use App\CashReceipt;
use App\Transport;
use App\Branch;
// Get the sale.
$creditDue = Sale::find($sale['Id']);
// Get the branch.
$branch = Branch::find($creditDue->BranchId);
// Get the creditor.
$creditor = null;
if ($sale->CreditorType == 1) {
    $creditor = Client::find($sale->CreditorId);
} else {
    $creditor = Institution::find($sale->CreditorId);
}
// Get the transport request.
$paymentCollection = Transport::find($transport['Id']);
$payments = CashReceipt::where('Type', '=', 2)->where('TypeId', '=', $sale->Id)->get();
$totalDue = $creditDue->Value + $creditDue->Tax;
foreach ($payments as $payment) {
    $totalDue -= $payment->Value;
}
?>
<p>{{ $creditor->Name }},</p>
<p>Les enviamos el siguiente correo para dejarles saber que el {{ $transport->Date }} estaremos llegando a recoger el pago de la factura numero {{ $sale->Id }}. El total pendiente es de C$ {{ $totalDue }}.</p>
<p>Si por algun motivo no podra pagar ese dia puede reprogramar nuestra visita respondiendo a este correo de la siguiente manera:</p>
<p>Reprogramar:{{ date('Y-m-d', strtotime("+5 days")) }}</p>
예제 #18
0
 /**
  * Display a listing of the resource.
  *
  * @return \Illuminate\Http\Response
  */
 public function index(Request $request)
 {
     //$sales = Sale::with ( 'user', 'country' )->orderBy ( 'id', 'desc' )->get ();
     $sales = Sale::with('user', 'country', 'values')->orderBy('id', 'desc');
     $flag = 0;
     $arr_Request = [];
     if ($request['user_id'] != null) {
         $arr_Request['user_id'] = $request['user_id'];
         $flag = 1;
         $sales = $sales->where('user_id', $arr_Request['user_id']);
     } else {
         $arr_Request['user_id'] = null;
     }
     if ($request['customer_name'] != null) {
         $arr_Request['customer_name'] = $request['customer_name'];
         $sales = $sales->where('customer_name', $arr_Request['customer_name']);
         $flag = 1;
     } else {
         $arr_Request['customer_name'] = null;
     }
     if ($request['country_id'] != null) {
         $arr_Request['country_id'] = $request['country_id'];
         $sales = $sales->where('country_id', $arr_Request['country_id']);
         $flag = 1;
     } else {
         $arr_Request['country_id'] = null;
     }
     if ($request['region'] != null) {
         $arr_Request['region'] = $request['region'];
         $sales = $sales->where('region', $arr_Request['region']);
         $flag = 1;
     } else {
         $arr_Request['region'] = null;
     }
     if ($request['vertical'] != null) {
         $arr_Request['vertical'] = $request['vertical'];
         $sales = $sales->where('vertical', $arr_Request['vertical']);
         $flag = 1;
     } else {
         $arr_Request['vertical'] = null;
     }
     if ($request['delivery_location'] != null) {
         $arr_Request['delivery_location'] = $request['delivery_location'];
         $sales = $sales->where('delivery_location', $arr_Request['delivery_location']);
         $flag = 1;
     } else {
         $arr_Request['delivery_location'] = null;
     }
     if ($request['engagement'] != null) {
         $arr_Request['engagement'] = $request['engagement'];
         $sales = $sales->where('engagement', $arr_Request['engagement']);
         $flag = 1;
     } else {
         $arr_Request['engagement'] = null;
     }
     if ($request['service'] != null) {
         $arr_Request['service'] = $request['service'];
         $sales = $sales->where('service', $arr_Request['service']);
         $flag = 1;
     } else {
         $arr_Request['service'] = null;
     }
     $currentYear = date("Y");
     if ($request['year'] != null) {
         $arr_Request['year'] = $request['year'];
         $currentYear = $arr_Request['year'];
         $flag = 1;
     } else {
         $arr_Request['year'] = null;
     }
     if ($request['q'] != null) {
         $arr_Request['q'] = $request['q'];
     } else {
         $arr_Request['q'] = null;
     }
     $arr_Request['flag'] = $flag;
     $years = Sale::getYear();
     $sales = $sales->get();
     $totals = [];
     $hc1 = $hc2 = $hc3 = $hc4 = $hc5 = $hc6 = $hc7 = $hc8 = $hc9 = $hc10 = $hc11 = $hc12 = 0;
     $v1 = $v2 = $v3 = $v4 = $v5 = $v6 = $v7 = $v8 = $v9 = $v10 = $v11 = $v12 = 0;
     $total_hc = 0;
     $total_value = 0;
     foreach ($sales as $key => $sale) {
         $total_hc += $sale->head_count;
         $total_value += $sale->value;
         $value = [];
         if ($request['q'] != null && $request['q'] == 'full') {
             $value = Sale::makeFullValue($sale, $currentYear);
         } elseif ($request['q'] != null && $request['q'] == 'weighted') {
             $value = Sale::makeWeightedValue($sale, $currentYear);
         } else {
             $value = Sale::makeFullValue($sale, $currentYear);
         }
         $total_val_hc = $total_val_value = 0;
         foreach ($value as $val) {
             $total_val_hc += $val['hc'];
             $total_val_value += $val['value'];
         }
         if ($total_val_hc == 0 && $total_val_value == 0) {
             unset($sales[$key]);
             $sale->success = false;
         }
         $sale->months = $value;
         $hc1 += $sale->months[0]['hc'];
         $hc2 += $sale->months[1]['hc'];
         $hc3 += $sale->months[2]['hc'];
         $hc4 += $sale->months[3]['hc'];
         $hc5 += $sale->months[4]['hc'];
         $hc6 += $sale->months[5]['hc'];
         $hc7 += $sale->months[6]['hc'];
         $hc8 += $sale->months[7]['hc'];
         $hc9 += $sale->months[8]['hc'];
         $hc10 += $sale->months[9]['hc'];
         $hc11 += $sale->months[10]['hc'];
         $hc12 += $sale->months[11]['hc'];
         $v1 += $sale->months[0]['value'];
         $v2 += $sale->months[1]['value'];
         $v3 += $sale->months[2]['value'];
         $v4 += $sale->months[3]['value'];
         $v5 += $sale->months[4]['value'];
         $v6 += $sale->months[5]['value'];
         $v7 += $sale->months[6]['value'];
         $v8 += $sale->months[7]['value'];
         $v9 += $sale->months[8]['value'];
         $v10 += $sale->months[9]['value'];
         $v11 += $sale->months[10]['value'];
         $v12 += $sale->months[11]['value'];
     }
     array_push($totals, array('hc' => $hc1, 'value' => $v1));
     array_push($totals, array('hc' => $hc2, 'value' => $v2));
     array_push($totals, array('hc' => $hc3, 'value' => $v3));
     array_push($totals, array('hc' => $hc4, 'value' => $v4));
     array_push($totals, array('hc' => $hc5, 'value' => $v5));
     array_push($totals, array('hc' => $hc6, 'value' => $v6));
     array_push($totals, array('hc' => $hc7, 'value' => $v7));
     array_push($totals, array('hc' => $hc8, 'value' => $v8));
     array_push($totals, array('hc' => $hc9, 'value' => $v9));
     array_push($totals, array('hc' => $hc10, 'value' => $v10));
     array_push($totals, array('hc' => $hc11, 'value' => $v11));
     array_push($totals, array('hc' => $hc12, 'value' => $v12));
     $users = User::all();
     $countries = Country::all();
     $customerNames = Sale::getCustomerName();
     return view('fulls.index')->with('sales', $sales)->with('totals', $totals)->with('years', $years)->with('users', $users)->with('countries', $countries)->with('arr_Request', $arr_Request)->with('customerNames', $customerNames)->with('total_hc', $total_hc)->with('total_value', $total_value);
 }
예제 #19
0
 /**
  * Function that searches for past trips.
  *
  * @return Response
  */
 public function searchVehicleTrips()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('vehicle' => 'required', 'start' => 'required', 'end' => 'required'));
     if ($validator->fails()) {
         return response()->json(['error' => 'Informacion incompleta!']);
     }
     // Check that user is part of authorized staff.
     if (Auth::user()->Type != 1) {
         // If they are unauthorized no point in returning anything.
         return response()->json(array());
     }
     // Get trips.
     $start = date('Y-m-d', strtotime(Input::get('start')));
     $end = date('Y-m-d', strtotime(Input::get('end')));
     $trips = Transport::where('VehicleId', '=', Input::get('vehicle'))->where('Date', '>=', $start)->where('Date', '<=', $end)->where('State', '=', 1)->groupBy('Date')->orderBy('Order')->get();
     $tripData = array();
     foreach ($trips as $trip) {
         $driver = Worker::find($trip->DriverId);
         $reason = '';
         switch ($trip->Type) {
             case 1:
                 // Get sale breakdown.
                 $breakdown = SaleBreakdown::find($trip->ReasonId);
                 // Get product or service.
                 $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $driver->BranchId)->first();
                 if ($product) {
                     $reason = 'Venta de ' . $product->Description;
                 } else {
                     $service = Service::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $driver->BranchId)->first();
                     $reason = 'Venta de ' . $service->Description;
                 }
                 break;
             case 2:
                 // Get sale.
                 $sale = Sale::find($trip->ReasonId);
                 // Get client or institution.
                 if ($sale->CreditorType == 1) {
                     if ($sale->CreditorId == 0) {
                         $reason = 'Venta a cliente no definido';
                     } else {
                         $client = Client::find($sale->CreditorId);
                         $reason = 'Venta a ' . $client->Name;
                     }
                 } else {
                     $institution = Institution::find($sale->CreditorId);
                     $reason = 'Venta a ' . $institution->Name;
                 }
                 break;
             case 3:
                 // Get order breakdown.
                 $breakdown = OrderBreakdown::find('OrderId', '=', $trip->ReasonId);
                 // Get product or service.
                 $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $driver->BranchId)->first();
                 $reason = 'Produccion de ' . $product->Description;
                 break;
             case 4:
                 // Get order.
                 $order = Order::find($trip->ReasonId);
                 // Get client or institution.
                 $client = Client::find($order->ClientId);
                 if ($client->InstitutionId == 0) {
                     $reason = 'Orden de Produccion de ' . $client->Name;
                 } else {
                     $institution = Institution::find($client->InstitutionId);
                     $reason = 'Orden de Produccion de ' . $institution->Name;
                 }
                 break;
             case 5:
                 // Get storage request.
                 $request = StorageRequest::find($trip->ReasonId);
                 $reason = $request->Reason;
                 break;
             case 6:
                 // Get visit.
                 $visit = Visit::find($trip->ReasonId);
                 $reason = 'Visita ' . $visit->Result;
                 break;
             case 7:
                 // Get credit bill.
                 $creditBill = Sale::find($trip->ReasonId);
                 $reason = 'Cobro de Facturo: ' . $creditBill->Id;
                 break;
             case 8:
                 // Contract Payment.
                 $contract = Contract::find($trip->ReasonId);
                 $reason = 'Cobro de Contrato: ' . $contract->Code;
                 break;
             case 9:
                 // Provider purchase.
                 $aiOrder = AIOrder::find($trip->ReasonId);
                 $reason = 'Compra automatica ' . $aiOrder->Id;
                 break;
             case 10:
                 $reason = 'Generado por usuario.';
                 break;
         }
         array_push($tripData, array('Id' => $trip->Id, 'Date' => $trip->Date, 'Driver' => $driver->Name, 'Reason' => $reason, 'Distance' => $trip->Distance, 'Journey' => json_decode($trip->Journey, true), 'StartLat' => $trip->StartLatitude, 'StartLon' => $trip->StartLongitude, 'EndLat' => $trip->EndLatitude, 'EndLon' => $trip->EndLongitude));
     }
     $response['state'] = 'Success';
     $response['trips'] = $tripData;
     return response()->json($response);
 }
예제 #20
0
 public function decrease(Request $request)
 {
     $view = $this->modifyQuantity($request, -1);
     if ($view == false) {
         return;
     }
     $sale = new Sale();
     $sale->product_id = $request->product_id;
     $sale->quantity = 1;
     $sale->unit_price = Product::find($request->product_id)->sale_price;
     $sale->save();
     return $view;
 }
예제 #21
0
                                    DV-{{$transaction->id}}
                                @endif
                            </td></tr>
                        <tr><td>Recieved by: {{$transaction->user->name}}</td></tr>
                    </table>
                </td>
            </tr>
        </table>


        <table class="col-md-12"  style="width: 100%;" >
            <tr style="border:1px solid black; background: url('../../assets/img/lightBlueBackground.jpg');">
                <td colspan="2">Received from:
                    @if($transaction->type == "Receive")
                        <?php 
$sales = \App\Sale::where('invoice_id', '=', $transaction->invoice_id)->first();
?>
                        {{$sales->party->name}}
                    @elseif($transaction->type == "Payment")
                        <?php 
$sales = \App\PurchaseInvoice::where('invoice_id', '=', $transaction->invoice_id)->first();
?>
                        {{$sales->party->name}}
                    @endif
                </td>
                <td style="border:1px solid black;" class="text-center">
                    Amount
                </td>
            </tr>
            <tr style="border:1px solid black;">
                <td colspan="2">
예제 #22
0
function transactionType($transaction)
{
    switch ($transaction->Type) {
        case 1:
            // Check if a credit card was used for sale.
            if (Sale::where('TransactionId', '=', $transaction->Id)->first()->Card) {
                return 'Venta con Tarjeta';
            } else {
                return $transaction->Reason;
            }
            break;
        case 2:
            return $transaction->Reason;
            break;
        case 3:
            return $transaction->Reason;
            break;
        case 4:
            return 'Otros Gastos';
            break;
        case 5:
            return 'Retiro de Caja';
            break;
        case 6:
            return 'Reembolso de Caja';
            break;
        case 7:
            return 'Pago de Contrato';
            break;
        case 8:
            return 'Pago de Credito';
            break;
        case 9:
            return $transaction->Reason;
            break;
        case 10:
            return $transaction->Reason;
            break;
    }
}
예제 #23
0
 /**
  * Function that scans a sale and adds a bonus to selected worker if necessary.
  *
  * @return Response
  */
 public function scanSale()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('staffId' => 'required', 'saleId' => 'required'));
     if ($validator->fails()) {
         $response['state'] = 'Error';
         $response['error'] = 'Debe cargar al trabajador!';
         return response()->json($response);
     }
     // Check that user is part of authorized staff.
     if (Auth::user()->Type != 1) {
         // If they are unauthorized no point in returning anything.
         return response()->json(array());
     }
     // Get the worker of given Id.
     $response = array();
     $worker = Worker::where('Cedula', '=', Input::get('staffId'))->first();
     if ($worker) {
         // Check if this worker should get a bonus from this.
         if ($worker->BonusSource != 'productionexclusive' && $worker->BonusSource != 'productionsinglecustom') {
             $response['state'] = 'Error';
             $response['error'] = 'Este trabajador no puede ser asignado bonos por facturas.';
             return response()->json($response);
         }
         // Get today's day.
         $todaySalary = WorkerSalary::where('WorkerId', '=', $worker->Id)->where('Date', '=', date('Y-m-d'))->first();
         if (!$todaySalary) {
             $response['state'] = 'Error';
             $response['error'] = 'El trabajador no ha sido agregado en la planilla del dia de hoy!';
             return response()->json($response);
         }
         // Get the sale.
         $sale = Sale::find(Input::get('saleId'));
         if (!$sale) {
             $response['state'] = 'Error';
             $response['error'] = 'Venta Inexistente!';
             return response()->json($response);
         }
         // Get the breakdown.
         $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
         foreach ($breakdown as $b) {
             // Check that this sale breakdown has not been used already.
             $extraData = json_decode($b->ExtraData, true);
             if (is_array($extraData) && array_key_exists('workerId', $extraData)) {
                 // Get the worker.
                 $worker = Worker::find($extraData['workerId']);
                 $response['state'] = 'Error';
                 $response['error'] = 'Esta factura ha sido asignada a ' . $worker->Name . '!';
                 return response()->json($response);
             }
             $product = Stock::where('Code', '=', $b->Code)->where('BranchId', '=', $sale->BranchId)->first();
             if ($product) {
                 $todaySalary->Bonus += $product->Bonus;
                 $todaySalary->save();
             } else {
                 $service = Service::where('Code', '=', $b->Code)->where('BranchId', '=', $sale->BranchId)->first();
                 $todaySalary->Bonus += $service->Bonus;
                 $todaySalary->save();
             }
             // Add extra data to breakdown.
             $extraData['workerId'] = $worker->Id;
             $b->ExtraData = json_encode($extraData);
             $b->save();
         }
         // Return response.
         $response['state'] = 'Success';
         $response['message'] = 'Factura agregada exitosamente!';
         return response()->json($response);
     } else {
         $response['state'] = 'Error';
         $response['error'] = 'Trabajador Inexistente!';
         return response()->json($response);
     }
 }
예제 #24
0
 /**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index()
 {
     $salesReport = Sale::all();
     return view('report.sale')->with('saleReport', $salesReport);
 }
예제 #25
0
 /**
  * Remove the specified resource from storage.
  *
  * @param int $id        	
  * @return \Illuminate\Http\Response
  */
 public function destroy($id)
 {
     $sale = Sale::findOrFail($id);
     $sale->delete();
     // redirect
     // Session::flash('message', 'Successfully deleted the sale!');
     return Redirect::to('sale');
 }
예제 #26
0
 public function getDelete($id)
 {
     $salesreturn = SalesReturnDetail::find($id);
     $saleReturnInvoice = SalesReturnInvoice::where('invoice_id', '=', $salesreturn->invoice_id)->first();
     $remaining_amount = $salesreturn->return_amount;
     $partyId = $saleReturnInvoice->party_id;
     if ($remaining_amount > 0) {
         $invoiceId = Sale::where('party_id', '=', $partyId)->where('is_sale', '=', 1)->get();
         foreach ($invoiceId as $invid) {
             $amount = Transaction::where('invoice_id', '=', $invid->invoice_id)->where('type', '=', 'Receive')->where('account_category_id', '=', 7)->get();
             foreach ($amount as $amnt) {
                 if ($amnt->amount > $remaining_amount) {
                     $transaction = Transaction::find($amnt->id);
                     $transaction->amount = $transaction->amount - $remaining_amount;
                     $transaction->save();
                     $sale = Sale::find($invid->id);
                     $sale->status = 'Partial';
                     $sale->save();
                     $remaining_amount = 0;
                 } elseif ($amnt->amount < $remaining_amount) {
                     $transaction = Transaction::find($amnt->id);
                     $transacamount = $transaction->amount;
                     $transaction->delete();
                     $sale = Sale::find($invid->id);
                     $sale->status = 'Partial';
                     $sale->save();
                     $remaining_amount = $remaining_amount - $transacamount;
                 } elseif ($amnt->amount == $remaining_amount) {
                     $transaction = Transaction::find($amnt->id);
                     $transaction->delete();
                     $sale = Sale::find($invid->id);
                     $sale->status = 'Partial';
                     $sale->save();
                     $remaining_amount = 0;
                 }
             }
         }
     }
     $salesreturn->delete();
     $saleReturnDetail = SalesReturnDetail::where('invoice_id', '=', $saleReturnInvoice->invoice_id)->get();
     if (empty($saleReturnDetail[0])) {
         echo 'deleted';
         $saleReturnInvoice->delete();
     }
 }
예제 #27
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     // Get all workers that haven't been fired.
     $workers = Worker::where('Fired', '=', false)->get();
     foreach ($workers as $worker) {
         // First let's check if it has a long term loan active.
         $currentMonth = date('Y-m');
         if ($worker->Loan > 0) {
             // Let's check if we have gotten this months loan payment.
             $loans = WorkerLoan::where('WorkerId', '=', $worker->Id)->where('Date', '>', $currentMonth . '-01')->where('Type', '=', 2)->get();
             if (count($loans) == 0) {
                 // Charge worker for loan.
                 $charge = $worker->Loan / $worker->Months;
                 $loan = WorkerLoan::create(array('Date' => date('Y-m-d'), 'Amount' => $charge, 'Processed' => false, 'State' => 2, 'Type' => 2, 'WorkerId' => $worker->Id));
                 $worker->Loan -= $charge;
                 $worker->Months--;
                 $worker->save();
             }
         }
         // Now let's check if we have gotten this month's insurance fee.
         $loans = WorkerLoan::where('WorkerId', '=', $worker->Id)->where('Date', '>', $currentMonth . '-01')->where('Type', '=', 3)->get();
         if (count($loans) == 0) {
             // Charge worker for loan.
             $charge = $worker->Insurance - $worker->Patron;
             if ($charge > 0) {
                 $loan = WorkerLoan::create(array('Date' => date('Y-m-d'), 'Amount' => $charge, 'Processed' => false, 'State' => 2, 'Type' => 3, 'WorkerId' => $worker->Id));
             }
         }
         // Get workers days.
         $days = WorkerSalary::where('SystemProcess', '=', false)->where('WorkerId', '=', $worker->Id)->get();
         // Now let's check if we need to add a bonus to the worker.
         if ($worker->BonusPercentage > 0) {
             switch ($worker->BonusSource) {
                 case 'production':
                     foreach ($days as $day) {
                         if ($day->DayType != 3 && ($day->DayType < 5 || $day->DayType == 7)) {
                             // If worker is on general production then let's get what was produced and the price of what was produced.
                             $produced = ProductionStage::where('Date', '>', $day->Date . ' 00:00:01')->get();
                             $totalProduced = 0;
                             $pIds = array();
                             foreach ($produced as $p) {
                                 // Check if we have already checked this product.
                                 if (!in_array($p->ProductionId, $pIds)) {
                                     array_push($pIds, $p->ProductionId);
                                     // Check if product is finished.
                                     $product = Production::find($p->ProductionId);
                                     if ($product->Stage == $product->maxStage()) {
                                         $finalProduct = Stock::where('Code', '=', $product->Code)->where('BranchId', '=', $product->BranchId)->first();
                                         $totalProduced += $finalProduct->Price;
                                     }
                                 }
                             }
                             $day->Bonus += $totalProduced * ($worker->BonusPercentage / 100);
                         }
                         // Add insurance Patron Value for the day.
                         // TODO: I should check how many days are in this month,
                         $day->Insurance = $worker->Patron / 30;
                         $day->save();
                     }
                     break;
                 case 'productionsingle':
                     foreach ($days as $day) {
                         if ($day->DayType != 3 && ($day->DayType < 5 || $day->DayType == 7)) {
                             // If worker is on single production then let's get what he produced and the price of what was produced.
                             $produced = ProductionStage::where('Date', '>', $day->Date . ' 00:00:01')->where('WorkerId', '=', $worker->Id)->get();
                             $totalProduced = 0;
                             $pIds = array();
                             foreach ($produced as $p) {
                                 // Check if we have already checked this product.
                                 if (!in_array($p->ProductionId, $pIds)) {
                                     array_push($pIds, $p->ProductionId);
                                     // Check if product is finished.
                                     $product = Production::find($p->ProductionId);
                                     if ($product->Stage == $product->maxStage()) {
                                         $finalProduct = Stock::where('Code', '=', $product->Code)->where('BranchId', '=', $product->BranchId)->first();
                                         $totalProduced += $finalProduct->Price;
                                     }
                                 }
                             }
                             $day->Bonus += $totalProduced * ($worker->BonusPercentage / 100);
                         }
                         // Add insurance Patron Value for the day.
                         // TODO: I should check how many days are in this month,
                         $day->Insurance = $worker->Patron / 30;
                         $day->save();
                     }
                     break;
                 case 'sales':
                     foreach ($days as $day) {
                         if ($day->DayType != 3 && ($day->DayType < 5 || $day->DayType == 7)) {
                             // If worker is on general sales then let's get all sales.
                             $sales = Sale::where('Created', '>=', $day->Date . ' 00:00:01')->where('Created', '<=', $day->Date . ' 23:59:59')->where('BranchId', '=', $worker->BranchId)->get();
                             $totalSales = 0;
                             foreach ($sales as $sale) {
                                 $totalSales += $sale->Value;
                             }
                             $day->Bonus += $totalSales * ($worker->BonusPercentage / 100);
                         }
                         // Add insurance Patron Value for the day.
                         // TODO: I should check how many days are in this month,
                         $day->Insurance = $worker->Patron / 30;
                         $day->save();
                     }
                     break;
                 case 'salessingle':
                     foreach ($days as $day) {
                         if ($day->DayType != 3 && ($day->DayType < 5 || $day->DayType == 7)) {
                             // If worker is on general sales then let's get all sales.
                             $sales = Sale::where('Created', '>=', $day->Date . ' 00:00:01')->where('Created', '<=', $day->Date . ' 23:59:59')->where('WorkerId', '=', $worker->Id)->get();
                             $totalSales = 0;
                             foreach ($sales as $sale) {
                                 $totalSales += $sale->Value;
                             }
                             $day->Bonus += $totalSales * ($worker->BonusPercentage / 100);
                         }
                         // Add insurance Patron Value for the day.
                         // TODO: I should check how many days are in this month,
                         $day->Insurance = $worker->Patron / 30;
                         $day->save();
                     }
                     break;
             }
         }
     }
     // Get all days that have not been processed and set them as being processed.
     $allDays = WorkerSalary::where('SystemProcess', '=', false)->get();
     foreach ($allDays as $day) {
         $day->SystemProcess = true;
         $day->save();
     }
 }
예제 #28
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     // Let's get all credit sales that have not been paid yet.
     $creditSales = Sale::where('Credit', '=', true)->where('Cancelled', '=', false)->get();
     // Check if any of them are due soon.
     $today = date('Y-m-d H:i:s');
     foreach ($creditSales as $sale) {
         // Get the client or institution that made the credit purchase.
         $creditor = null;
         if ($sale->CreditorType == 1) {
             $creditor = Client::find($sale->CreditorId);
         } else {
             $creditor = Institution::find($sale->CreditorId);
         }
         // First check if the payment is late.
         if (date('Y-m-d H:i:s', strtotime($sale->Created) + $creditor->CreditDays * 86400) < $today) {
             // If it's past due for more than a month notify admins so they can deal with it.
             if (date('Y-m-d H:i:s', strtotime($sale->Created) + ($creditor->CreditDays + 30) * 86400) < $today) {
                 // In this case we don't have a vehicle and the provider doesn't provide delivery so we must notify an administrator.
                 $users = User::where('UserLevel', '=', 1)->get();
                 foreach ($users as $admin) {
                     Notification::create(array('UserId' => $admin->Id, 'Created' => date('Y-m-d H:i:s'), 'Reason' => 'Aergia ha tratado de cobrar la venta de credito con factura: ' . $sale->Id . ', sin embargo no se ha registrado el pago de la factura y esta tiene mas de un mes de vencimiento. Aergia no seguira tratando de cobrar esta factura, por favor darle seguimiento al caso.', 'Url' => '/creditdue/' . $sale->Id, 'Seen' => false));
                 }
             } else {
                 // Check to see if there is a transport request active to collect payment.
                 $transport = Transport::where('Type', '=', 7)->where('ReasonId', '=', $sale->Id)->where('Date', '>', date('Y-m-d'))->get();
                 if (count($transport) == 0) {
                     // Get a vehicle that can be used to go to charge creditor.
                     $vehicles = Vehicle::where('BranchId', '=', $sale->BranchId)->where('Repair', '=', false)->get();
                     $vehicle = null;
                     foreach ($vehicles as $v) {
                         if (!$vehicle) {
                             $vehicle = $v;
                         }
                         // In this case the smaller the vehicle the more suitable it should be.
                         // TODO: This could be improved.
                         if ($v->Type < $vehicle->Type) {
                             $vehicle = $v;
                         }
                     }
                     if (!$vehicle) {
                         // In this case we don't have a vehicle to go charge creditor so we must notify an administrator.
                         $users = User::where('UserLevel', '=', 1)->get();
                         foreach ($users as $admin) {
                             Notification::create(array('UserId' => $admin->Id, 'Created' => date('Y-m-d H:i:s'), 'Reason' => 'Aergia no fue capaz de organizar el cobro de la factura: ' . $sale->Id . ' ya que no tuvo vehiculos disponibles para hacerlo. Por favor organizar el cobro de la factura.', 'Url' => '/creditdue/' . $sale->Id, 'Seen' => false));
                         }
                     } else {
                         // Get location of creditor.
                         $location = Location::find($creditor->LocationId);
                         $paymentCollection = Transport::create(array('Date' => date('Y-m-d', strtotime("+1 day")), 'Time' => '00:00:00', 'VehicleId' => $vehicle->Id, 'DriverId' => 0, 'StartLatitude' => 0, 'StartLongitude' => 0, 'Journey' => '[]', 'EndLatitude' => $location->Latitude, 'EndLongitude' => $location->Longitude, 'EndAddress' => $creditor->Address, 'Distance' => 0, 'ReasonId' => $sale->Id, 'Type' => 7, 'State' => 2, 'Order' => 0, 'Depreciation' => 0));
                         // Inform creditor of when you shall collect payment.
                         if ($creditor->Email != '') {
                             Mail::send('emails.ai.creditorReminder', ['sale' => $sale, 'creditor' => $creditor, 'transport' => $paymentCollection], function ($message) use($sale, $creditor) {
                                 $message->to($creditor->Email);
                                 $message->subject('Cobro Factura: ' . $sale->Id);
                             });
                         }
                     }
                 }
             }
         }
     }
 }
예제 #29
0
 private function generateInvoiceId()
 {
     $invdesc = Sale::orderBy('id', 'DESC')->first();
     if ($invdesc != null) {
         $invDescId = $invdesc->invoice_id;
         $invDescIdNo = substr($invDescId, 6);
         $subinv1 = substr($invDescId, 6);
         $dd = substr($invDescId, 0, 2);
         $mm = substr($invDescId, -8, -6);
         $yy = substr($invDescId, -6, -4);
         $tz = 'Asia/Dhaka';
         $timestamp = time();
         $dt = new \DateTime("now", new \DateTimeZone($tz));
         //first argument "must" be a string
         $dt->setTimestamp($timestamp);
         //adjust the object to correct timestamp
         $Today = $dt->format('d.m.Y');
         $explodToday = explode(".", $Today);
         $dd2 = $explodToday[1];
         $mm2 = $explodToday[0];
         $yy1 = $explodToday[2];
         $yy2 = substr($invDescId, 2);
         if ($dd == $dd2 && $yy == $yy2 && $mm == $mm2) {
             $invoiceidd = $dd2 . $mm2 . $yy2 . $invDescIdNo + 1;
         } else {
             $invoiceidd = $dd2 . $mm2 . $yy2 . "0001";
         }
     } else {
         $tz = 'Asia/Dhaka';
         $timestamp = time();
         $dt = new \DateTime("now", new \DateTimeZone($tz));
         //first argument "must" be a string
         $dt->setTimestamp($timestamp);
         //adjust the object to correct timestamp
         $Today = $dt->format('d.m.Y');
         $explodToday = explode(".", $Today);
         $dd2 = $explodToday[1];
         $mm2 = $explodToday[0];
         $yy1 = $explodToday[2];
         $yy2 = substr($yy1, 2);
         $invoiceidd = $dd2 . $mm2 . $yy2 . "0001";
     }
 }
예제 #30
0
 /**
  * Function that generates order.
  *
  * @return Response
  */
 public function aiOrder()
 {
     // Get all branches.
     $branches = Branch::all();
     // Get all providers.
     $providers = Provider::where('AIManaged', '=', true)->get();
     // Prepare order array.
     $order = array();
     // Loop through providers.
     foreach ($providers as $provider) {
         $order[$provider->Id] = array();
         // Get all products.
         $products = Stock::where('Provider', '=', $provider)->get();
         foreach ($products as $product) {
             $order[$provider->Id][$product->Code][$provider->BranchId] = array('Code' => $product->Code, 'Description' => $product->Description, 'Exist' => $product->Quantity, 'Cost' => $product->Cost, 'Minimum' => $product->Minimum, 'Order' => 0, 'Average' => 0, 'Sold' => 0);
         }
         // Get all the products sold in selected sample range.
         $today = date('Y-m-d H:i:s');
         switch ($provider->SampleRange) {
             case '1week':
                 $startDate = date('Y-m-d H:i:s', strtotime($today) - 604800);
                 $sales = Sale::where('BranchId', '=', $branchId)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get();
                 foreach ($sales as $sale) {
                     $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
                     foreach ($breakdown as $item) {
                         if (array_key_exists($item->Code, $order)) {
                             $order[$item->Code]['Sold'] += $item->Quantity;
                         }
                     }
                 }
                 // Now calculate average of each product.
                 foreach ($order as $index => $product) {
                     $order[$index]['Average'] = $product['Sold'] / 7;
                 }
                 break;
             case '2week':
                 $startDate = date('Y-m-d H:i:s', strtotime($today) - 1209600);
                 $sales = Sale::where('BranchId', '=', $branchId)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get();
                 foreach ($sales as $sale) {
                     $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
                     foreach ($breakdown as $item) {
                         if (array_key_exists($item->Code, $order)) {
                             $order[$item->Code]['Sold'] += $item->Quantity;
                         }
                     }
                 }
                 // Now calculate average of each product.
                 foreach ($order as $index => $product) {
                     $order[$index]['Average'] = $product['Sold'] / 14;
                 }
                 break;
             case '1month':
                 $startDate = date('Y-m-d H:i:s', strtotime($today) - 2419200);
                 $sales = Sale::where('BranchId', '=', $branchId)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get();
                 foreach ($sales as $sale) {
                     $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
                     foreach ($breakdown as $item) {
                         if (array_key_exists($item->Code, $order)) {
                             $order[$item->Code]['Sold'] += $item->Quantity;
                         }
                     }
                 }
                 // Now calculate average of each product.
                 foreach ($order as $index => $product) {
                     $order[$index]['Average'] = $product['Sold'] / 30;
                 }
                 break;
             case '3month':
                 $startDate = date('Y-m-d H:i:s', strtotime($today) - 7257600);
                 $sales = Sale::where('BranchId', '=', $branchId)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get();
                 foreach ($sales as $sale) {
                     $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
                     foreach ($breakdown as $item) {
                         if (array_key_exists($item->Code, $order)) {
                             $order[$item->Code]['Sold'] += $item->Quantity;
                         }
                     }
                 }
                 // Now calculate average of each product.
                 foreach ($order as $index => $product) {
                     $order[$index]['Average'] = $product['Sold'] / 90;
                 }
                 break;
             case '1year':
                 $startDate = date('Y-m-d H:i:s', strtotime($today) - 29030400);
                 $sales = Sale::where('BranchId', '=', $branchId)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get();
                 foreach ($sales as $sale) {
                     $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
                     foreach ($breakdown as $item) {
                         if (array_key_exists($item->Code, $order)) {
                             $order[$item->Code]['Sold'] += $item->Quantity;
                         }
                     }
                 }
                 // Now calculate average of each product.
                 foreach ($order as $index => $product) {
                     $order[$index]['Average'] = $product['Sold'] / 365;
                 }
                 break;
         }
     }
     // Now calculate amount to order based on average, existence, minimum and order range.
     switch (Input::get('orderRange')) {
         case '3day':
             foreach ($order as $index => $product) {
                 $estimatedOrder = $product['Average'] * 3;
                 // Order should be at least twice minimum required with existence influded.
                 if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) {
                     $estimatedOrder = $product['Minimum'] * 2;
                 }
                 $order[$index]['Order'] = round($estimatedOrder);
             }
             break;
         case '1week':
             foreach ($order as $index => $product) {
                 $estimatedOrder = $product['Average'] * 7;
                 // Order should be at least twice minimum required with existence influded.
                 if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) {
                     $estimatedOrder = $product['Minimum'] * 2;
                 }
                 $order[$index]['Order'] = round($estimatedOrder);
             }
             break;
         case '2week':
             foreach ($order as $index => $product) {
                 $estimatedOrder = $product['Average'] * 14;
                 // Order should be at least twice minimum required with existence influded.
                 if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) {
                     $estimatedOrder = $product['Minimum'] * 2;
                 }
                 $order[$index]['Order'] = round($estimatedOrder);
             }
             break;
         case '1month':
             foreach ($order as $index => $product) {
                 $estimatedOrder = $product['Average'] * 30;
                 // Order should be at least twice minimum required with existence influded.
                 if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) {
                     $estimatedOrder = $product['Minimum'] * 2;
                 }
                 $order[$index]['Order'] = round($estimatedOrder);
             }
             break;
         case '3month':
             foreach ($order as $index => $product) {
                 $estimatedOrder = $product['Average'] * 90;
                 // Order should be at least twice minimum required with existence influded.
                 if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) {
                     $estimatedOrder = $product['Minimum'] * 2;
                 }
                 $order[$index]['Order'] = round($estimatedOrder);
             }
             break;
     }
     // Check if we have recently made an order for this provider to fix order.
     $aiOrders = AIOrder::where('GenerationDate', '>', date('Y-m-d H:i:s', strtotime($today) - 259200))->where('Received', '=', false)->get();
     foreach ($aiOrders as $o) {
         // Get breakdown and remove quantity from order.
         $breakdown = AIOrderBreakdown::where('AIOrderId', '=', $o->Id)->get();
         foreach ($breakdown as $item) {
             if (array_key_exists($item->Code, $order)) {
                 $order[$item->Code]['Order'] -= $item->Quantity;
             }
         }
     }
     $order = AIOrder::findOrFail(1);
     $breakdown = AIOrderBreakdown::where('AIOrderId', '=', $order->Id)->get();
     // Ship order...
     Mail::send('emails.ai.makeOrder', ['order' => $order, 'breakdown' => $breakdown], function ($message) {
         $message->to('*****@*****.**');
         $message->subject('Orden de Compra');
     });
     $response['state'] = 'Success';
     $response['message'] = 'Servicio eliminado exitosamente!';
     return response()->json($response);
 }