Example #1
0
 /**
  * Display the specified resource.
  *
  * @param  int  $id
  * @return \Illuminate\Http\Response
  */
 public function show($id)
 {
     $user = JWTAuth::parseToken()->authenticate();
     $stock = Stock::where('user_id', $user->id)->find($id);
     if (Gate::denies('show-stock', $stock)) {
         abort(403);
     }
     if ($stock) {
         return response()->json($stock);
     }
 }
function getCost($service)
{
    $branchId = Worker::find(Auth::user()->TypeId)->BranchId;
    $materials = json_decode($service->Materials);
    $total = 0;
    foreach ($materials as $material => $quantity) {
        $product = Stock::where('Code', '=', $material)->where('BranchId', '=', $branchId)->first();
        $total += $product->AverageCost * $quantity;
    }
    return $total;
}
function getName($code, $branch)
{
    // Try getting a normal product for this code
    $product = Stock::where('Code', '=', $code)->where('BranchId', '=', $branch)->first();
    if (!$product) {
        // If we failed try getting a service.
        $service = Service::where('Code', '=', $code)->where('BranchId', '=', $branch)->first();
        return $service->Description;
    }
    return $product->Description;
}
Example #4
0
 /**
  * Function that gets product based on code.
  *
  * @return Response
  */
 public function productSearch()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('code' => 'required'));
     $response = array();
     if ($validator->fails()) {
         $response['state'] = 'Error';
         $response['error'] = 'Es necesario escribir el codigo del producto';
         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);
     }
     // Get the branch of the current worker.
     $branchId = Worker::find(Auth::user()->TypeId)->BranchId;
     // Get the product.
     $products = Stock::where('Code', '=', Input::get('code'))->get();
     if ($products->isEmpty()) {
         $response['state'] = 'Error';
         $response['error'] = 'No existe un producto con ese codigo.';
         return response()->json($response);
     }
     if (Input::get('loadAll') == 'false') {
         $found = false;
         foreach ($products as $product) {
             if ($product->BranchId == $branchId) {
                 $found = true;
             }
         }
         if (!$found) {
             $response['state'] = 'Error';
             $response['error'] = 'No existe un producto con ese codigo.';
             return response()->json($response);
         }
     }
     // Check if we are loading the table.
     if (Input::get('loadTable')) {
         return View::make('general.tables.stockTable', array('code' => Input::get('code'), 'loadAll' => Input::get('loadAll')));
     }
     $response['state'] = 'Success';
     return response()->json($response);
 }
                                        <div class="widget-header"> <i class="icon-shopping-cart"></i>
                                            <h3>Materiales Ocupados</h3>
                                        </div>
                                        <!-- /widget-header -->
                                        <div class="widget-content table-responsive table-compras">
                                            <table class="table table-striped table-bordered">
                                                <thead>
                                                    <tr>
                                                        <th>Material</th>
                                                        <th>Cantidad Usado</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    @foreach(json_decode($stage->Materials) as $code => $quantity)
                                                        <?php 
$s = Stock::where('Code', '=', $code)->where('BranchId', '=', $worker->BranchId)->first();
?>
                                                        <tr><td>{{ $s->Description }}</td><td>{{ $quantity }}</td></tr>
                                                    @endforeach
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="span6">
                            <div class="row-fluid form-horizontal">
                                <div class="control-group span8">
                                    <label class="control-label">Trabajador Asignado:</label>
                                    <div class="controls">
<?php

use App\User;
use App\Worker;
use App\Branch;
use App\UserLevel;
use App\Notification;
use App\Stock;
use App\Provider;
$currentNotification = Notification::find($notification);
$currentNotification->Seen = true;
$currentNotification->save();
$permissions = json_decode(UserLevel::find(Auth::user()->UserLevel)->Permissions);
$worker = Worker::find(Auth::user()->TypeId);
$product = Stock::where('Code', '=', $code)->where('BranchId', '=', $id)->first();
$provider = Provider::find($product->ProviderId);
?>
<!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">
        <link href="{{ URL::to('/') }}/css/font-awesome.css" rel="stylesheet">
        <link href="{{ URL::to('/') }}/css/style.css" rel="stylesheet">
