Ejemplo n.º 1
0
 public function api_update(Request $request)
 {
     $contract = Contract::find($request->input('id'));
     $contract->start_date = $request->input('start_date');
     $contract->status = $request->input('status');
     $contract->end_date = $request->input('end_date');
     $contract->rate = $request->input('rate');
     $contract->car_id = $request->input('car.id');
     $contract->driver_id = $request->input('driver.id');
     $contract->save();
     return response("Updated");
 }
Ejemplo n.º 2
0
 /**
  * Update the specified Contracts in storage.
  * @param  int              $id
  * @param UpdateContractsRequest $request
  * @return Response
  */
 public function update($id, UpdateContractsRequest $request)
 {
     $contracts = $this->contractsRepository->find($id);
     if (empty($contracts)) {
         Flash::error('Contracts not found');
         return redirect(route('contracts.index'));
     }
     $contracts = $this->contractsRepository->updateRich($request->all(), $id);
     $contractsMany = \App\Contract::find($id);
     $contractsMany->gyms()->detach();
     $gyms = $request->input('gyms');
     if (isset($gyms)) {
         foreach ($gyms as $gym) {
             $contractsMany->gyms()->attach($gym);
         }
     }
     $contractsMany->catracas()->detach();
     $catracas = $request->input('catracas');
     if (isset($catracas)) {
         foreach ($catracas as $catraca) {
             $contractsMany->catracas()->attach($catraca);
         }
     }
     $contractsMany->turmas()->detach();
     $turmas = $request->input('turmas');
     if (isset($turmas)) {
         foreach ($turmas as $turma) {
             $contractsMany->turmas()->attach($turma);
         }
     }
     Flash::success('Contracts updated successfully.');
     return redirect(route('contracts.index'));
 }
Ejemplo n.º 3
0
 public function show($id)
 {
     $contract = Contract::find($id);
     return view('contracts.show', compact('contract'));
 }
Ejemplo n.º 4
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);
 }
Ejemplo n.º 5
0
 /**
  * Remove the specified resource from storage.
  *
  * @param  int  $id
  * @return \Illuminate\Http\Response
  */
 public function destroy($id, Request $request)
 {
     $this->validate($request, ['room_id' => 'required|numeric', 'water_degree' => 'required|numeric', 'electric_degree' => 'required|numeric'], ['required' => 'The :attribute field is required', 'numeric' => 'The :attribute field must be numeric']);
     $deleteInput = $request->all();
     $room = Room::find($deleteInput['room_id']);
     $contract = Contract::find($id);
     $feeplancount = FeePlan::where("rent_id", $id)->where('status', 0)->count();
     if ($feeplancount > 0) {
         $ret['status'] = -1;
         $ret['desc'] = '该租户还有欠款为付清,无法终止合同。如中途退出,请联系主管,先走特殊费用终止流程!';
         return $ret;
     } else {
         try {
             DB::beginTransaction();
             $room['water_degree'] = $deleteInput['water_degree'];
             $room['electric_degree'] = $deleteInput['electric_degree'];
             if (!$room->save()) {
                 abort(500, 'Destroy failed');
             }
             $contract['end_water_degree'] = $deleteInput['water_degree'];
             $contract['end_electric_degree'] = $deleteInput['electric_degree'];
             $realendtime = new \DateTime();
             $realEndTimeStr = $realendtime->format('Y-m-d');
             $contract['real_end_time'] = $realEndTimeStr;
             if (!$contract->save()) {
                 abort(500, 'Destroy failed');
             }
             DB::commit();
         } catch (Exception $exception) {
             DB::rollBack();
             abort(500, 'Destroy failed');
         }
         $ret['status'] = Contract::destroy($id);
         return $ret;
     }
 }
Ejemplo n.º 6
0
 /**
  * Function that updates a contract with specified parameters.
  *
  * @return Response
  */
 public function updateContractAuth()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('formData' => 'required', 'contractId' => '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);
     }
     // Now check if information provided for authentication is correct.
     $authenticatedUser = User::where('Username', '=', Input::get('formData')['cusername'])->first();
     if (!$authenticatedUser || !Auth::once(array('Username' => Input::get('formData')['cusername'], 'password' => Input::get('formData')['cpassword'] . $authenticatedUser->Salt, 'Type' => 1))) {
         $response['state'] = 'Error';
         $response['error'] = 'Las credenciales utilizadas son incorrectas!';
         return response()->json($response);
     }
     // Get the permissions of authenticated user.
     $permissions = json_decode(UserLevel::find($authenticatedUser->UserLevel)->Permissions);
     if (!$permissions->permissions->sales->create->contract->update) {
         $response['state'] = 'Error';
         $response['error'] = 'Este usuario no tiene permiso para actualizar contratos!';
         return response()->json($response);
     }
     // Get the contract.
     $contract = Contract::find(Input::get('contractId'));
     $contract->State = Input::get('formData')['contractState'];
     $contract->save();
     $response['state'] = 'Success';
     $response['message'] = 'Contrato cancelado exitosamente!';
     // Return response.
     return response()->json($response);
 }
Ejemplo n.º 7
0
 /**
  * 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);
             }
         }
     }
 }