Пример #1
0
 public function storeContract(Request $request)
 {
     $contract = new Contract();
     $df = new Carbon($request->input('start_date'));
     $dt = new Carbon($request->input('end_date'));
     $contract->start_date = $df;
     $contract->end_date = $dt;
     $contract->rate = (double) $request->input('rate');
     $contract->currency = "GBP";
     $contract->status = $request->input('status');
     $contract->car_id = $request->input('car');
     $contract->driver_id = $request->input('driver');
     $contract->save();
     return redirect('/investor/contracts');
 }
Пример #2
0
 public function destroy($id)
 {
     $property = Property::findOrFail($id);
     $contract = Contract::where('property_id', '=', $id)->delete();
     $property->delete();
     return redirect('properties');
 }
Пример #3
0
 public function status($statusType)
 {
     if (1 == $statusType) {
         $buildingNumber = Building::count();
         $roomNumber = Room::count();
         $buildingRet = ['buildingNumber' => $buildingNumber, 'roomNumber' => $roomNumber];
         return $buildingRet;
     } else {
         if (2 == $statusType) {
             $roomNumber = Room::count();
             $rentedRoomNumber = Contract::count();
             $emptyRoomNumber = $roomNumber - $rentedRoomNumber;
             $rentRet = ['roomNumber' => $roomNumber, 'rentedNumber' => $rentedRoomNumber, 'emptyNumber' => $emptyRoomNumber];
             return $rentRet;
         } else {
             if (3 == $statusType) {
                 $feePlanItem = DB::select('SELECT COUNT(DISTINCT feemeta_id) as counts FROM fee_plans WHERE status=0 AND deleted_at IS NULL');
                 $feePlanRentNumber = DB::select('SELECT COUNT(DISTINCT rent_id) as counts FROM fee_plans WHERE status=0 AND deleted_at IS NULL');
                 $feeRet = ['feePlanNumber' => $feePlanItem[0]->counts, 'feePlanRentNumber' => $feePlanRentNumber[0]->counts];
                 return $feeRet;
             } else {
                 if (4 == $statusType) {
                     $userNumber = User::count();
                     $userRet = ['userCount' => $userNumber];
                     return $userRet;
                 }
             }
         }
     }
 }
Пример #4
0
 public function destroy($id)
 {
     $renter = Renter::findOrFail($id);
     $contract = Contract::where('renter_id', '=', $id)->delete();
     $renter->delete();
     return redirect('renters');
 }
Пример #5
0
 public function roomHistory($room_id)
 {
     $room_contracts = Contract::withTrashed()->where('room_id', $room_id)->select('id', 'contractor_name', 'phone', 'end_water_degree', 'end_electric_degree', 'start_time', 'end_time', 'real_end_time')->get();
     foreach ($room_contracts as &$contract) {
         $images = Image::where('r_id', $contract['id'])->select('path as img', 'imageable_id', 'r_id')->get();
         $contract['images'] = $images;
     }
     return $room_contracts;
 }
Пример #6
0
 /**
  * Run the database seeds.
  *
  * @return void
  */
 public function run()
 {
     //
     $limit = 30;
     for ($i = 0; $i < $limit; $i++) {
         $date = \Carbon\Carbon::now()->addWeeks(rand(-4, 4));
         $end_date = $date->copy()->addWeeks(rand(1, 5))->addDays($i);
         Contract::create(['car_id' => rand(1, 20), 'driver_id' => rand(1, 40), 'status' => rand(1, 4), 'start_date' => $date, 'end_date' => $end_date, 'rate' => rand(20, 40), 'currency' => 'GBP']);
     }
 }
Пример #7
0
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function postContract(CreateContractRequest $request)
 {
     $input = Cookie::get('rate');
     $email = $request->input('email');
     $name = $request->input('first_name');
     $rate = Rate::find($input);
     $contract = new Contract($request->all());
     $contract->rate()->associate($rate);
     /* $contract->save(); */
     /* mail('*****@*****.**','Test','Hello,','') */
     /* email contract */
     /**    Mail::send('emails.contract', $data, function ($message)
      *    {
      *        $message->from('*****@*****.**', 'Laravel');
      *        $message->to('*****@*****.**');
      *        $message->subject($subject);
      *        $message->attach($pathToFile);
      *    });
      */
     return view('contracts.send')->with('email', $email);
 }