Example #7
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);
 }
Example #8
0
             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) {
                     // Check if we have already sold this service.
                     if (array_key_exists($service->Code, $sold)) {
                         $sold[$salebreakdown->Code]['Quantity'] += $salebreakdown->Quantity;
                     } else {
                         $sold[$salebreakdown->Code] = array('Description' => $service->Description, 'Quantity' => $salebreakdown->Quantity);
Example #9
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();
     }
 }
Example #10
0
                                        <!-- /widget-header -->
                                        <div class="widget-content table-responsive table-compras">
                                            <table class="table table-striped table-bordered">
                                                <thead>
                                                    <tr>
                                                        <th>Codigo</th>
                                                        <th>Descripcion</th>
                                                        <th>Cantidad</th>
                                                        <th>Costo</th>
                                                        <th>Total</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    @foreach($billBreakdown as $breakdown)
                                                        <?php 
$s = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $worker->BranchId)->first();
$total += $breakdown->Quantity * $s->Cost;
?>
                                                        <tr><td>{{ $s->Code }}</td><td>{{ $s->Description }}</td><td>{{ $breakdown->Quantity }}</td><td>{{ $s->Cost }}</td><td>{{ $breakdown->Quantity*$s->Cost }}</td></tr>
                                                    @endforeach
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="span6">
                            <div class="row-fluid form-horizontal">
                                <div class="control-group span8">
                                    <label class="control-label">Total:</label>
 /**
  * Function that gets reservation information.
  *
  * @return Response
  */
 public function getReservationData()
 {
     // 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;
     // Get the reservation.
     $reservation = Reservation::find(Input::get('id'));
     // Get the breakdown of the reservation.
     $reservationBreakdown = ReservationBreakdown::where('ReservationId', '=', $reservation->Id)->get();
     $reservationItems = array();
     foreach ($reservationBreakdown as $breakdown) {
         // Try getting the product.
         $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $userBranch)->first();
         if (!$product) {
             // If it's not a product it's a service.
             $service = Service::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $userBranch)->first();
             array_push($reservationItems, array('quantity' => $breakdown->Quantity, 'description' => $service->Description, 'price' => $service->Price));
         } else {
             array_push($reservationItems, array('quantity' => $breakdown->Quantity, 'note' => $product->Description, 'price' => $product->Price));
         }
     }
     // Get the client's or institution's information.
     $client;
     if ($reservation->CreditorId != 0) {
         if ($reservation->CreditorType != 1) {
             $temp = Institution::find($reservation->CreditorId);
             $client = array('Name' => $temp->Name, 'Address' => $temp->Address, 'Id' => $temp->RUC);
         } else {
             $temp = Client::find($reservation->CreditorId);
             $client = array('Name' => $temp->Name, 'Address' => $temp->Address, 'Id' => $temp->Id);
         }
     } else {
         $client = array('Name' => 'No asignado', 'Address' => 'No asignado', 'Id' => 'No asignado');
     }
     // Get configuration info.
     $config = Configuration::find(0);
     //  Now prepare all the information to be returned to user.
     $response['state'] = 'Success';
     $response['clientInfo'] = $client;
     $response['reservationInfo'] = array('Date' => date('Y-m-d', strtotime($reservation->Created)), 'Life' => $config->ReservationLife, 'ReservationId' => $reservation->Id, 'SubTotal' => $reservation->Value, 'Discount' => $reservation->Discount, 'Tax' => $reservation->Tax, 'Deposit' => $reservation->Deposit, 'Total' => $reservation->Value + $reservation->Tax - $reservation->Discount);
     $response['reservationItems'] = $reservationItems;
     // Return response.
     return response()->json($response);
 }
