/** * ��� ��������� ����������� �� ����������� �������������, - ���������� � ��� �� API � �������� ���������� ������� ��� ���������� � ������� ��� � ���� � notes_count * @param Request $request */ public function getcounthypercomments(Request $request) { // ���������� �� ��� ������ �� �������-������������ HyperComments � ������ $hcData = json_decode($request['data'], true); $hcSecretkey = 'df28fhdjDJn3ujy7bsdhga73g63k6egx'; if ($request['signature'] != md5($hcSecretkey . $request['data'] . $request['time'])) { exit('Error: invalid data'); } // ���������, �� ����� � ������ �� ��� �� hypercomment-�� $worker_id = basename($hcData[0]['link']); // ���������� �� API � �������� ���������� ������������ ������� (cm2) ��� ���� ��������. ������ �� ������ (cm2) �� ���������, �.�. �������� ���������� ������ if ($curl = curl_init()) { curl_setopt($curl, CURLOPT_URL, 'http://c1api.hypercomments.com/1.0/streams/get'); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); $body = '{"widget_id":79747, "link":"none", "xid":"' . $hcData[0]['xid'] . '"}'; curl_setopt($curl, CURLOPT_POSTFIELDS, 'body=' . $body . '&signature=' . sha1($body . $hcSecretkey)); $out = json_decode(curl_exec($curl), 1); curl_close($curl); } // file_put_contents("/var/www/sh/storage/logs/laravel.log",$out['result'],FILE_APPEND); if ($out['result']=="error") file_put_contents("/var/www/sh/storage/logs/laravel.log",$out['description'],FILE_APPEND); if ($out && $out['result'] == 'success') { $additional_count = $out['data'][0]['cm']; $worker = Worker::find($worker_id); $worker->notes_count = count($worker->notes) + $additional_count; $worker->save(); $worker->addToIndex(); echo 'ok'; } else { echo 'some error'; } exit; }
/** * Get the name of the user */ public function name() { if ($this->Type == 1) { return Worker::find($this->TypeId)->Name; } return Client::find($this->TypeId)->Name; }
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 that gets product suggestions based on query term. * * @return Response */ public function suggestions() { // Validate Input. $validator = Validator::make(Input::all(), array('query' => 'required')); if ($validator->fails()) { return response()->json(['error' => 'Es necesario escribir algo para buscar!']); } // 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 products that match description and sort them into array. $response = array(); $products = Stock::where('Description', 'like', Input::get('query') . '%')->orWhere('Code', 'like', Input::get('query') . '%')->where('BranchId', '=', $branchId)->get(); foreach ($products as $product) { array_push($response, array('label' => $product->Description, 'value' => $product->Code)); } // Return suggestions. return response()->json($response); }
/** * Function that gets events from a worker's calendar. * * @return Response */ public function getEvents() { // 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); // Get the events. $events = array(); $calendar = Calendar::where('WorkerId', '=', $worker->Id)->get(); foreach ($calendar as $event) { array_push($events, array('id' => $event->Id, 'start' => $event->Start, 'end' => $event->End, 'allDay' => $event->AllDay, 'title' => $event->Title)); } // Return response. return response()->json($events); }
/** * @param Note $note * @return \Illuminate\Http\RedirectResponse * @throws \Exception */ public function deleteNote(Note $note) { $note->delete(); $this->calcNotesCount(Worker::find($note->worker_id)); return redirect()->route('admin::worker_notes', $note->worker_id); }
use App\User; use App\Worker; use App\Branch; use App\UserLevel; use App\Notification; use App\StorageRequest; use App\Production; use App\ProductionStage; use App\Stock; $currentNotification = Notification::find($notification); $currentNotification->Seen = true; $currentNotification->save(); $permissions = json_decode(UserLevel::find(Auth::user()->UserLevel)->Permissions); $production = Production::find($pId); $stage = ProductionStage::where('ProductionId', '=', $pId)->where('Stage', '=', $stage)->first(); $worker = Worker::find($stage->WorkerId); $product = Stock::where('Code', '=', $production->Code)->where('BranchId', '=', $worker->BranchId)->first(); ?> <!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">
/** * Function that generates order. * * @return Response */ public function generateOrder() { // Validate Input. $validator = Validator::make(Input::all(), array('provider' => 'required', 'orderRange' => 'required', 'sampleRange' => '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()); } // First let's get the provider. $provider = Provider::find(Input::get('provider')); // Now let's get user's branch. $branchId = Worker::find(Auth::user()->TypeId)->BranchId; // Now let's get all the products for this provider. $products = Stock::where('BranchId', '=', $branchId)->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 (Input::get('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'] = 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)->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; } } } $response['state'] = 'Success'; $response['order'] = $order; return response()->json($response); }
<?php use App\ReservationBreakdown; use App\Stock; use App\Service; use App\Worker; // Get the worker and branch. $worker = Worker::find(Auth::user()->TypeId); $userBranch = $worker->BranchId; // Get the breakdown of the reservation. $reservationBreakdown = ReservationBreakdown::where('ReservationId', '=', $id)->get(); 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; } ?> <thead> <tr><th>Producto</th><th>Precio Individual</th><th>Cantidad</th></tr> </thead> <tbody> @foreach($reservationBreakdown as $breakdown) <tr><td>{{ getName($breakdown->Code, $userBranch) }}</td><td>{{ $breakdown->Price }}</td><td>{{ $breakdown->Quantity }}</td></tr> @endforeach </tbody>
/** * 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); }
/** * Function that adds a loan to defined worker. * * @return Response */ public function requestLoan() { // Validate Input. $validator = Validator::make(Input::all(), array('worker' => 'required', 'formData' => 'required')); if ($validator->fails()) { // No reason why staffId and dayType would not be provided so return nothing. return response()->json(array()); } // 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()); } // Create request. $request = Request::create(array('Amount' => Input::get('formData')['plsamounts'], 'Reason' => Input::get('formData')['plsReasons'], 'RequestBy' => Auth::user()->Id, 'State' => 'pending', 'GrantedBy' => 0, 'Used' => false, 'Created' => date('Y-m-d H:i:s'))); // Notify admins. $worker = Worker::find(Auth::user()->TypeId); $loanTo = Worker::where('Cedula', '=', Input::get('worker'))->first(); $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' => $worker->Name . ' ha solicitado permiso para prestar dinero a ' . $loanTo->Name . '.', 'Url' => '/requestLoan/' . $request->Id, 'Seen' => false)); } $response['state'] = 'Success'; $response['message'] = 'La solicitud fue realizada exitosamente! Recibiras una notificacion cuando haya respuesta de algun administrador.'; return response()->json($response); }
/** * Function that saves default expenses. * * @return Response */ public function saveDefaultExpenses() { // Validate Input. $validator = Validator::make(Input::all(), array('electricity' => 'required', 'water' => 'required', 'phone' => 'required', 'rent' => 'required', 'government' => 'required', 'depreciation' => 'required', 'taxes' => 'required', 'security' => 'required', 'regimen' => '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 user branch. $branch = Branch::find(Worker::find(Auth::user()->TypeId)->BranchId); // Get expenses. $expenses = array('electricity' => Input::get('electricity'), 'water' => Input::get('water'), 'phone' => Input::get('phone'), 'rent' => Input::get('rent'), 'government' => Input::get('government'), 'depreciation' => Input::get('depreciation'), 'taxes' => Input::get('taxes'), 'security' => Input::get('security'), 'regimen' => Input::get('regimen')); $branch->DefaultExpenses = json_encode($expenses); $branch->save(); $response['state'] = 'Success'; $response['message'] = 'Gastos guardados exitosamente!'; return response()->json($response); }
/** * 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); }
/** * Function to get Worker of this Production Stage. */ public function worker() { return Worker::find($this->WorkerId); }
/** * 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!']); }
/** * Function that gets order Information. * * @return Response */ public function addReturn() { // Validate Input. $validator = Validator::make(Input::all(), array('code' => 'required', 'worker' => '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!']); } // Verify that worker exists and is of correct branch. $worker = Worker::find(Input::get('worker')); if (!$worker) { return response()->json(['error' => 'Este trabajador no existe']); } if ($worker->BranchId != 2) { return response()->json(['error' => 'Este trabajador no es parte de la sucursal correcta!']); } // Set item as being repaired. $item->Stage = 0; $item->save(); // Create Repair Stage for item. $itemStage = ProductionStage::create(array('ProductionId' => $item->Id, 'Stage' => 0, 'WorkerId' => $worker->Id, 'Materials' => '{}', 'Date' => date('Y-m-d'))); // Return information. $response['success'] = 'Devolucion hecha exitosamente!'; return response()->json($response); }
/** * Function that creates a new provider. * * @return Response */ public function createProvider() { // Validate Input. $validator = Validator::make(Input::all(), array('name' => 'required', 'number' => 'required', 'email' => 'required', 'ruc' => 'required', 'web' => 'required', 'retainer' => '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); // Create the provider. $provider = Provider::create(array('Name' => Input::get('name'), 'Phone' => Input::get('number'), 'Email' => Input::get('email'), 'RUC' => Input::get('ruc'), 'Web' => Input::get('web'), 'Retainer' => Input::get('retainer'))); // 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 proveedor: " . Input::get('name') . " El proveedor fue creado por {$worker->Name}."; Notification::create(array('UserId' => $admin->Id, 'Reason' => $reason, 'Url' => '/bills/provider/' . $provider->Id, 'Seen' => false)); } // Get updated list of providers. $providers = Provider::all(); $response['state'] = 'Success'; $response['providers'] = $providers; // Return result. return response()->json($response); }
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(); } } }
/** * Function that submits stocktake. * * @return Response */ public function submitStockTake() { // Validate Input. $validator = Validator::make(Input::all(), array('stockItems' => '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; // Create Stocktake. $stocktake = StockTake::create(array('Created' => date('Y-m-d H:i:s'), 'BranchId' => $branchId)); // Now insert the breakdown of the stock. foreach (Input::get('stockItems') as $item) { // Get product. $product = Stock::find($item['id']); // Insert breakdown. StockTakeBreakdown::create(array('StockTakeId' => $stocktake->Id, 'Code' => $product->Code, 'SystemQuantity' => $product->Quantity, 'Counted' => $item['quantity'], 'Difference' => $item['quantity'] - $product->Quantity, 'State' => 0, 'ExtraData' => '')); } $response['state'] = 'Success'; $response['message'] = 'Toma de inventario agregado exitosamente!'; return response()->json($response); }
<?php use App\Asset; use App\Worker; use App\User; $branch = Worker::find(Auth::user()->TypeId)->BranchId; ?> @foreach(Asset::where('BranchId', '=', $branch)->get() as $asset) <tr id="asset-{{ $asset->Id }}"><td>{{ $asset->Description }}</td><td>{{ $asset->Value }}</td><td>{{ $asset->Days }}</td><td>{{ $asset->Type }}</td></tr> @endforeach
/** * 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); } } } }