use App\User; use App\Worker; use App\Branch; use App\UserLevel; use App\Notification; use App\Provider; use App\ProviderBill; use App\ProviderBillBreakdown; use App\Stock; $currentNotification = Notification::find($notification); $currentNotification->Seen = true; $currentNotification->save(); $permissions = json_decode(UserLevel::find(Auth::user()->UserLevel)->Permissions); $provider = Provider::find($pId); $bill = ProviderBill::where('ProviderId', '=', $pId)->where('BillNumber', '=', $bill)->first(); $billBreakdown = ProviderBillBreakdown::where('ProviderBillId', '=', $bill->Id)->get(); $worker = Worker::find(Auth::user()->TypeId); $total = 0; ?> <!DOCTYPE html> <html lang="es"> <head> <title>Eirene Systema Administrativo</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta charset="UTF-8"> <meta name="csrf-token" content="{{{ Session::token() }}}"> <link href="{{ URL::to('/') }}/css/bootstrap.min.css" rel="stylesheet"> <link href="{{ URL::to('/') }}/css/bootstrap-responsive.min.css" rel="stylesheet"> <link href="http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600"
/** * Function that pays amount to specified bill. * * @return Response */ public function payExisting() { // Validate Input. $validator = Validator::make(Input::all(), array('formData' => 'required')); $response = array(); if ($validator->fails()) { $response['state'] = 'Error'; $response['error'] = 'Informacion incompleta!'; 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 bill. $bill = ProviderBill::where('ProviderId', '=', Input::get('formData')['peBillProvider'])->where('BillNumber', '=', Input::get('formData')['peBillNumber'])->first(); if (!$bill) { $response['state'] = 'Error'; $response['error'] = 'Factura inexistente!'; return response()->json($response); } if ($bill->State == 2) { $response['state'] = 'Error'; $response['error'] = 'Esta factura ya ha sido cancelada!'; return response()->json($response); } // Get the payments. $payments = ProviderBillPayment::where('ProviderBillId', '=', $bill->Id)->get(); $due = 0; foreach ($payments as $payment) { $due = $payment->Debt; } $amount = Input::get('formData')['peBillAmount']; if ($amount > $due) { $response['state'] = 'Error'; $response['error'] = 'No se puede hacer un pago mayor a lo que se debe!'; return response()->json($response); } // Get cashbox. $userId = Auth::user()->Id; $cashbox = Cashbox::where('UserId', '=', $userId)->where('Close', '=', NULL)->first(); if (!$cashbox) { $response['state'] = 'Error'; $response['error'] = 'No se encontro una caja abierta!'; return response()->json($response); } $provider = Provider::find(Input::get('formData')['peBillProvider']); $reason = "Pago a {$provider->Name} por Factura Numero: " . Input::get('formData')['peBillNumber']; $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 2, 'Amount' => $amount, 'Reason' => $reason)); $due -= $amount; $billPayment = ProviderBillPayment::create(array('ProviderBillId' => $bill->Id, 'TransactionId' => $transaction->Id, 'Date' => date('Y-m-d'), 'Payment' => $amount, 'Debt' => $due)); if ($due == 0) { $bill->State = 2; $bill->save(); } $response['state'] = 'Success'; $response['message'] = 'Pago agregado exitosamente!'; // Return result. return response()->json($response); }
<?php use App\Provider; use App\ProviderBill; use App\ProviderBillPayment; // Get all the outstanding bills for selected provider. $outstandingBills = array(); if (isset($provider) && $provider == 0) { $outstandingBills = ProviderBill::where('State', '!=', 2)->get(); } else { if (isset($provider) && $provider != 0) { $outstandingBills = ProviderBill::where('State', '!=', 2)->where('ProviderId', '=', $provider)->get(); } } function getProvider($id) { return Provider::find($id); } function getDebt($bill) { $debt = $bill->Value; $payments = ProviderBillPayment::where('ProviderBillId', '=', $bill->Id)->get(); foreach ($payments as $payment) { $debt = $payment->Debt; } return $debt; } function getState($state) { if ($state = 1) { return 'Pendiente';
public function purchaseAnalyticsGraph() { // Validate Input. $validator = Validator::make(Input::all(), array('start' => 'required', 'end' => 'required', 'interval' => 'required', 'toGraph' => 'required', 'currency' => 'required', 'provider' => '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 the branch of the current worker. $branchId = Worker::find(Auth::user()->TypeId)->BranchId; // Get the cashboxes so we can get dollar values. $cashboxes = Cashbox::where('BranchId', '=', $branchId)->where('Date', '>=', Input::get('start'))->where('Date', '<=', Input::get('end'))->get(); $valueDollarByDate = array(); // First let's get all the dollar values in this period of time. foreach ($cashboxes as $cashbox) { if (!array_key_exists($cashbox->Date, $valueDollarByDate)) { $valueDollarByDate[$cashbox->Date] = $cashbox->Dollar; } } // Define keys for all arrays. $initDate = date_create(date('Y-m-d', strtotime(Input::get('start')))); $finalDate = date_create(date('Y-m-d', strtotime(Input::get('end')))); $currentDate = $initDate; $currentDollarValue = 1; // Check if we are getting data on specific products. if (Input::get('provider') == 0) { // Define variable to store all data. $products = array(); $labels = array(); for ($i = 0; $i < count(Input::get('toGraph')); $i++) { // Get the product. $product = Stock::where('BranchId', '=', $branchId)->where('Code', '=', Input::get('toGraph')[$i])->first(); $products[Input::get('toGraph')[$i]] = array('label' => $product->Description, 'quantity' => array(), 'cost' => array(), 'dailyAverage' => 0, 'totalCost' => 0, 'totalQuantity' => 0, 'totalStock' => $product->AverageCost * $product->Quantity); } $totalDays = 0; // Now add all the date keys we will need. while ($currentDate <= $finalDate) { $c = date_format($currentDate, 'Y-m-d'); for ($i = 0; $i < count(Input::get('toGraph')); $i++) { $products[Input::get('toGraph')[$i]]['quantity'][$c] = 0; $products[Input::get('toGraph')[$i]]['cost'][$c] = 0; } if (!array_key_exists($c, $valueDollarByDate)) { $valueDollarByDate[$c] = $currentDollarValue; } else { $currentDollarValue = $valueDollarByDate[$c]; } $totalDays++; date_add($currentDate, date_interval_create_from_date_string("1 day")); } $response['dayDiff'] = $totalDays; // Get all the bills of the selected time frame. $bills = ProviderBill::where('Date', '>=', Input::get('start'))->where('Date', '<=', Input::get('end'))->get(); if (Input::get('currency') == 'cordoba') { foreach ($bills as $bill) { // Get the breakdown of the bill. $billBreakdown = ProviderBillBreakdown::where('ProviderBillId', '=', $bill->Id)->get(); foreach ($billBreakdown as $breakdown) { // Check if this is one of the products we want to graph. if (array_key_exists($breakdown->Code, $products)) { $products[$breakdown->Code]['cost'][date('Y-m-d', strtotime($bill->Date))] += $breakdown->CurrentCost; $products[$breakdown->Code]['quantity'][date('Y-m-d', strtotime($bill->Date))] += $breakdown->Quantity; $products[$breakdown->Code]['totalCost'] += $breakdown->Quantity * $breakdown->CurrentCost; $products[$breakdown->Code]['totalQuantity'] += $breakdown->Quantity; } } } } else { foreach ($bills as $bill) { // Get the breakdown of the bill. $billBreakdown = ProviderBillBreakdown::where('ProviderBillId', '=', $bill->Id)->get(); foreach ($billBreakdown as $breakdown) { // Check if this is one of the products we want to graph. if (array_key_exists($breakdown->Code, $products)) { $products[$breakdown->Code]['cost'][date('Y-m-d', strtotime($bill->Date))] += $breakdown->CurrentCost / $valueDollarByDate[date('Y-m-d', strtotime($bill->Date))]; $products[$breakdown->Code]['quantity'][date('Y-m-d', strtotime($bill->Date))] += $breakdown->Quantity; $products[$breakdown->Code]['totalCost'] += $breakdown->Quantity * $breakdown->CurrentCost / $valueDollarByDate[date('Y-m-d', strtotime($bill->Date))]; $products[$breakdown->Code]['totalQuantity'] += $breakdown->Quantity; } } } } switch (Input::get('interval')) { case 'days': $graphLabels = array(); $productLabels = array(); $productCostByDate = array(); $productQuantityByDate = array(); $productQuantityTotal = array(); $productCostTotal = array(); $productStockTotal = array(); // Prepare graph labels. foreach ($products as $product) { foreach ($product['cost'] as $date => $data) { if (!in_array($date, $graphLabels)) { array_push($graphLabels, $date); } } array_push($productLabels, $product['label']); array_push($productCostByDate, $product['cost']); array_push($productQuantityByDate, $product['quantity']); array_push($productCostTotal, $product['totalCost']); array_push($productQuantityTotal, $product['totalQuantity']); array_push($productStockTotal, $product['totalStock']); } // Return required information. $response['graphLabel'] = $graphLabels; $response['productLabels'] = $productLabels; $response['productCostByDate'] = $productCostByDate; $response['productQuantityByDate'] = $productQuantityByDate; $response['productCostTotal'] = $productCostTotal; $response['productQuantityTotal'] = $productQuantityTotal; $response['productStockTotal'] = $productStockTotal; $response['state'] = 'Success'; return response()->json($response); break; case 'weeks': $graphLabels = array(); $productLabels = array(); $productCostByDate = array(); $productQuantityByDate = array(); $productQuantityTotal = array(); $productCostTotal = array(); $productStockTotal = array(); $productCostByWeek = array(); $productQuantityByWeek = array(); // Prepare graph labels. foreach ($products as $product) { // Reset weekly arrays. $productCostByWeek = array(); $productQuantityByWeek = array(); foreach ($product['cost'] as $date => $data) { if (!in_array(date('W-Y', strtotime($date)), $graphLabels)) { array_push($graphLabels, date('W-Y', strtotime($date))); } if (!array_key_exists(date('W-Y', strtotime($date)), $productCostByWeek)) { $productCostByWeek[date('W-Y', strtotime($date))] = $data; $productQuantityByWeek[date('W-Y', strtotime($date))] = $product['quantity'][$date]; } else { $productCostByWeek[date('W-Y', strtotime($date))] += $data; $productQuantityByWeek[date('W-Y', strtotime($date))] += $product['quantity'][$date]; } } array_push($productLabels, $product['label']); array_push($productCostByDate, $productCostByWeek); array_push($productQuantityByDate, $productQuantityByWeek); array_push($productCostTotal, $product['totalCost']); array_push($productQuantityTotal, $product['totalQuantity']); array_push($productStockTotal, $product['totalStock']); } // Return required information. $response['graphLabel'] = $graphLabels; $response['productLabels'] = $productLabels; $response['productCostByDate'] = $productCostByDate; $response['productQuantityByDate'] = $productQuantityByDate; $response['productCostTotal'] = $productCostTotal; $response['productQuantityTotal'] = $productQuantityTotal; $response['productStockTotal'] = $productStockTotal; $response['state'] = 'Success'; return response()->json($response); break; case 'months': $graphLabels = array(); $productLabels = array(); $productCostByDate = array(); $productQuantityByDate = array(); $productQuantityTotal = array(); $productStockTotal = array(); $productCostTotal = array(); $productCostByMonth = array(); $productQuantityByMonth = array(); // Prepare graph labels. foreach ($products as $product) { // Reset monthly arrays. $productCostByMonth = array(); $productQuantityByMonth = array(); foreach ($product['cost'] as $date => $data) { if (!in_array(date('m-Y', strtotime($date)), $graphLabels)) { array_push($graphLabels, date('m-Y', strtotime($date))); } if (!array_key_exists(date('m-Y', strtotime($date)), $productCostByMonth)) { $productCostByMonth[date('m-Y', strtotime($date))] = $data; $productQuantityByMonth[date('m-Y', strtotime($date))] = $product['quantity'][$date]; } else { $productCostByMonth[date('m-Y', strtotime($date))] += $data; $productQuantityByMonth[date('m-Y', strtotime($date))] += $product['quantity'][$date]; } } array_push($productLabels, $product['label']); array_push($productCostByDate, $productCostByMonth); array_push($productQuantityByDate, $productQuantityByMonth); array_push($productCostTotal, $product['totalCost']); array_push($productQuantityTotal, $product['totalQuantity']); array_push($productStockTotal, $product['totalStock']); } // Return required information. $response['graphLabel'] = $graphLabels; $response['productLabels'] = $productLabels; $response['productCostByDate'] = $productCostByDate; $response['productQuantityByDate'] = $productQuantityByDate; $response['productCostTotal'] = $productCostTotal; $response['productQuantityTotal'] = $productQuantityTotal; $response['productStockTotal'] = $productStockTotal; $response['state'] = 'Success'; return response()->json($response); break; case 'years': $graphLabels = array(); $productLabels = array(); $productCostByDate = array(); $productQuantityByDate = array(); $productQuantityTotal = array(); $productCostTotal = array(); $productStockTotal = array(); $productCostByYear = array(); $productQuantityByYear = array(); // Prepare graph labels. foreach ($products as $product) { // Reset monthly arrays. $productCostByYear = array(); $productQuantityByYear = array(); foreach ($product['cost'] as $date => $data) { if (!in_array(date('Y', strtotime($date)), $graphLabels)) { array_push($graphLabels, date('Y', strtotime($date))); } if (!array_key_exists(date('Y', strtotime($date)), $productCostByYear)) { $productCostByYear[date('Y', strtotime($date))] = $data; $productQuantityByYear[date('Y', strtotime($date))] = $product['quantity'][$date]; } else { $productCostByYear[date('Y', strtotime($date))] += $data; $productQuantityByYear[date('Y', strtotime($date))] += $product['quantity'][$date]; } } array_push($productLabels, $product['label']); array_push($productCostByDate, $productCostByYear); array_push($productQuantityByDate, $productQuantityByYear); array_push($productCostTotal, $product['totalCost']); array_push($productQuantityTotal, $product['totalQuantity']); array_push($productStockTotal, $product['totalStock']); } // Return required information. $response['graphLabel'] = $graphLabels; $response['productLabels'] = $productLabels; $response['productCostByDate'] = $productCostByDate; $response['productQuantityByDate'] = $productQuantityByDate; $response['productCostTotal'] = $productCostTotal; $response['productQuantityTotal'] = $productQuantityTotal; $response['productStockTotal'] = $productStockTotal; $response['state'] = 'Success'; return response()->json($response); break; default: // Anything else we just don't do anything. break; } } else { // Get all the products of the selected provider. $allProducts = Stock::where('BranchId', '=', $branchId)->where('ProviderId', '=', Input::get('provider'))->get(); // Define variable to store all data. $products = array(); $labels = array(); foreach ($allProducts as $product) { $products[$product->Code] = array('label' => $product->Description, 'quantity' => array(), 'cost' => array(), 'dailyAverage' => 0, 'totalCost' => 0, 'totalQuantity' => 0, 'totalStock' => $product->AverageCost * $product->Quantity); } $totalDays = 0; // Now add all the date keys we will need. while ($currentDate <= $finalDate) { $c = date_format($currentDate, 'Y-m-d'); foreach ($products as $code => $data) { $products[$code]['quantity'][$c] = 0; $products[$code]['cost'][$c] = 0; } $all['quantity'][$c] = 0; $all['cost'][$c] = 0; if (!array_key_exists($c, $valueDollarByDate)) { $valueDollarByDate[$c] = $currentDollarValue; } else { $currentDollarValue = $valueDollarByDate[$c]; } $totalDays++; date_add($currentDate, date_interval_create_from_date_string("1 day")); } } $response['dayDiff'] = $totalDays; // Get all the bills of the selected provider. $bills = ProviderBill::where('ProviderId', '=', Input::get('provider'))->where('Date', '>=', Input::get('start'))->where('Date', '<=', Input::get('end'))->get(); if (Input::get('currency') == 'cordoba') { foreach ($bills as $bill) { // Get the breakdown of the bill. $billBreakdown = ProviderBillBreakdown::where('ProviderBillId', '=', $bill->Id)->get(); foreach ($billBreakdown as $breakdown) { // Check if this is one of the products we want to graph. if (array_key_exists($breakdown->Code, $products)) { $products[$breakdown->Code]['cost'][date('Y-m-d', strtotime($bill->Date))] += $breakdown->CurrentCost; $products[$breakdown->Code]['quantity'][date('Y-m-d', strtotime($bill->Date))] += $breakdown->Quantity; $products[$breakdown->Code]['totalCost'] += $breakdown->Quantity * $breakdown->CurrentCost; $products[$breakdown->Code]['totalQuantity'] += $breakdown->Quantity; } } } } else { foreach ($bills as $bill) { // Get the breakdown of the bill. $billBreakdown = ProviderBillBreakdown::where('ProviderBillId', '=', $bill->Id)->get(); foreach ($billBreakdown as $breakdown) { // Check if this is one of the products we want to graph. if (array_key_exists($breakdown->Code, $products)) { $products[$breakdown->Code]['cost'][date('Y-m-d', strtotime($bill->Date))] += $breakdown->CurrentCost / $valueDollarByDate[date('Y-m-d', strtotime($bill->Date))]; $products[$breakdown->Code]['quantity'][date('Y-m-d', strtotime($bill->Date))] += $breakdown->Quantity; $products[$breakdown->Code]['totalCost'] += $breakdown->Quantity * $breakdown->CurrentCost / $valueDollarByDate[date('Y-m-d', strtotime($bill->Date))]; $products[$breakdown->Code]['totalQuantity'] += $breakdown->Quantity; } } } } switch (Input::get('interval')) { case 'days': $graphLabels = array(); $productLabels = array(); $productCostByDate = array(); $productQuantityByDate = array(); $productQuantityTotal = array(); $productCostTotal = array(); $productStockTotal = array(); // Prepare graph labels. foreach ($products as $product) { foreach ($product['cost'] as $date => $data) { if (!in_array($date, $graphLabels)) { array_push($graphLabels, $date); } } array_push($productLabels, $product['label']); array_push($productCostByDate, $product['cost']); array_push($productQuantityByDate, $product['quantity']); array_push($productCostTotal, $product['totalCost']); array_push($productQuantityTotal, $product['totalQuantity']); array_push($productStockTotal, $product['totalStock']); } // Return required information. $response['graphLabel'] = $graphLabels; $response['productLabels'] = $productLabels; $response['productCostByDate'] = $productCostByDate; $response['productQuantityByDate'] = $productQuantityByDate; $response['productCostTotal'] = $productCostTotal; $response['productQuantityTotal'] = $productQuantityTotal; $response['productStockTotal'] = $productStockTotal; $response['state'] = 'Success'; return response()->json($response); break; case 'weeks': $graphLabels = array(); $productLabels = array(); $productCostByDate = array(); $productQuantityByDate = array(); $productQuantityTotal = array(); $productCostTotal = array(); $productStockTotal = array(); $productCostByWeek = array(); $productQuantityByWeek = array(); // Prepare graph labels. foreach ($products as $product) { // Reset weekly arrays. $productCostByWeek = array(); $productQuantityByWeek = array(); foreach ($product['cost'] as $date => $data) { if (!in_array(date('W-Y', strtotime($date)), $graphLabels)) { array_push($graphLabels, date('W-Y', strtotime($date))); } if (!array_key_exists(date('W-Y', strtotime($date)), $productCostByWeek)) { $productCostByWeek[date('W-Y', strtotime($date))] = $data; $productQuantityByWeek[date('W-Y', strtotime($date))] = $product['quantity'][$date]; } else { $productCostByWeek[date('W-Y', strtotime($date))] += $data; $productQuantityByWeek[date('W-Y', strtotime($date))] += $product['quantity'][$date]; } } array_push($productLabels, $product['label']); array_push($productCostByDate, $productCostByWeek); array_push($productQuantityByDate, $productQuantityByWeek); array_push($productCostTotal, $product['totalCost']); array_push($productQuantityTotal, $product['totalQuantity']); array_push($productStockTotal, $product['totalStock']); } // Return required information. $response['graphLabel'] = $graphLabels; $response['productLabels'] = $productLabels; $response['productCostByDate'] = $productCostByDate; $response['productQuantityByDate'] = $productQuantityByDate; $response['productCostTotal'] = $productCostTotal; $response['productQuantityTotal'] = $productQuantityTotal; $response['productStockTotal'] = $productStockTotal; $response['state'] = 'Success'; return response()->json($response); break; case 'months': $graphLabels = array(); $productLabels = array(); $productCostByDate = array(); $productQuantityByDate = array(); $productQuantityTotal = array(); $productCostTotal = array(); $productStockTotal = array(); $productCostByMonth = array(); $productQuantityByMonth = array(); // Prepare graph labels. foreach ($products as $product) { // Reset monthly arrays. $productCostByMonth = array(); $productQuantityByMonth = array(); foreach ($product['cost'] as $date => $data) { if (!in_array(date('m-Y', strtotime($date)), $graphLabels)) { array_push($graphLabels, date('m-Y', strtotime($date))); } if (!array_key_exists(date('m-Y', strtotime($date)), $productCostByMonth)) { $productCostByMonth[date('m-Y', strtotime($date))] = $data; $productQuantityByMonth[date('m-Y', strtotime($date))] = $product['quantity'][$date]; } else { $productCostByMonth[date('m-Y', strtotime($date))] += $data; $productQuantityByMonth[date('m-Y', strtotime($date))] += $product['quantity'][$date]; } } array_push($productLabels, $product['label']); array_push($productCostByDate, $productCostByMonth); array_push($productQuantityByDate, $productQuantityByMonth); array_push($productCostTotal, $product['totalCost']); array_push($productQuantityTotal, $product['totalQuantity']); array_push($productStockTotal, $product['totalStock']); } // Return required information. $response['graphLabel'] = $graphLabels; $response['productLabels'] = $productLabels; $response['productCostByDate'] = $productCostByDate; $response['productQuantityByDate'] = $productQuantityByDate; $response['productCostTotal'] = $productCostTotal; $response['productQuantityTotal'] = $productQuantityTotal; $response['productStockTotal'] = $productStockTotal; $response['state'] = 'Success'; return response()->json($response); break; case 'years': $graphLabels = array(); $productLabels = array(); $productCostByDate = array(); $productQuantityByDate = array(); $productQuantityTotal = array(); $productCostTotal = array(); $productStockTotal = array(); $productCostByYear = array(); $productQuantityByYear = array(); // Prepare graph labels. foreach ($products as $product) { // Reset monthly arrays. $productCostByYear = array(); $productQuantityByYear = array(); foreach ($product['cost'] as $date => $data) { if (!in_array(date('Y', strtotime($date)), $graphLabels)) { array_push($graphLabels, date('Y', strtotime($date))); } if (!array_key_exists(date('Y', strtotime($date)), $productCostByYear)) { $productCostByYear[date('Y', strtotime($date))] = $data; $productQuantityByYear[date('Y', strtotime($date))] = $product['quantity'][$date]; } else { $productCostByYear[date('Y', strtotime($date))] += $data; $productQuantityByYear[date('Y', strtotime($date))] += $product['quantity'][$date]; } } array_push($productLabels, $product['label']); array_push($productCostByDate, $productCostByYear); array_push($productQuantityByDate, $productQuantityByYear); array_push($productCostTotal, $product['totalCost']); array_push($productQuantityTotal, $product['totalQuantity']); array_push($productStockTotal, $product['totalStock']); } // Return required information. $response['graphLabel'] = $graphLabels; $response['productLabels'] = $productLabels; $response['productCostByDate'] = $productCostByDate; $response['productQuantityByDate'] = $productQuantityByDate; $response['productCostTotal'] = $productCostTotal; $response['productQuantityTotal'] = $productQuantityTotal; $response['productStockTotal'] = $productStockTotal; $response['state'] = 'Success'; return response()->json($response); break; default: // Anything else we just don't do anything. break; } $response['state'] = 'Success'; $response['products'] = $products; $response['all'] = $all; return response()->json($response); }
/** * Function that deletes Transaction. * * @return Response */ public function deleteAuthenticated() { // Validate Input. $validator = Validator::make(Input::all(), array('id' => 'required')); $response = array(); if ($validator->fails()) { $response['state'] = 'Error'; $response['error'] = 'La identification de la transaccion es necesaria!'; return response()->json($response); } // 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); } // Verify the user first. $userToVerify = User::where('Username', '=', Input::get('username'))->first(); if (!$userToVerify) { $response['state'] = 'Error'; $response['error'] = 'Este usuario no existe!'; return response()->json($response); } if (Auth::validate(array('Username' => Input::get('username'), 'password' => Input::get('password') . $userToVerify->Salt, 'Type' => 1))) { // If user was verified make sure user has permission to withdraw money. $permissions = json_decode(UserLevel::find($userToVerify->UserLevel)->Permissions); if ($permissions->permissions->cashbox->delete->can != "true") { $response['state'] = 'Error'; $response['d'] = $permissions->permissions->cashbox->delete->can; $response['error'] = 'Este usuario no tiene permitido eliminar transacciones!'; return response()->json($response); } } else { $response['state'] = 'Error'; $response['error'] = 'Usuario o contraseña incorrectos!'; return response()->json($response); } // Get transaction Data. $transaction = CashboxTransaction::find(Input::get('id')); if (!$transaction) { $response['state'] = 'Fail'; $response['error'] = 'Esta transaccion no existe!'; return response()->json($response); } // Get cashbox. $cashbox = Cashbox::find($transaction->CashboxId); // Get worker. $worker = Worker::find(User::find($cashbox->UserId)->TypeId); if ($transaction->Type == 1 || $transaction->Type == 8) { // Get sale. $sale = Sale::where('TransactionId', '=', $transaction->Id)->first(); // Get items in sale. $items = SaleBreakdown::where('SaleId', '=', $sale->Id)->get(); // Loop trough sales breakdown and add products and materials back to stock. foreach ($items as $item) { $product = Stock::where('Code', '=', $item->Code)->where('BranchId', '=', $sale->BranchId)->first(); if (!$product) { $service = Service::where('Code', '=', $item->Code)->where('BranchId', '=', $sale->BranchId)->first(); // Get materials. $materials = json_decode($service->Materials); foreach ($materials as $material => $quantity) { // Update Stock. $product = Stock::where('Code', '=', $material)->where('BranchId', '=', $sale->BranchId)->first(); $product->AverageCost = ($product->AverageCost * $product->Quantity + $product->Cost * $quantity) / ($product->Quantity + $quantity); $product->Quantity += $quantity; $product->save(); } } else { // Update product. $product->AverageCost = ($product->AverageCost * $product->Quantity + $item->Cost * $item->Quantity) / ($product->Quantity + $item->Quantity); $product->Quantity += $item->Quantity; $product->save(); } // Delete item. $item->delete(); } // Now delete sale and trasaction. $sale->delete(); $transaction->delete(); // Now return transaction data. $response['state'] = 'Success'; $response['message'] = 'Transaccion eliminada!'; return response()->json($response); } else { if ($transaction->Type == 7) { // Get the cash receipt. $receipt = CashReceipt::where('TransactionId', '=', $transaction->Id)->first(); // Get the contract. $contract = Contract::find($receipt->TypeId); // Now delete receipt. $receipt->delete(); // Delete transaction. $transaction->delete(); // If contract is not in late state then that means we might need to update the state. if ($contract->State != 'late') { // Get today's date. $today = date_create(date('Y-m-d')); // Get the contract Payments. $contractPayments = CashReceipt::where('Type', '=', 1)->where('TypeId', '=', $contract->Id)->get(); // Get the amount of time that has passed since contract has been created. $time = date_diff($today, date_create($contract->StartDate)); // Check how many intervals have passed. $passedIntervals = 0; if ($contract->QuotaInterval == 'mensuales') { $passedIntervals = floor($time->format('%m')); } else { if ($contract->QuotaInterval == 'quincenales') { /* 1 Month has an average of 4.34524 weeks*/ $passedIntervals = floor($time->format('%a') / 7) / 4.34524; $decimal = $passedIntervals - floor($passedIntervals); if ($decimal >= 0.5) { $passedIntervals = floor($passedIntervals) * 2 + 1; } else { $passedIntervals = floor($passedIntervals) * 2; } } else { if ($contract->QuotaInterval == 'semanales') { $passedIntervals = floor($time->format('%a') / 7); } } } // Now finally get the expected payment. $expectedPayment = $passedIntervals * $contract->Quota; // If it is over the Debt of the contract reset it to contract value. if ($expectedPayment > $contract->Debt) { $expectedPayment = $contract->Debt; } // Calculate real payments. $realPayment = 0; foreach ($contractPayments as $contractPayment) { $realPayment += $contractPayment->Value; } if ($realPayment < $expectedPayment) { $contract->State = 'late'; $contract->save(); } } // Now return transaction data. $response['state'] = 'Success'; $response['message'] = 'Pago a contrato eliminado!'; return response()->json($response); } else { if ($transaction->Type == 9) { // If it's a reservation get the reservation with this transaction Id. $reservation = Reservation::where('TransactionId', '=', $transaction->Id)->first(); $reservation->State = 'deleted'; $reservation->save(); // Now delete transaction. $transaction->delete(); // Now return transaction data. $response['state'] = 'Success'; $response['message'] = 'Deposito y reservacion eliminados!'; return response()->json($response); } else { // Check if this is a payment for a provider bill. if ($transaction->Type == 2) { // Get the provider bill information. $providerBillPayment = ProviderBillPayment::where('TransactionId', '=', $transaction->Id)->first(); // Get the provider bill and provider. $providerBill = ProviderBill::find($providerBillPayment->ProviderBillId); // Check if bill has credit. if ($providerBill->Credit) { // Set as unpaid (No way you can delete a payment and still stay paid -.-). $providerBill->State = 1; $providerBill->save(); // Delete payment. $providerBillPayment->delete(); $response['message'] = 'Transaccion eliminada!'; } else { // Get sale breakdown. $items = ProviderBillBreakdown::where('ProviderBillId', '=', $providerBill->Id)->get(); $response['items'] = $items; // Get the branch of the current worker. $branchId = Worker::find(Auth::user()->TypeId)->BranchId; // Loop through them and update stock. foreach ($items as $item) { // Get product. $product = Stock::where('Code', '=', $item->Code)->where('BranchId', '=', $branchId)->first(); // Update it. $totalAfter = $product->Quantity - $item->Quantity; $product->AverageCost = ($product->AverageCost * $product->Quantity - $item->CurrentCost * $item->Quantity) / $totalAfter; $product->Quantity -= $item->Quantity; $product->save(); //Delete breakdown. $item->delete(); } // Delete transaction, bill, and billpayment. $response['message'] = 'Transaccion eliminada! Al ser el unico pago de una factura de contado se ha eliminado tambien la factura del Proveedor y retirado los productos del Inventario.'; $providerBill->delete(); $providerBillPayment->delete(); $transaction->delete(); } // Return what we have. $response['state'] = 'Success'; } else { // No special action needed just delete it. $transaction->delete(); $response['message'] = 'Transaccion eliminada!'; $response['state'] = 'Success'; } return response()->json($response); } } } }