Example #12
0
 public function cancelDispatch($id, Request $request)
 {
     $dispatch = RecipientPackage::find($id);
     $recipient = Recipient::find(Auth::user()->recipient_id);
     foreach ($dispatch->items as $items) {
         $volume = $items->amount * PackagingInformation::find($items->packaging_id)->cm_per_dose * 0.001;
         $stock = Stock::where('recipient_id', $recipient->id)->where('vaccine_id', $items->vaccine_id)->where('lot_number', $items->batch_number)->first();
         $storeStock = StoreStock::where('store_id', $items->store_id)->where('vaccine_id', $items->vaccine_id)->where('lot_number', $items->batch_number)->first();
         $stock->amount = $stock->amount + $items->amount;
         $storeStock->amount = $storeStock->amount + $items->amount;
         $stock->save();
         $storeStock->save();
         //reduce volume in store
         $store = Store::find($items->store_id);
         $store->used_volume = $store->used_volume + $volume;
         $store->save();
         //update line item status
         $items->status = 'canceled';
         $items->save();
         //delete stock item if amount has turned to zero
         if ($stock->amount == 0) {
             $stock->delete();
         }
         if ($storeStock->amount == 0) {
             $storeStock->delete();
         }
     }
     //update arrival status
     $dispatch->receiving_status = 'canceled';
     $dispatch->comments = $request->has('notes') ? $request->input('notes') : "";
     $dispatch->save();
     Log::create(array("user_id" => Auth::user()->id, "action" => "Cancel Dispatch with reference Number " . $dispatch->voucher_number));
     return $dispatch->voucher_number;
 }
 /**
  * Function that sets record of specified item as finished.
  *
  * @return Response
  */
 public function finishItemProduction()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('code' => 'required', 'productCode' => 'required|integer'));
     if ($validator->fails()) {
         return response()->json(['error' => 'All fields are required!']);
     }
     // 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 Item in production.
     $item = Production::find(Input::get('productCode'));
     if (!$item) {
         return response()->json(['error' => 'No existe un ataud con este codigo!']);
     }
     // Make sure that item is still in production.
     $maxStage = $item->maxStage();
     if ($item->Stage > $maxStage) {
         return response()->json(['error' => 'Este ataud ya no esta en produccion!']);
     }
     // Now check that item is ready to move to final stage.
     if ($item->Stage != $maxStage && $item->Stage != 0) {
         return response()->json(['error' => 'Este ataud no esta listo para completarse!']);
     }
     // Check that we aren't repairing.
     if ($item->Stage != 0) {
         $itemStage = $item->currentStage();
         // Get current worker of current stage.
         $worker = Worker::find($itemStage->WorkerId);
         // Check that he is working today.
         $salary = $worker->getDateSalary(date('Y-m-d'));
         if (!$salary) {
             return response()->json(['error' => "El trabajador asignado para la etapa {$item->Stage} no sido agregado a asistencia de hoy!"]);
         }
         // Get the value of the bono.
         $expense = $item->currentExpense();
         $salary->Bonus += $expense->Bonus;
         $salary->save();
     }
     // Now update the stage of item.
     $item->Stage = $maxStage + 1;
     $item->save();
     // Now add it to the stock.
     $stock = Stock::where('Code', '=', $item->Code)->where('BranchId', '=', 2)->first();
     // Calculate the cost of it.
     $stages = $item->stages();
     $cost = 0;
     foreach ($stages as $stage) {
         $materials = json_decode($stage->Materials, true);
         foreach ($materials as $material => $quantity) {
             $stockMaterial = Stock::where('Code', '=', $material)->where('BranchId', '=', 2)->first();
             $cost += $stockMaterial->AverageCost * $quantity;
         }
     }
     $expenses = $item->expenses();
     foreach ($expenses as $expense) {
         $cost += $expense->Bonus;
     }
     $stock->AverageCost = ($stock->AverageCost * $stock->Quantity + $cost) / $stock->Quantity + 1;
     $stock->Cost = $cost;
     $stock->Quantity++;
     $stock->save();
     // Inform user.
     return response()->json(['success' => 'Ataud completado exitosamente!']);
 }
Example #14
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);
 }
Example #15
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);
     }
 }
