Exemplo n.º 1
0
 /**
  *  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;
 }
Exemplo n.º 2
0
 /**
  * ��� ��������� ����������� �� ����������� �������������, - ���������� � ��� �� 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;
 }
Exemplo n.º 3
0
 /**
  * @param Organization $organization
  * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
  */
 public function organizationPage(Organization $organization)
 {
     $workers = null;
     $snapshot = Snapshot::where('organization_id', $organization->id)->orderBy('id', 'desc')->first();
     if (!is_null($snapshot)) {
         $workers = Worker::where('snapshot_id', $snapshot->id)->get();
         $workers = Worker::structure($workers);
     }
     $this->getCounters();
     return view('site.organization', ['organization' => $organization, 'snapshot' => $snapshot, 'workers' => $workers, 'fixed' => true]);
 }
Exemplo n.º 4
0
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;
}
Exemplo n.º 5
0
 /**
  * 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);
 }
Exemplo n.º 6
0
<?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
Exemplo n.º 7
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();
     }
 }
 /**
  * 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);
 }
 /**
  * Remove the specified resource from storage.
  *
  * @param  int $id
  * @return \Illuminate\Http\Response
  */
 public function destroy($id)
 {
     Worker::destroy($id);
     return redirect()->back();
 }
Exemplo n.º 10
0
 /**
  * Function to get Worker of this Production Stage.
  */
 public function worker()
 {
     return Worker::find($this->WorkerId);
 }
Exemplo n.º 11
0
 /**
  * Пересчитываем кол-во заметок у работника
  * @param Worker $worker
  */
 protected function calcNotesCount(Worker $worker)
 {
     $worker->notes_count = count($worker->notes);
     $worker->save();
     $worker->addToIndex();
 }
Exemplo n.º 12
0
 /**
  * Счетчики огранизаций и работников
  */
 protected function getCounters()
 {
     View::share('organizationCount', Organization::where('snapshot_id', '>', 0)->count());
     View::share('workersCount', Worker::count());
 }
Exemplo n.º 13
0
 /**
  * Remove the specified resource from storage.
  *
  * @param  int  $id
  * @return \Illuminate\Http\Response
  */
 public function destroy($id)
 {
     return Worker::where('id', $id)->delete();
 }
Exemplo n.º 14
0
 /**
  * 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);
 }
 /**
  * Show the form for creating a new resource.
  * @param Request $request
  * @return Response
  */
 public function postRelated(Request $request)
 {
     $people = People::all();
     $worker = Worker::all();
     $ids = array();
     for ($i = 0; $i < $worker->count(); $i++) {
         for ($j = 0; $j < $people->count(); $j++) {
             if ($people->get($j)->id == $worker->get($i)->people_id) {
                 $ids[] = $people->get($j)->id;
             }
         }
     }
     $people = People::whereNotIn('id', $ids)->get();
     $branch = Branch::findOrFail($request->get('id'));
     return view('admin.listpeople', compact('people', 'branch'));
 }
 /**
  * Display the specified resource.
  *
  * @param  int  $id
  * @return \Illuminate\Http\Response
  */
 public function show($id)
 {
     $moneyPerMonth = DB::select('CALL department_money_per_month_statistic(?)', array($id));
     $packagesCountStatistic = DB::select('CALL sended_received_stats(?)', array($id));
     $best5Clients = DB::select('CALL best_5_clients(?)', array($id));
     $bestWorker = Worker::where('department_id', $id)->orderBy('packages_count', 'desc')->take(1)->get();
     $monthsSet = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
     $values = array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
     foreach ($moneyPerMonth as $stat) {
         $values[array_search($stat->month, $monthsSet)] = $stat->value;
     }
     #return json_encode($months);
     $dept = Department::find($id);
     $workers = $dept->workers();
     $objMoney = json_encode($values);
     $obMonth = json_encode($monthsSet);
     $params = ['department' => $dept, 'workers' => $workers, 'months' => $obMonth, 'money' => $objMoney, 'category' => 4, 'packagesStatistic' => array_shift($packagesCountStatistic), 'moneyPerMonth' => $moneyPerMonth, 'bestWorkers' => $bestWorker, 'bestClients' => $best5Clients, 'category' => 1];
     return View::make('department.detail', $params);
 }
