Example #1
0
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"
                rel="stylesheet">
Example #2
0
 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);
 }
Example #3
0
 /**
  * Function that adds a bill to the system.
  *
  * @return Response
  */
 public function addBill()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('billNumber' => 'required', 'billProvider' => 'required', 'billValue' => 'required', 'billCredit' => 'required', 'billProducts' => 'required', 'billDiscount' => 'required'));
     if ($validator->fails()) {
         return response()->json(['error' => $validator->messages()]);
     }
     // Validate file input.
     /*$validator = Validator::make(Request::all(),
           array(
               'billImage' => 'required|mimes:jpeg,jpg,png|max:2000'
               )
           );
       if($validator->fails()) {
           return response()->json(['error' => $validator->messages()]);
       }*/
     // 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());
     }
     // Calculate the discount percentage.
     $discount = 1 - Input::get('billDiscount') / (Input::get('billDiscount') + Input::get('billValue'));
     // Let's check that the bill Number is unique for this provider.
     $bill = ProviderBill::where('BillNumber', '=', Input::get('billNumber'))->where('ProviderId', '=', Input::get('billProvider'))->first();
     if ($bill) {
         // Inform user bill already exists.
         return response()->json(['error' => 'Una factura con el mismo numero y para el mismo proveedor ya existe en el sistema!']);
     }
     // Get the branch of the current worker.
     $worker = Worker::find(Auth::user()->TypeId);
     $branchId = $worker->BranchId;
     // Create Bill it can either be 1 - pending payment or 2 paid.
     $state = Input::get('billCredit') == 'true' ? 1 : 2;
     // If we have already paid it upfront mark is as paid.
     if ($state == 2) {
         // Make transaction for user's cashbox.
         $userId = Auth::user()->Id;
         $cashbox = Cashbox::where('UserId', '=', $userId)->where('Close', '=', NULL)->first();
         if (!$cashbox) {
             return response()->json(['error' => 'No hay una caja abierta!']);
         }
         $bill = ProviderBill::create(array('Date' => date('Y-m-d'), 'BillNumber' => Input::get('billNumber'), 'Value' => Input::get('billValue'), 'Credit' => Input::get('billCredit') == 'true' ? true : false, 'State' => $state, 'ProviderId' => Input::get('billProvider'), 'BranchId' => $branchId, 'Discount' => Input::get('billDiscount')));
         // Prepare reason for transaction.
         $provider = Provider::find(Input::get('billProvider'));
         $reason = "Pago a {$provider->Name} por Factura Numero: " . Input::get('billNumber');
         // Transaction types 1 : Sale. 2 : Payment. 3 : Withdrawal. 4 : Deposit.
         $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 2, 'Amount' => Input::get('billValue'), 'Reason' => $reason));
         $billPayment = ProviderBillPayment::create(array('ProviderBillId' => $bill->Id, 'TransactionId' => $transaction->Id, 'Date' => date('Y-m-d'), 'Payment' => Input::get('billValue'), 'Debt' => 0));
     } else {
         $bill = ProviderBill::create(array('Date' => date('Y-m-d'), 'BillNumber' => Input::get('billNumber'), 'Value' => Input::get('billValue'), 'Credit' => Input::get('billCredit') == 'true' ? true : false, 'State' => $state, 'ProviderId' => Input::get('billProvider'), 'BranchId' => $branchId, 'Discount' => Input::get('billDiscount')));
         $billPayment = ProviderBillPayment::create(array('ProviderBillId' => $bill->Id, 'TransactionId' => 0, 'Date' => date('Y-m-d'), 'Payment' => 0, 'Debt' => Input::get('billValue')));
     }
     // Now add items that came with bill to stock.
     $notified = false;
     $billProducts = json_decode(Input::get('billProducts'));
     foreach ($billProducts as $product => $data) {
         // First get the item in question from stock.
         $item = Stock::where('Code', '=', $product)->where('BranchId', '=', $branchId)->where('ProviderId', '=', Input::get('billProvider'))->first();
         // Now check if the price was changed.
         if ($item->Cost != $data->cost && !$notified) {
             // Prepare to notify admins.
             // Admins are UserLevel 1
             $admins = User::where('UserLevel', '=', 1)->get();
             // Now send notifications to admins.
             foreach ($admins as $admin) {
                 $provider = Provider::find(Input::get('billProvider'));
                 $worker = Worker::find(Auth::user()->TypeId);
                 $reason = "Hubo cambio de precio en al menos un producto en la factura: " . Input::get('billNumber') . " de el Proveedor {$provider->Name}. " . "La factura fue agregada por {$worker->Name}.";
                 Notification::create(array('UserId' => $admin->Id, 'Reason' => $reason, 'Url' => '/bills/provider/' . $provider->Id . '/viewBill/' . Input::get('billNumber'), 'Seen' => false));
             }
             $notified = true;
         }
         // Now add it to the breakdown of the bill.
         ProviderBillBreakdown::create(array('ProviderBillId' => $bill->Id, 'Code' => $product, 'Quantity' => $data->quantity, 'OldCost' => $item->Cost, 'CurrentCost' => $data->cost));
         // Get the average cost of the stock.
         $quantity = $item->Quantity;
         $totalAverage = $item->AverageCost * $quantity;
         $totalCurrent = $data->quantity * $data->cost * $discount;
         // Calculate new average value.
         $newAverage = ($totalAverage + $totalCurrent) / ($quantity + $data->quantity);
         // Update the stock.
         $item->AverageCost = $newAverage;
         $item->Quantity += $data->quantity;
         $item->save();
         // Now update all costs of all products with this code and provider.
         $items = Stock::where('Code', '=', $product)->where('ProviderId', '=', Input::get('billProvider'))->get();
         foreach ($items as $i) {
             $i->Cost = $data->cost;
             $i->save();
         }
     }
     /*$disk = Storage::disk('local');
             
             // Check if directory for this Provider exists.
             $directory = Input::get('billProvider').'/';
             if(!$disk->exists($directory)) {
     
                 // Create directory for this provider.
                 $disk->makeDirectory($directory);
             }
             $file = Request::file('billImage');
             $extension = $file->getClientOriginalExtension();
     
             // Now move the save the file to directory.
             $disk->put($directory.$bill->Id.'.'.$extension,  file_get_contents($file));
     */
     // Return suggestions.
     return response()->json(['success' => 'Factura agregada exitosamente al sistema!']);
 }
 /**
  * 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);
             }
         }
     }
 }