Example #16
0
                                            <h3>Contenido de Orden</h3>
                                        </div>
                                        <!-- /widget-header -->
                                        <div class="widget-content table-responsive table-compras">
                                            <table class="table table-striped table-bordered">
                                                <thead>
                                                    <tr>
                                                        <th>Producto</th>
                                                        <th>Cantidad a Ordenar</th>
                                                        <th>Cantidad en Existencia</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    @foreach($orderBreakdown as $breakdown)
                                                        <?php 
$product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $branch->Id)->first();
if (!$product) {
    $product = Service::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $branch->Id)->first();
}
?>
                                                        <tr><td>{{ $product->Description }}</td><td>{{ $breakdown->Quantity }}</td><td>{{ $product->Quantity }}</td></tr>
                                                    @endforeach
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="span6">
                            <div class="row-fluid form-horizontal">
 /**
  * Function that gets the item information with specified code.
  *
  * @return Response
  */
 public function loadStageMaterials()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('code' => 'required', 'stage' => 'required'));
     if ($validator->fails()) {
         return response()->json(['error' => 'El codigo es necesario!']);
     }
     // 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 Product.
     $item = Production::find(Input::get('code'));
     // Check if it exists.
     if (!$item) {
         return response()->json(['error' => 'No existe un ataud con este codigo!']);
     }
     // Get the product information.
     $expense = $item->currentExpense();
     $stage = $item->currentStage();
     $maxStage = $item->maxStage();
     // Make all relevant checks.
     if ($item->Stage > $maxStage) {
         return response()->json(['error' => 'Este ataud ya ha sido terminado!']);
     }
     // If item is under repairs return.
     if ($item->Stage == 0) {
         return response()->json(['error' => 'No hay materiales definidos para reparaciones!']);
     }
     // If this item has a grip fuse materials.
     $usedMaterials = json_decode($expense->Materials, true);
     if ($item->Grip) {
         $gripMaterials = json_decode($expense->GripMaterial, true);
         $found = false;
         foreach ($gripMaterials as $gripMaterial => $gripQuantity) {
             foreach ($usedMaterials as $material => $quantity) {
                 // If the material is already in the used Materials just add extra quantity.
                 if ($material == $gripMaterial) {
                     $found = true;
                     $quantity += $gripQuantity;
                 }
             }
             // If the grip material isn't in used Materials add it.
             $usedMaterials[$gripMaterial] = $gripQuantity;
         }
     }
     // Now add product description to used materials.
     foreach ($usedMaterials as $material => $quantity) {
         $stock = Stock::where('Code', '=', $material)->where('BranchId', '=', 2)->get()->first();
         $usedMaterials[$material] = $stock->Description;
     }
     // Prepare information.
     $response = array('materials' => $usedMaterials);
     // Return suggestions.
     return response()->json($response);
 }
Example #18
0
use App\Provider;
use App\Stock;
use App\Branch;
use App\User;
use App\Worker;
// Get all the products for the selected provider or code.
$stock = array();
// Get the worker's branch Id.
$branchId = Worker::find(Auth::user()->TypeId)->BranchId;
if (isset($provider) && $provider == 0 && $code == '') {
    $stock = Stock::where('BranchId', '=', $branchId)->get();
} else {
    if (isset($provider) && $provider != 0 && $code == '') {
        $stock = Stock::where('ProviderId', '=', $provider)->where('BranchId', '=', $branchId)->get();
    } else {
        $stock = Stock::where('Code', '=', $code)->where('BranchId', '=', $branchId)->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;
}
 public function getProduct()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('product' => 'required', 'usingCode' => '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(['state' => 'Unauthorized']);
     }
     // Get the product.
     $product;
     if (Input::get('usingCode') == 'true') {
         $branchId = Worker::find(Auth::user()->TypeId)->BranchId;
         $product = Stock::where('Code', '=', Input::get('product'))->where('BranchId', '=', $branchId)->first();
     } else {
         $product = Stock::find(Input::get('product'));
     }
     if (!$product) {
         $response['state'] = 'Error';
         $response['error'] = 'No existe un producto con este codigo!';
         return response()->json($response);
     }
     // Return provider info.
     $response['state'] = 'Success';
     $response['product'] = $product;
     return response()->json($response);
 }