Exemplo n.º 17
0
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">
Exemplo n.º 18
0
 /**
  * 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);
 }
Exemplo n.º 19
0
 /**
  * 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);
 }
Exemplo n.º 20
0
 /**
  * This function reloads the salary of the current staff member.
  */
 public function reloadSalary()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('staffId' => 'required'));
     if ($validator->fails()) {
         return response()->json(['error' => 'La identificacion es necesaria!']);
     }
     // 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) {
         // Store the worker's general information.
         $response['totalInsurance'] = $worker->Insurance;
         // Now get the worker's salary.
         $days = $worker->salary;
         // Store information in response array.
         $response['totalSalary'] = 0;
         $response['salary'] = array();
         foreach ($days as $day) {
             $response['totalSalary'] += $day->Basic + $day->Bono;
             array_push($response['salary'], array('date' => $day->Date, 'basic' => $day->Basic, 'bono' => $day->Bonus));
         }
         // Now get the worker's loans.
         $loans = $worker->loans;
         // Store information in response array.
         $response['totalLoans'] = 0;
         $response['loans'] = array();
         foreach ($loans as $loan) {
             // If loan has been approved deduct from salary.
             if ($loan->State == 2) {
                 $response['totalLoans'] += $loan->Amount;
             }
             // Define the loan state.
             $state = 'Solicitado';
             switch ($loan->State) {
                 // State 1 not necessary.
                 case 2:
                     $state = 'Aprobado';
                     break;
                 case 3:
                     $state = 'Rechazado';
                     break;
             }
             array_push($response['loans'], array('date' => $loan->Date, 'loan' => $loan->Amount, 'state' => $state));
         }
         // Calculate how much worker will earn.
         $response['totalEarned'] = $response['totalSalary'] - $response['totalLoans'] - $response['totalInsurance'];
         // Return response.
         return response()->json($response);
     } else {
         return response()->json(['error' => 'Trabajador inexistente']);
     }
 }
Exemplo n.º 21
0
 /**
  * Удаление организации
  * @param Organization $organization
  * @return \Illuminate\Http\RedirectResponse
  * @throws \Exception
  */
 public function delete(Organization $organization)
 {
     // удаляем подразделения
     Organization::where('parent_id', $organization->id)->delete();
     // удаляем сотрудников
     Worker::where('organization_id', $organization->id)->delete();
     Snapshot::where('organization_id', $organization->id)->delete();
     // удаляем саму организацию
     $organization->delete();
     return redirect()->route('admin::organization');
 }
Exemplo n.º 22
0
 /**
  * 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!']);
 }
Exemplo n.º 23
0
 /**
  * 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);
 }
Exemplo n.º 24
0
 /**
  * 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);
 }
Exemplo n.º 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();
         }
     }
 }
Exemplo n.º 26
0
<?php

use App\Branch;
use App\User;
use App\Worker;
use App\WorkerPayment;
// Get all the payments.
$payments = array();
// Get the worker's branch Id.
$worker = Worker::where('Cedula', '=', $worker)->first();
if ($worker != null) {
    $branchId = $worker->BranchId;
    $payments = WorkerPayment::where('WorkerId', '=', $worker->Id)->get();
}
?>
@foreach($payments as $payment)
	<tr id='payment-{{ $payment->Id }}'><td>{{ $payment->Date }}</td><td>{{ $payment->WorkedDays }}</td><td>{{ $payment->VacationDays }}</td><td>{{ $payment->TotalBasic }}</td><td>{{ $payment->TotalBonus }}</td><td>{{ $payment->TotalAguinaldo }}</td><td>{{ $payment->TotalLoan }}</td><td>{{ $payment->TotalInsurance }}</td></tr>
@endforeach
<?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>
Exemplo n.º 28
0
 /**
  * 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);
 }
Exemplo n.º 29
0
<?php

// Import all the models we need.
use App\Worker;
use App\Institution;
use App\Client;
use App\User;
use App\CashboxTransaction;
use App\Sale;
// Get the workers.
// TODO: Once permissions have been figured out filter only workers who have cashboxes.
$workers = Worker::all();
// Get transactions.
$defaultStartDate = date('Y-m-d', strtotime(date('Y-m-d') . '-1 days'));
$defaultEndDate = date('Y-m-d H:i:s');
?>
<script src="{{ URL::to('/') }}/js/reservations.js"></script>
<div class="main hideable hide" id="reservations">
	<div class="main-inner">
		<div class="container">
			<div class="row">
				<div class="span6">
					<div class="row-fluid v-offset-2">
						<div class="control-group span12">
							<div class="center" style="width:280px">
								<a type="button" class="btn btn-info" href="#history">
									<i class="icon-list-alt"></i> Transacciones
								</a>
								<a type="button" class="btn btn-info" href="#contracts">
									<i class="icon-legal"></i> Contratos
								</a>
Exemplo n.º 30
0
 /**
  * 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);
 }