Пример #8
0
 /**
  * Store a newly created resource in storage.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
 public function store(Request $request)
 {
     $ret['status'] = 1;
     $this->validate($request, ['id' => 'required|numeric', 'name' => 'required|max:255', 'type' => 'required|numeric', 'assign_type' => 'required|numeric', 'fee' => 'required|numeric', 'alert' => 'required|numeric'], ['required' => 'The :attribute field is required', 'numeric' => 'The :attribute field must be numeric', 'max' => 'The length of :attribute can not bigger than 255']);
     $feePlanInput = $request->all();
     if ($feePlanInput['assign_type'] == 1) {
         $allContracts = Contract::all();
     } else {
         if ($feePlanInput['assign_type'] == 2) {
             $allContracts = Contract::where('building_id', $feePlanInput['building_id'])->get();
         }
     }
     $feePlansArr = array();
     foreach ($allContracts as $contract) {
         $feePlan['feemeta_id'] = $feePlanInput['id'];
         $feePlan['rent_id'] = $contract['id'];
         $feePlan['room_id'] = $contract['room_id'];
         $feePlan['building_id'] = $contract['building_id'];
         $feePlan['fee_name'] = $feePlanInput['name'];
         $feePlan['fee'] = $feePlanInput['fee'];
         $feePlan['status'] = 0;
         $feePlan['user_id'] = $this->user['id'];
         $feePlan['type'] = $feePlanInput['type'];
         if (FeeMeta::isYearlyType($feePlan['type'])) {
             $feePlan['fee_start_date'] = $contract['start_time'];
             $feePlan['fee_end_date'] = $contract['end_time'];
             $alertDate = new \DateTime($feePlan['fee_start_date']);
             $alertDate->add(new \DateInterval('P' . $feePlanInput['days'] . 'D'));
             $feePlan['fee_alert_date'] = $alertDate;
         } else {
             $feePlan['fee_alert_date'] = $feePlanInput['fee_alert_date'];
             $feePlan['fee_start_date'] = $feePlanInput['fee_start_date'];
             $feePlan['fee_end_date'] = $feePlanInput['fee_end_date'];
         }
         if (FeePlan::checkNotExistPlanned($feePlan)) {
             //build up the feeplan data and push to a array
             array_push($feePlansArr, $feePlan);
         }
     }
     if (count($feePlansArr) > 0) {
         $ret['status'] = FeePlan::insert($feePlansArr);
         if (!$ret['status']) {
             abort(500, 'Could not save fee plans');
         }
     } else {
         $ret['status'] = 0;
         $ret['desc'] = "All of the room has this kind of fee already";
     }
     return $ret;
 }
 /**
  * Display a listing of the resource.
  *
  * @return \Illuminate\Http\Response
  */
 public function index($buildingId)
 {
     //  $rooms = Room::with("building")
     $rooms = Room::where('building_id', $buildingId)->get();
     $today = new \DateTime('today');
     foreach ($rooms as &$room) {
         $contract = Contract::where('room_id', $room['id'])->where('end_time', '>=', $today)->get();
         if ($contract->count() > 0) {
             $room['hasContract'] = 1;
             $room['contract'] = $contract[0];
         } else {
             $room['hasContract'] = 0;
         }
     }
     return $rooms;
 }
Пример #10
0
 /**
  * Display a listing of the resource.
  *
  * @return \Illuminate\Http\Response
  */
 public function index()
 {
     $rooms = Room::with(["building" => function ($query) {
         $query->select('name', 'id', 'building_sn');
     }])->get();
     $today = new \DateTime('today');
     foreach ($rooms as &$room) {
         $contract = Contract::where('room_id', $room['id'])->where('end_time', '>=', $today)->get();
         if ($contract->count() > 0) {
             $room['hasContract'] = 1;
             $room['contract'] = $contract[0];
         } else {
             $room['hasContract'] = 0;
         }
     }
     return $rooms;
 }
Пример #11
0
 /**
  * Display a listing of the resource.
  *
  * @return \Illuminate\Http\Response
  */
 public function index()
 {
     $buildings = Building::all();
     $today = new \DateTime('today');
     foreach ($buildings as &$building) {
         $roomsCount = Room::where("building_id", $building['id'])->count();
         $contractsCount = Contract::where('building_id', $building['id'])->where('end_time', '>=', $today)->count();
         $building['contractsNumber'] = $contractsCount;
         $building['emptyNumber'] = $roomsCount - $contractsCount;
         $building['rooms_count'] = $roomsCount;
         if ($building['emptyNumber'] > 0) {
             $building['hasEmptyRoom'] = 1;
         } else {
             $building['hasEmptyRoom'] = 0;
         }
     }
     return $buildings;
 }