Example #20
0
function getName($code, $branchId)
{
    // Get product.
    $product = Stock::where('Code', '=', $code)->where('BranchId', '=', $branchId)->first();
    return $product->Description;
}
Example #21
0
 public function resetStock()
 {
     $stock = Stock::where('product_id', $this->product_id)->where('location_id', $this->location_id)->first(['id', 'qty']);
     if ($stock != null) {
         $stock->qty += $this->qty;
         Log::debug('Requesition: reset item qty: success', ['product_id' => $this->product_id, 'location_id' => $this->location_id, 'qty_return' => $this->qty, 'qty_total' => $stock->qty]);
         return $stock->save();
     }
     Log::debug('Requesition: reset item qty: error', ['product_id' => $this->product_id, 'location_id' => $this->location_id, 'qty_return' => $this->qty, 'qty_total' => $stock->qty]);
     return false;
 }
Example #22
0
 /**
  * Function that creates a new product.
  *
  * @return Response
  */
 public function createProduct()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('code' => 'required', 'description' => 'required', 'cost' => 'required', 'price' => 'required', 'minimum' => 'required', 'providerId' => '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 worker.
     $worker = Worker::find(Auth::user()->TypeId);
     // Verify that a product with code doesn't already exist.
     $product = Stock::where('Code', '=', Input::get('code'))->where('BranchId', '=', $worker->BranchId)->first();
     if ($product) {
         $response['state'] = 'Error';
         $response['error'] = 'Ya existe un producto con el codigo especificado!';
         return response()->json($response);
     }
     // Create the product.
     Stock::create(array('Code' => Input::get('code'), 'Description' => Input::get('description'), 'Cost' => Input::get('cost'), 'Price' => Input::get('price'), 'Minimum' => Input::get('minimum'), 'ProviderId' => Input::get('providerId'), 'BranchId' => $worker->BranchId, 'AverageCost' => Input::get('cost'), 'Quantity' => 0));
     // Prepare to notify admins.
     // Admins are UserLevel 1
     $admins = User::where('UserLevel', '=', 1)->get();
     // Now send notifications to admins.
     foreach ($admins as $admin) {
         $reason = "Se ha creado un nuevo producto: " . Input::get('description') . " El producto fue creado por {$worker->Name}.";
         Notification::create(array('UserId' => $admin->Id, 'Reason' => $reason, 'Url' => '/bills/product/' . Input::get('code') . '/branchId/' . $worker->BranchId, 'Seen' => false));
     }
     $response['state'] = 'Success';
     // Return result.
     return response()->json($response);
 }
Example #23
0
 /**
  * Function that gets order Information.
  *
  * @return Response
  */
 public function getStageInfo()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('code' => 'required', 'stage' => 'required'));
     if ($validator->fails()) {
         return response()->json(['error' => 'El codigo del ataud es necesario!']);
     }
     // 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 Item in question.
     $item = Production::find(Input::get('code'));
     if (!$item) {
         return response()->json(['error' => 'No existe un ataud con este codigo!']);
     }
     // Make sure item has finished production.
     $maxStage = $item->maxStage();
     if ($item->Stage <= $maxStage) {
         return response()->json(['error' => 'Este ataud no ha salido del proceso de produccion!']);
     }
     // Now get the stages, workers and materials used.
     $usedMaterials = array();
     $stages = $item->stages;
     foreach ($stages as $stage) {
         $materials = json_decode($stage->Materials, true);
         if ($stage->Stage == Input::get('stage')) {
             foreach ($materials as $material => $quantity) {
                 $description = Stock::where('Code', '=', $material)->where('BranchId', '=', 2)->first()->Description;
                 $usedMaterials[$material]['description'] = $description;
                 $usedMaterials[$material]['quantity'] = $quantity;
             }
         }
     }
     // Return information.
     $response['materials'] = $usedMaterials;
     return response()->json($response);
 }
