public function update($logEntryId)
 {
     $reason = \Request::get('reason');
     if (!in_array($reason, ['training', 'testing'])) {
         throw new \BB\Exceptions\ValidationException("Not a valid reason");
     }
     $equipmentLog = $this->equipmentLogRepository->getById($logEntryId);
     /*
     if ($equipmentLog->user_id == \Auth::user()->id) {
         throw new \BB\Exceptions\ValidationException("You can't update your own record");
     }
     */
     if (!\Auth::user()->hasRole($equipmentLog->device) && !\Auth::user()->isAdmin()) {
         throw new \BB\Exceptions\ValidationException("You don't have permission to alter this record");
     }
     if (!empty($equipmentLog->reason)) {
         throw new \BB\Exceptions\ValidationException("Reason already set");
     }
     $billedStatus = $equipmentLog->billed;
     if ($equipmentLog->billed) {
         //the user has been billed, we need to undo this.
         $payments = $this->paymentRepository->getPaymentsByReference($equipmentLog->id . ':' . $equipmentLog->device);
         if ($payments->count() == 1) {
             $this->paymentRepository->delete($payments->first()->id);
             $billedStatus = false;
         } else {
             throw new \BB\Exceptions\ValidationException("Unable to locate related payment, please contact an admin");
         }
     }
     $this->equipmentLogRepository->update($logEntryId, ['reason' => $reason, 'billed' => $billedStatus]);
     \Notification::success("Record Updated");
     return \Redirect::back();
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     //Close records that were left open
     $records = $this->equipmentLogRepository->getActiveRecords();
     foreach ($records as $log) {
         if ($log->last_update && $log->last_update->lt(\Carbon\Carbon::now()->subHour())) {
             //Last update received over an hour ago
             //End the session with the end date being the last update date
             $this->equipmentLogRepository->endSession($log->id, $log->last_update);
         } elseif (!$log->last_update && $log->started->lt(\Carbon\Carbon::now()->subHour())) {
             //started over an hour ago, no updates
             //We don't know how long the user was active so record a minute
             $this->equipmentLogRepository->endSession($log->id, $log->started->addMinute());
         }
     }
     //Combine logs that are very close to each other - this will run over all inactive records that haven't been billed
     $this->combineEquipmentLogs->run();
     //check through all the unbilled inactive records and remove the small ones
     $unbilledRecords = $this->equipmentLogRepository->getUnbilledRecords();
     foreach ($unbilledRecords as $record) {
         $secondsActive = $record->finished->diffInSeconds($record->started);
         //If the record is less than 60 seconds ignore it
         if ($secondsActive <= 60) {
             $record->removed = true;
         }
         //Processing is finished
         //$record->processed = true;
         $record->save();
     }
 }
 /**
  * @return bool
  */
 private function updateLogEntries()
 {
     foreach ($this->logEntries as $entry) {
         //look all the subsequent records for related entries
         //See if there is a record we can join with
         $nextRecord = $this->fetchNextRecord($entry['user_id'], $entry['device'], $entry['reason'], $entry['finished']);
         if ($nextRecord) {
             $this->equipmentLogRepository->update($entry['id'], ['finished' => $nextRecord['finished']]);
             $this->equipmentLogRepository->delete($nextRecord['id']);
             //The array is now dirty - re-fetch it and return to restart the check
             $this->logEntries = $this->equipmentLogRepository->getUnbilledRecords();
             return true;
         }
     }
     return false;
 }
 private function processEndAction()
 {
     //Close the session
     $sessionId = $this->equipmentLogRepository->findActiveUserSession($this->user->id, $this->deviceKey);
     if ($sessionId !== false) {
         $this->equipmentLogRepository->endSession($sessionId);
     } else {
         $sessionId = $this->equipmentLogRepository->recordStartCloseExisting($this->user->id, $this->keyFob->id, $this->deviceKey, 'inaccurate start');
         $this->equipmentLogRepository->endSession($sessionId);
     }
 }
 public function calculatePendingFees()
 {
     $records = $this->equipmentLogRepository->getFinishedUnbilledRecords();
     foreach ($records as $record) {
         $equipment = $this->equipmentRepository->findBySlug($record->device);
         if ($equipment->hasUsageCharge()) {
             $feePerSecond = $this->costPerSecond($equipment->usageCost);
             //How may seconds was the device in use
             $secondsActive = $record->finished->diffInSeconds($record->started);
             //Charges are for a minimum of 15 minutes
             $secondsActive = $this->roundUpSecondsActive($secondsActive);
             $incurredFee = $this->sessionFee($feePerSecond, $secondsActive);
             //If the reason is empty then its not a special case and should be billed
             if (empty($record->reason)) {
                 //Create a payment against the user
                 $this->paymentRepository->recordPayment('equipment-fee', $record->user_id, 'balance', '', $incurredFee, 'paid', 0, $record->id . ':' . $record->device);
             }
         }
         //Mark this log as being billed and complete
         $record->billed = true;
         $record->save();
     }
 }
 public function show($equipmentId)
 {
     $equipment = $this->equipmentRepository->findBySlug($equipmentId);
     $trainers = $this->inductionRepository->getTrainersForEquipment($equipment->induction_category);
     $equipmentLog = $this->equipmentLogRepository->getFinishedForEquipment($equipment->device_key);
     $usageTimes = [];
     $usageTimes['billed'] = $this->equipmentLogRepository->getTotalTime($equipment->device_key, true, '');
     $usageTimes['unbilled'] = $this->equipmentLogRepository->getTotalTime($equipment->device_key, false, '');
     $usageTimes['training'] = $this->equipmentLogRepository->getTotalTime($equipment->device_key, null, 'training');
     $usageTimes['testing'] = $this->equipmentLogRepository->getTotalTime($equipment->device_key, null, 'testing');
     $userInduction = $this->inductionRepository->getUserForEquipment(\Auth::user()->id, $equipment->induction_category);
     $trainedUsers = $this->inductionRepository->getTrainedUsersForEquipment($equipment->induction_category);
     $usersPendingInduction = $this->inductionRepository->getUsersPendingInductionForEquipment($equipment->induction_category);
     return \View::make('equipment.show')->with('equipmentId', $equipmentId)->with('equipment', $equipment)->with('trainers', $trainers)->with('equipmentLog', $equipmentLog)->with('userInduction', $userInduction)->with('trainedUsers', $trainedUsers)->with('usersPendingInduction', $usersPendingInduction)->with('usageTimes', $usageTimes);
 }
 /**
  * Show the form for creating a new resource.
  *
  * @return \Illuminate\Http\Response
  *
  * @SWG\Delete(
  *     path="/acs/activity/{activityId}",
  *     tags={"activity"},
  *     description="End a period of an activity",
  *     @SWG\Parameter(name="activityId", in="path", type="string", required=true),
  *     @SWG\Response(response="204", description="Activity ended/deleted"),
  *     @SWG\Response(response="400", description="Session invalid"),
  *     security={{"api_key": {}}}
  * )
  */
 public function destroy(Request $request, $activityId)
 {
     $keyFob = $this->fobAccess->extendedKeyFobLookup($request->get('tagId'));
     $this->equipmentLogRepository->endSession($activityId);
     return response()->json([], 204);
 }