Пример #12
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     // Get contracts that are still active.
     $contracts = Contract::where('State', '!=', 'used')->where('State', '!=', 'cancelled')->where('State', '!=', 'paid')->get();
     foreach ($contracts as $contract) {
         // Check if we have visited this month.
         if ($contract->Visited) {
             // Check if we should reset this.
             if ($contract->QuotaInterval == 'mensuales') {
                 if ('01' == date('d')) {
                     $contract->Visited = false;
                     $contract->save();
                 }
             } else {
                 if ($contract->QuotaInterval == 'quincenales') {
                     if ('01' == date('d')) {
                         $contract->Visited = false;
                         $contract->save();
                     } else {
                         if ('16' == date('d')) {
                             $contract->Visited = false;
                             $contract->save();
                         }
                     }
                 } else {
                     if (date('D') == 'Mon') {
                         $contract->Visited = false;
                         $contract->save();
                     }
                 }
             }
         }
         // Check if we need to organize a visit for this contract.
         if (!$contract->Visited) {
             if ($contract->StartDate < date('Y-m-d')) {
                 $visitDates = explode(',', $contract->PaymentDates);
                 foreach ($visitDates as $date) {
                     if ($date == date('d', strtotime("+3 days"))) {
                         // Check if we already have a visit programmed for this contract.
                         $transports = Transport::where('Type', '=', '8')->where('ReasonId', '=', $contract->Id)->where('Date', '=', date('Y-m-d', strtotime("+3 days")))->get();
                         if (count($transports) == 0) {
                             // Get an appropriate vehicle for this.
                             $vehicles = Vehicle::where('BranchId', '=', $contract->BranchId)->where('Repair', '=', false)->get();
                             $vehicle = null;
                             foreach ($vehicles as $v) {
                                 if (!$vehicle) {
                                     $vehicle = $v;
                                 }
                                 // In this case the smaller the vehicle the more suitable it should be.
                                 // TODO: This could be improved.
                                 if ($v->Type < $vehicle->Type) {
                                     $vehicle = $v;
                                 }
                             }
                             if (!$vehicle) {
                                 // In this case we don't have a vehicle and the provider doesn't provide delivery so we must notify an administrator.
                                 $users = User::where('UserLevel', '=', 1)->get();
                                 foreach ($users as $admin) {
                                     Notification::create(array('UserId' => $admin->Id, 'Created' => date('Y-m-d H:i:s'), 'Reason' => 'Aergia no fue capaz de organizar el cobro para el contrato ' . $contract->Code . '. Por favor revisar y organizar el cobro de la cuota de este contrato.', 'Url' => '/contract/' . $contract->Id, 'Seen' => false));
                                 }
                             } else {
                                 // Get location of client.
                                 $client = Client::find($contract->ClientId);
                                 $location = Location::find($client->LocationId);
                                 $transport = Transport::create(array('Date' => date('Y-m-d', strtotime("+3 day")), 'Time' => '00:00:00', 'VehicleId' => $vehicle->Id, 'DriverId' => 0, 'StartLatitude' => 0, 'StartLongitude' => 0, 'Journey' => '[]', 'EndLatitude' => $location->Latitude, 'EndLongitude' => $location->Longitude, 'EndAddress' => $client->Address, 'Distance' => 0, 'ReasonId' => $contract->Id, 'Type' => 8, 'State' => 2, 'Order' => 0, 'Depreciation' => 0));
                                 // Inform creditor of when you shall collect payment.
                                 if ($client->Email != '') {
                                     Mail::send('emails.ai.contractReminder', ['contract' => $contract, 'transport' => $transport], function ($message) use($contract, $client) {
                                         $message->to($client->Email);
                                         $message->subject('Cobro de Cuota de Contrato: ' . $contract->Code);
                                     });
                                 }
                             }
                         }
                     }
                 }
             }
         }
         // TODO: Not sure if I want to do something in these cases.
         switch ($contract->State) {
             case 'usedpending':
                 break;
             case 'late':
                 break;
         }
     }
 }
Пример #13
0
<?php