Example #24
0
                                        <!-- /widget-header -->
                                        <div class="widget-content table-responsive table-compras">
                                            <table class="table table-striped table-bordered">
                                                <thead>
                                                    <tr>
                                                        <th>Producto</th>
                                                        <th>Cantidad</th>
                                                        <th>Costo</th>
                                                        <th>Precio</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    @foreach($salebreakdown as $breakdown)
                                                        <?php 
$description = '';
$stock = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $branchId)->first();
if ($stock) {
    $description = $stock->Description;
} else {
    $service = Service::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $branchId)->first();
    $description = $service->Description;
}
$subtotal += $breakdown->Quantity * $breakdown->Price;
?>
                                                        <tr><td>{{ $description }}</td><td>{{ $breakdown->Quantity }}</td><td>{{ $breakdown->Price }}</td><td>{{ $breakdown->Quantity*$breakdown->Price }}</td></tr>
                                                    @endforeach
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
Example #25
0
 private function returnItems($items, $lastitem)
 {
     // Get user branch.
     $userBranch = Worker::find(Auth::user()->TypeId)->BranchId;
     // Loop through all items.
     foreach ($items as $code => $info) {
         if ($code == $lastitem) {
             return;
         }
         // 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);
             }
             // Return materials.
             $materials = json_decode($service->Materials);
             foreach ($materials as $materialCode => $quantity) {
                 $stock = Stock::where('Code', '=', $materialCode)->where('BranchId', '=', $userBranch)->first();
                 $stock->Quantity += $quantity * $info->quantity;
                 $stock->save();
             }
             // TODO: Check if any special functions need to be executed.
         } else {
             // Return products.
             $product->Quantity += $info->quantity;
             $product->save();
         }
     }
 }
Example #26
0
 public function addStock()
 {
     $items = $this->receiveItems;
     foreach ($items as $item) {
         if ($item->status == ReceiveItem::SUCCESS) {
             $stock = Stock::where('product_id', $item->product_id)->where('location_id', $item->location_id)->first();
             $stock->qty = $stock->qty + $item->qty;
             Log::info('add-stock: receive item', ['stock' => "product_id: {$stock->product_id}, location_id:{$stock->location_id}", 'product_id' => $item->product_id, 'location_id' => $item->location_id, 'stockNow' => $stock->qty, 'stockAdd' => $item->qty]);
             $stock->save();
         }
     }
 }
Example #27
0
 /**
  * Display a stockItems for user.
  *@param $recipient
  * @param $level
  * @return Response
  */
 public function stock_items($recipient, $level)
 {
     //        return Stock::where('recipient_id',Auth::user()->recipient_id)->get();
     if ($level == '1') {
         $dispatch = Stock::where('recipient_id', $recipient)->get();
     } elseif ($level == '2') {
         $orgunit = Recipient::find($recipient);
         $arr = [0, $recipient];
         array_push($arr, $recipient);
         foreach ($orgunit->childrens as $val) {
             array_push($arr, $val->id);
         }
         $dispatch = DB::table('stock')->whereIn('recipient_id', $arr)->get();
     } elseif ($level == '3') {
         $orgunit = Recipient::find($recipient);
         $arr = [0];
         array_push($arr, $recipient);
         foreach ($orgunit->childrens as $val) {
             array_push($arr, $val->id);
             $orgunit1 = Recipient::find($val->id);
             foreach ($orgunit1->childrens as $val) {
                 array_push($arr, $val->id);
             }
         }
         $dispatch = DB::table('stock')->whereIn('recipient_id', $arr)->get();
     } else {
         Stock::where('recipient_id', Auth::user()->recipient_id)->get();
     }
     return $dispatch;
 }
 public function addLimitSellOrder(Request $request)
 {
     $metaData = MetaData::where('meta_key', 'server_status')->first();
     if ($metaData['meta_value'] == 0) {
         $errorData = array('status' => 'fail', 'message' => 'Sorry! Server is closed. Please try later.', 'code' => '422');
         return Response::json($errorData, 200);
     }
     try {
         $productType = Product::find($request['productTypeId']);
         // if(($productType->type  == 0) && ($productType->lot_size * $request['lot'] < 25000)){
         //     $returnData = array(
         //                 'status' => 'fail',
         //                 'message' => 'Sorry! Invalid requist. Please try retail symbol.',
         //                 'code' => '422'
         //             );
         //     return Response::json($returnData,200);
         // }
         // if(($productType->type  == 1) && ($productType->lot_size * $request['lot'] >= 25000)){
         //     $returnData = array(
         //                 'status' => 'fail',
         //                 'message' => 'Sorry! Invalid requist. Please try wholesale symbol.',
         //                 'code' => '422'
         //             );
         //     return Response::json($returnData,200);
         // }
         $stock = Stock::where('productTypeId', $request['productTypeId'])->where('branchId', $request['branchId'])->first();
         // $stock->quantity = AddProduct::where('stockId',$stock->id)->sum('quantity');
         // if($stock->quantity < ($productType->lot_size * $request['lot'])){
         //     $returnData = array(
         //                 'status' => 'fail',
         //                 'message' => 'Sorry! Insufficient stock. Please try low quantity.',
         //                 'code' => '422'
         //             );
         //     return Response::json($returnData,200);
         // }
         $login = Login::where('remember_token', '=', $request->header('token'))->where('status', '=', '1')->where('login_from', '=', $request->ip())->first();
         $clientStock = new LimitOrder();
         $clientStock->memberId = $login->member_id;
         $clientStock->stockId = $stock->id;
         $clientStock->amount = $productType->lot_size * $request['lot'];
         $clientStock->status = 0;
         $clientStock->type = 0;
         $clientStock->priceMin = $request['priceMin'];
         $clientStock->priceMax = $request['priceMax'];
         //$clientStock->cost = ($clientStock->amount/10) * 4800;
         // $date = strtotime("+7 day");
         // $clientStock->delivery_date = date('Y-m-d', $date);
         // $clientStock->ticket = $this->ticket_generate();
         $clientStock->save();
         // $account = new Account;
         // $account->memberId = $login->member_id;
         // $account->addedBy = $login->member_id;
         // $account->type = 0;
         // $account->amount = $clientStock->cost;
         // $account->ticket = $clientStock->ticket;
         // $account->save();
         $returnData = array('status' => 'ok', 'code' => '200', 'limitOrder' => $clientStock);
         return Response::json($returnData, 200);
     } catch (\Exception $e) {
         return $e->getMessage();
     }
 }