use App\Contract;
use App\Client;
use App\CashReceipt;
// Get contracts.
$contracts = array();
if (isset($contractCode) && $contractCode != '') {
    $contracts = Contract::where('Code', '=', $contractCode)->get();
} else {
    if (isset($contractClient) && $contractClient != '') {
        $client = Client::where('Cedula', '=', $contractClient)->first();
        $contracts = Contract::where('ClientId', '=', $client->Id)->get();
    } else {
        if (isset($contractState) && $contractState != '') {
            $contracts = Contract::where('State', '=', $contractState)->get();
        }
    }
}
function contractInterval($interval)
{
    // Default will be Monthly.
    $intervalC = 'Mensual';
    // Check if it is anything but monthly and assign text accordingly.
    if ($interval == 'quincenales') {
        $intervalC = 'Quincenal';
    } else {
        if ($interval == 'semanales') {
            $intervalC = 'Semanal';
        }
    }
Пример #14
0
 public function store()
 {
     // validate
     // read more on validation at http://laravel.com/docs/validation
     $rules = array('client_id' => 'required|not_in:0', 'debtor_id' => 'required|not_in:0', 'agreement_id' => 'required|not_in:0', 'tariff_id' => 'required|not_in:0');
     $validator = Validator::make(Input::all(), $rules);
     // process the login
     if ($validator->fails()) {
         $messages = $validator->messages();
         if (count($messages) > 1) {
             $message = 'Поля ';
         } else {
             $message = 'Поле ';
         }
         if ($messages->has('client_id')) {
             $message .= ' клиент,';
         }
         if ($messages->has('debtor_id')) {
             $message .= ' дебитор,';
         }
         if ($messages->has('agreement_id')) {
             $message .= ' договор,';
         }
         if ($messages->has('tariff_id')) {
             $message .= ' тариф';
         }
         if (count($messages) > 1) {
             $message .= ' не выбранны';
         } else {
             $message .= ' не выбранно';
         }
         return redirect()->back()->with('danger', $message)->withInput();
     } else {
         // store
         if (!empty(Input::get('original_documents_value'))) {
             echo "string";
             $original_document_value = Input::get('original_documents_value');
         } else {
             echo "string1";
             $original_document_value = 0;
         }
         $original_document = new OriginalDocument();
         $original_document->type = Input::get('original_documents_select');
         $original_document->name = Input::get('original_documents_select');
         $original_document->value = $original_document_value;
         $original_document->save();
         $contract = new Contract();
         $contract->code = Input::get('contract_code');
         $contract->name = Input::get('contract_name');
         $contract->code_1c = Input::get('contract_code_1c');
         $contract->gd_debitor_1c = Input::get('contract_gd_debitor_1c');
         $contract->description = Input::get('contract_description');
         $contract->created_at = Input::get('contract_created_at');
         if (Input::get('contract_date_end') != NULL) {
             $contract->date_end = Input::get('contract_date_end');
         }
         $contract->save();
         $relation = new Relation();
         $relation->client_id = Input::get('client_id');
         $relation->debtor_id = Input::get('debtor_id');
         $relation->active = Input::get('active');
         $relation->created_at = Input::get('created_at');
         $relation->confedential_factoring = Input::get('confedential_factoring');
         $relation->rpp = Input::get('rpp');
         $relation->agreement_id = Input::get('agreement_id');
         $relation->deferment_start = Input::get('size');
         $relation->deferment = Input::get('deferment');
         $relation->deferment_type = Input::get('deferment_type');
         $relation->waiting_period = Input::get('waiting_period');
         $relation->waiting_period_type = Input::get('waiting_period_type');
         $relation->regress_period = Input::get('regress_period');
         $relation->regress_period_type = Input::get('regress_period_type');
         $relation->original_document_id = $original_document->id;
         $relation->contract_id = $contract->id;
         $relation->tariff_id = Input::get('tariff_id');
         if ($relation->save()) {
             Session::flash('success', 'Связь добавлена');
         }
         return Redirect::to('relation');
     }
 }
Пример #15
0
 /**
  * Remove the specified resource from storage.
  *
  * @param  int  $id
  * @return Response
  */
 public function destroy(Request $request)
 {
     Contract::destroy($request->id);
     return Redirect::route('contracts.index');
 }
Пример #16
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);
 }
Пример #17
0
 /**
  * Store a newly created resource in storage.
  *
  * @param CreateContractRequest $request
  * @return Response
  */
 public function postContract(CreateContractRequest $request)
 {
     //$id = Cookie::get('rate');
     //Create contract
     $id = $request->input('id');
     $rate = Rate::find($id);
     $contract = new Contract($request->all());
     $contract->rate()->associate($rate);
     $contract->save();
     // Contract details
     $email = $request->input('email');
     //Create pdf attachement
     // Simple email
     /* mail('*****@*****.**','Test','Hello,','') */
     /*
     // Email contract
     Mail::send('emails.contract', $data, function ($message)
     {
          $message->from('*****@*****.**', 'Laravel');
          $message->to('*****@*****.**');
          $message->subject($subject);
          $message->attach($pathToFile);
     });
     */
     return view('electric.success')->with('email', $email);
 }
Пример #18
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);
 }
Пример #19
0
 public function destroy($id)
 {
     $contract = Contract::where($id, '=', 'id')->delete();
     return redirect('contracts');
 }
Пример #20
0
 public function ContractRevenueDetail($id)
 {
     $contract = Contract::findOrFail($id);
     $revenues = $contract->revenues->groupBy('weekPaidOn');
     $revenues->transform(function ($item, $key) {
         return $item->transform(function ($item, $key) {
             return ['week' => $item->weekPaidOn, 'date' => $item->created_at->toFormattedDateString(), 'amount' => $item->amount_paid];
         });
     });
     return $revenues;
 }
Пример #21
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;
     }
 }
Пример #22
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'));
 }
Пример #23
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);
             }
         }
     }
 }