Example #29
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     // Get providers.
     $providers = Provider::all();
     // Get the branches.
     $branches = Branch::all();
     // Loop through them and check which ones are set to auto order.
     foreach ($providers as $provider) {
         if ($provider->AIManaged) {
             foreach ($branches as $branch) {
                 // Now let's get all the products for this provider.
                 $products = Stock::where('BranchId', '=', $branch->Id)->where('ProviderId', '=', $provider->Id)->get();
                 $order = array();
                 foreach ($products as $product) {
                     if ($product->Quantity <= $product->Minimum) {
                         $order[$product->Code] = 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', '=', $branch->Id)->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', '=', $branch->Id)->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', '=', $branch->Id)->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', '=', $branch->Id)->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', '=', $branch->Id)->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 ($provider->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'] = ceil($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'] = ceil($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'] = ceil($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'] = ceil($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'] = ceil($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)->where('BranchId', '=', $branch->Id)->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;
                         }
                     }
                 }
                 // Check if we have anything to order.
                 $sendOrder = false;
                 foreach ($order as $item) {
                     if ($item['Order'] > 0) {
                         $sendOrder = true;
                     }
                 }
                 if (!$sendOrder) {
                     return 1;
                 }
                 // Generate Order.
                 $aiOrder = AIOrder::create(array('GenerationDate' => date('Y-m-d H:i:s'), 'ConfirmationDate' => '0000-00-00 00:00:00', 'ProviderId' => $provider->Id, 'BranchId' => $branch->Id, 'Received' => false, 'EstimatedDelivery' => date('Y-m-d', strtotime("+3 days"))));
                 foreach ($order as $item) {
                     AIOrderBreakdown::create(array('AIOrderId' => $aiOrder->Id, 'Code' => $item['Code'], 'Quantity' => $item['Order']));
                 }
                 $breakdown = AIOrderBreakdown::where('AIOrderId', '=', $aiOrder->Id)->get();
                 // Now if the provider has delivery send email with order.
                 if ($provider->Delivery) {
                     // Now check what method we will use to make order.
                     if ($provider->Method == 'email') {
                         try {
                             Mail::send('emails.ai.makeOrder', ['order' => $aiOrder, 'breakdown' => $breakdown], function ($message) use($provider, $aiOrder) {
                                 $message->to($provider->Email);
                                 $message->subject('Orden de Compra: ' . $aiOrder->Id);
                             });
                         } catch (\Exception $e) {
                             // In this case we should let an administrator know that the email order failed.
                             $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 un pedido via correo para ' . $provider->Name . '. Por favor revisar orden y organizar su compra.', 'Url' => '/ai/order/' . $aiOrder->Id, 'Seen' => false));
                             }
                         }
                     } else {
                         if ($provider->Method == 'ai') {
                             // TODO: Establish Contact via AI.
                         }
                     }
                 } else {
                     // If the provider doesn't have delivery program a trip to make purchase.
                     $vehicles = Vehicle::where('BranchId', '=', $branch->Id)->where('Repair', '=', false)->get();
                     $vehicle = null;
                     foreach ($vehicles as $v) {
                         if (!$vehicle) {
                             $vehicle = $v;
                         }
                         // In this case the bigger 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 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 no fue capaz de organizar un pedido a para ' . $provider->Name . '. Por favor revisar orden y organizar su compra.', 'Url' => '/ai/order/' . $aiOrder->Id, 'Seen' => false));
                         }
                     } else {
                         // Get location of provider.
                         $location = Location::find($provider->LocationId);
                         $transport = 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' => $provider->Address, 'Distance' => 0, 'ReasonId' => $aiOrder->Id, 'Type' => 9, 'State' => 2, 'Order' => 0, 'Depreciation' => 0));
                         // Update Estimated Delivery Date.
                         $aiOrder->EstimatedDelivery = date('Y-m-d', strtotime("+1 day"));
                         $aiOrder->save();
                     }
                 }
             }
         }
     }
 }
 /**
  * Function that gets contract payments table.
  *
  * @return Response
  */
 public function contractInfo()
 {
     // 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;
     // Get the contract.
     $contract = Contract::find(Input::get('id'));
     // Get the breakdown of the contract.
     $contractBreakdown = ContractBreakdown::where('ContractId', '=', $contract->Id)->get();
     $contractServices = array();
     foreach ($contractBreakdown as $breakdown) {
         // Try getting the product.
         $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $userBranch)->first();
         if (!$product) {
             // If it's not a product it's a service.
             $service = Service::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $userBranch)->first();
             array_push($contractServices, array('quantity' => $breakdown->Quantity, 'note' => $service->Note));
         } else {
             array_push($contractServices, array('quantity' => $breakdown->Quantity, 'note' => $product->Description));
         }
     }
     // Get the branch.
     $branch = Branch::find($userBranch);
     // Get the client's information.
     $client = Client::find($contract->ClientId);
     // Get the configuration information.
     $config = Configuration::find(0);
     //  Now prepare all the information to be returned to user.
     $response['state'] = 'Success';
     $response['name'] = $client->Name;
     $response['ocupation'] = $client->Ocupation;
     $response['address'] = $client->Address;
     $response['cedula'] = $client->Cedula;
     $response['debt'] = $contract->Debt;
     $response['span'] = floor($contract->Debt / $contract->Quota);
     $response['quota'] = $contract->Quota;
     $response['interval'] = $contract->QuotaInterval;
     $response['paymentDates'] = explode(',', $contract->PaymentDates);
     $response['startDate'] = $contract->StartDate;
     $response['createDate'] = date('Y-m-d', strtotime($contract->Created));
     $response['interest'] = $contract->Interest;
     $response['branchAddress'] = $branch->Address;
     $response['cityCoverage'] = $config->CityCoverage;
     $response['contractServices'] = $contractServices;
     // Return response.
     return response()->json($response);
 }