Ejemplo n.º 1
0
 /**
  * Function that makes a reservation.
  *
  * @return Response
  */
 public function makeReservation()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('items' => 'required', 'institution' => 'required', 'discount' => 'required', 'reservationAmount' => 'required'));
     if ($validator->fails()) {
         return response()->json(['error' => 'No se envio la informacion completa!']);
     }
     // 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(['state' => 'Unauthorized']);
     }
     // Get user branch.
     $worker = Worker::find(Auth::user()->TypeId);
     $userBranch = $worker->BranchId;
     $reservationPrice = 0;
     $branch = Branch::find($userBranch);
     // Get the user's cashbox.
     $cashbox = Cashbox::where('UserId', '=', Auth::user()->Id)->where('Close', '=', NULL)->first();
     // Check that we actually have a cashbox open.
     if (!$cashbox) {
         $response['state'] = 'Error';
         $response['error'] = 'La caja no esta abierta o por lo tanto no se puede realizar la reservacion!';
         return response()->json($response);
     }
     // Check discount is not greater than what user is allowed.
     $permissions = json_decode(UserLevel::find(Auth::user()->UserLevel)->Permissions);
     if (Input::get('discount') > $permissions->permissions->sales->discount->limit) {
         // Check if we have an auth code we can use.
         if (Input::get('authCode') == 0) {
             $response['state'] = 'Error';
             $response['error'] = 'No tiene permiso para otorgar este descuento!';
             return response()->json($response);
         }
         $request = Request::find(Input::get('authCode'));
         if ($request->Used == 1) {
             $response['state'] = 'Error';
             $response['error'] = 'No tiene permiso para otorgar este descuento!';
             return response()->json($response);
         }
         if ($request->Amount != Input::get('discount')) {
             $response['state'] = 'Error';
             $response['error'] = 'No tiene permiso para otorgar este descuento!';
             return response()->json($response);
         }
         $request->Used = 1;
         $request->save();
     }
     // Get client.
     $client = Client::where('Cedula', '=', Input::get('client'))->first();
     // Get institution if defined.
     $institution;
     if (Input::get('institution') != 0) {
         $institution = Institution::find(Input::get('institution'));
         if (!$institution) {
             $response['state'] = 'Error';
             $response['error'] = 'La institucion definida no fue encontrada en el sistema!';
             return response()->json($response);
         }
     }
     // Loop through products and services and get prices.
     $items = json_decode(Input::get('items'));
     foreach ($items as $code => $info) {
         // 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);
             }
             // Add price to total of quotation.
             $reservationPrice += $service->Price * $info->quantity;
         } else {
             // Add price to total of quotation.
             $reservationPrice += $product->Price * $info->quantity;
         }
     }
     $subTotal = $reservationPrice;
     $discount = $reservationPrice * (Input::get('discount') / 100);
     // Give discount.
     $reservationPrice = $reservationPrice * (1 - Input::get('discount') / 100);
     // Calculate tax if required.
     $tax = 0;
     if (json_decode($branch->DefaultExpenses)->regimen == 'cuotageneral') {
         if (Input::get('institution') != 0) {
             if (!$institution->Excempt) {
                 $tax = $salePrice * 0.15;
             }
         } else {
             if (!$client || !$client->Excempt) {
                 $tax = $salePrice * 0.15;
             }
         }
     }
     // Save client information.
     $clientInfo = array();
     if (Input::get('institution') != 0) {
         // Save institution information.
         $clientInfo = array('Name' => $institution->Name, 'Address' => $institution->Address, 'Id' => $institution->RUC);
     } else {
         // Save institution information.
         if ($client) {
             $clientInfo = array('Name' => $client->Name, 'Address' => $client->Address, 'Id' => $client->Cedula);
         }
     }
     // Get reservation info.
     $config = Configuration::find(0);
     // Check that the deposit covers the minimum.
     if (Input::get('reservationAmount') < $config->Dollar * $config->MinimumReservation) {
         $response['state'] = 'Error';
         $response['error'] = 'El deposito minimo para realizar la reservacion es de ' . $config->Dollar * $config->MinimumReservation . ' Cordobas o ' . $config->MinimumReservation . ' Dolares Americanos.';
         return response()->json($response);
     }
     // Make Reservation.
     $reservation;
     if (Input::get('institution') != 0) {
         // Creditor Type 1 = Client, 2 = Institution.
         $reservation = Reservation::create(array('WorkerId' => $worker->Id, 'Value' => $reservationPrice, 'Discount' => Input::get('discount'), 'Tax' => $tax, 'CreditorId' => Input::get('institution'), 'CreditorType' => 2, 'TransactionId' => 0, 'State' => 'fresh', 'Life' => $config->ReservationLife, 'Deposit' => Input::get('reservationAmount')));
     } else {
         if (!$client) {
             $reservation = Reservation::create(array('WorkerId' => $worker->Id, 'Value' => $reservationPrice, 'Discount' => Input::get('discount'), 'Tax' => $tax, 'CreditorId' => 0, 'CreditorType' => 1, 'TransactionId' => 0, 'State' => 'fresh', 'Life' => $config->ReservationLife, 'Deposit' => Input::get('reservationAmount')));
         } else {
             $reservation = Reservation::create(array('WorkerId' => $worker->Id, 'Value' => $reservationPrice, 'Discount' => Input::get('discount'), 'Tax' => $tax, 'CreditorId' => $client->Id, 'CreditorType' => 1, 'TransactionId' => 0, 'State' => 'fresh', 'Life' => $config->ReservationLife, 'Deposit' => Input::get('reservationAmount')));
         }
     }
     // Now that the reservation has been created, create the transaction for it.
     $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 9, 'Amount' => Input::get('reservationAmount'), 'Reason' => 'Deposito de Reservacion: ' . $reservation->Id . '.'));
     $reservation->TransactionId = $transaction->Id;
     $reservation->save();
     // Loop through items and add them to Reservation Breakdown.
     foreach ($items as $code => $info) {
         // Check if product.
         $product = Stock::where('Code', '=', $code)->where('BranchId', '=', $userBranch)->first();
         if (!$product) {
             // Get service cost.
             $service = Service::where('Code', '=', $code)->where('BranchId', '=', $userBranch)->first();
             ReservationBreakdown::create(array('ReservationId' => $reservation->Id, 'Code' => $code, 'Quantity' => $info->quantity, 'Price' => $service->Price));
         } else {
             ReservationBreakdown::create(array('ReservationId' => $reservation->Id, 'Code' => $code, 'Quantity' => $info->quantity, 'Price' => $product->Price));
         }
     }
     // Return success message and return quotation information.
     $response['state'] = 'Success';
     $response['reservationInfo'] = array('SubTotal' => $subTotal, 'Discount' => $discount, 'Tax' => $tax, 'Total' => $reservationPrice + $tax, 'ReservationId' => $reservation->Id, 'Date' => date('d/m/Y'), 'Life' => $config->ReservationLife, 'Deposit' => Input::get('reservationAmount'));
     $response['clientInfo'] = $clientInfo;
     return response()->json($response);
 }
Ejemplo n.º 2
0
                        $transactions = CashboxTransaction::where('DateTime', '>', $startDate . ' 00:00:00')->where('DateTime', '<', $endDate . ' 23:59:00')->get();
                        // Loop through transactions and filter it.
                        foreach ($transactions as $key => $transaction) {
                            $sale = Sale::where('TransactionId', '=', $transaction->Id)->first();
                            if ($sale == null || $sale->CreditorId != $institutionId || $sale->CreditorType != 2) {
                                // Remove current element from transactions array.
                                unset($transactions[$key]);
                            }
                        }
                    } else {
                        if (isset($salesman) && $salesman != 0) {
                            $user = User::where('Type', '=', 1)->where('TypeId', '=', $salesman)->first();
                            $transactions = CashboxTransaction::where('DateTime', '>', $startDate . ' 00:00:00')->where('DateTime', '<', $endDate . ' 23:59:00')->get();
                            // Make sure transaction was made by specified salesman.
                            foreach ($transactions as $key => $transaction) {
                                $cashbox = Cashbox::find($transaction->CashboxId);
                                if ($cashbox->UserId != $user->Id) {
                                    unset($transactions[$key]);
                                }
                            }
                        } else {
                            $transactions = CashboxTransaction::where('DateTime', '>', $startDate . ' 00:00:00')->where('DateTime', '<', $endDate . ' 23:59:00')->get();
                        }
                    }
                }
            }
        }
    }
}
// Define function that translates transaction to a string.
function transactionType($transaction)
 /**
  * Function that uses a reservation. It creates a transaction for the remainder of the money and makes the sale.
  *
  * @return Response
  */
 public function useReservation()
 {
     // 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;
     $salePrice = 0;
     // Get the cashbox.
     $cashbox = Cashbox::where('UserId', '=', Auth::user()->Id)->where('Close', '=', NULL)->first();
     // Check that we actually have a cashbox open.
     if (!$cashbox) {
         $response['state'] = 'Error';
         $response['error'] = 'La caja no esta abierta o por lo tanto no se puede realizar la transaccion!';
         return response()->json($response);
     }
     // Get the reservation.
     $reservation = Reservation::find(Input::get('id'));
     // Make sure the reservation hasn't been used yet.
     if ($reservation->State == 'used' || $reservation->State == 'credit') {
         $response['state'] = 'Error';
         $response['error'] = 'Esta reservacion ya ha sido utilizada!';
         return response()->json($response);
     }
     // Now make sure the reservation hasn't been deleted.
     if ($reservation->State == 'delete') {
         $response['state'] = 'Error';
         $response['error'] = 'Esta reservacion fue eliminada!';
         return response()->json($response);
     }
     // Now make sure the reservation hasn't expired.
     if ($reservation->State == 'late') {
         $response['state'] = 'Error';
         $response['error'] = 'Esta reservacion ya ha expirado!';
         return response()->json($response);
     }
     // Get the reservation breakdown.
     $reservationBreakdown = ReservationBreakdown::where('ReservationId', '=', Input::get('id'))->get();
     // Loop through all items.
     foreach ($reservationBreakdown as $breakdown) {
         // Check if it is a product.
         $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $userBranch)->first();
         if (!$product) {
             // Check if it is a service.
             $service = Service::where('Code', '=', $breakdown->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);
             }
             // Make sure there are enough materials in system and withdraw them.
             $materials = json_decode($service->Materials);
             foreach ($materials as $materialCode => $quantity) {
                 $stock = Stock::where('Code', '=', $materialCode)->where('BranchId', '=', $userBranch);
                 // If we have enough in stock withdraw it.
                 if ($stock->Quantity >= $quantity * $breakdown->Quantity) {
                     $stock->Quantity -= $quantity * $breakdown->Quantity;
                     $stock->save();
                 } else {
                     // Return all items and materials withdrawn so far.
                     $this->returnItems($reservationBreakdown, $breakdown->Code);
                     $response['state'] = 'Error';
                     $response['error'] = 'No hay suficientes materiales o productos!';
                     return response()->json($response);
                 }
             }
             // TODO: Check if any special functions need to be executed.
         } else {
             // Check quantity being taken is not greater than existing quantity in system.
             if ($product->Quantity >= $breakdown->Quantity) {
                 // Reduce products from stock.
                 $product->Quantity -= $breakdown->Quantity;
                 $product->save();
             } else {
                 // Return all items and materials withdrawn so far.
                 $this->returnItems($reservationBreakdown, $breakdown->Code);
                 $response['state'] = 'Error';
                 $response['info'] = $breakdown;
                 $response['product'] = $product;
                 $response['error'] = 'No hay suficientes materiales o productos!';
                 return response()->json($response);
             }
         }
     }
     // Make transaction for remaining reservation debt.
     $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 1, 'Amount' => $reservation->Value + $reservation->Tax - $reservation->Discount - $reservation->Deposit, 'Reason' => 'Venta con Reservacion.'));
     // Make sale.
     $sale;
     // TODO: Payment can also be with credit card.
     $sale = Sale::create(array('WorkerId' => $worker->Id, 'Value' => $reservation->Value - $reservation->Discount, 'Tax' => $reservation->Tax, 'Card' => false, 'TransactionId' => $transaction->Id, 'BranchId' => $userBranch, 'Credit' => 0, 'CreditorId' => $reservation->CreditorId, 'CreditorType' => $reservation->CreditorType, 'Cancelled' => 1));
     // Now add sales breakdown.
     foreach ($reservationBreakdown as $breakdown) {
         // Check if product.
         $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $userBranch)->first();
         if (!$product) {
             // Get service cost.
             $service = Service::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $userBranch)->first();
             $materials = json_decode($service->Materials);
             $cost = 0;
             foreach ($materials as $materialCode => $quantity) {
                 $material = Stock::where('Code', '=', $materialCode)->where('BranchId', '=', $userBranch)->first();
                 $cost += $material->AverageCost * $quantity;
             }
             SaleBreakdown::create(array('SaleId' => $sale->Id, 'Code' => $breakdown->Code, 'Quantity' => $breakdown->Quantity, 'Cost' => $cost * $breakdown->Quantity, 'Price' => $breakdown->Price));
         } else {
             SaleBreakdown::create(array('SaleId' => $sale->Id, 'Code' => $breakdown->Code, 'Quantity' => $breakdown->Quantity, 'Cost' => $product->AverageCost * $breakdown->Quantity, 'Price' => $breakdown->Price));
         }
     }
     // Now update the reservation.
     $reservation->State = 'used';
     $reservation->save();
     $response['state'] = 'Success';
     $response['saleId'] = $sale->Id;
     // Return response.
     return response()->json($response);
 }
Ejemplo n.º 4
0
 /**
  * Function that pays amount to specified bill.
  *
  * @return Response
  */
 public function payExisting()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('formData' => '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 bill.
     $bill = ProviderBill::where('ProviderId', '=', Input::get('formData')['peBillProvider'])->where('BillNumber', '=', Input::get('formData')['peBillNumber'])->first();
     if (!$bill) {
         $response['state'] = 'Error';
         $response['error'] = 'Factura inexistente!';
         return response()->json($response);
     }
     if ($bill->State == 2) {
         $response['state'] = 'Error';
         $response['error'] = 'Esta factura ya ha sido cancelada!';
         return response()->json($response);
     }
     // Get the payments.
     $payments = ProviderBillPayment::where('ProviderBillId', '=', $bill->Id)->get();
     $due = 0;
     foreach ($payments as $payment) {
         $due = $payment->Debt;
     }
     $amount = Input::get('formData')['peBillAmount'];
     if ($amount > $due) {
         $response['state'] = 'Error';
         $response['error'] = 'No se puede hacer un pago mayor a lo que se debe!';
         return response()->json($response);
     }
     // Get cashbox.
     $userId = Auth::user()->Id;
     $cashbox = Cashbox::where('UserId', '=', $userId)->where('Close', '=', NULL)->first();
     if (!$cashbox) {
         $response['state'] = 'Error';
         $response['error'] = 'No se encontro una caja abierta!';
         return response()->json($response);
     }
     $provider = Provider::find(Input::get('formData')['peBillProvider']);
     $reason = "Pago a {$provider->Name} por Factura Numero: " . Input::get('formData')['peBillNumber'];
     $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 2, 'Amount' => $amount, 'Reason' => $reason));
     $due -= $amount;
     $billPayment = ProviderBillPayment::create(array('ProviderBillId' => $bill->Id, 'TransactionId' => $transaction->Id, 'Date' => date('Y-m-d'), 'Payment' => $amount, 'Debt' => $due));
     if ($due == 0) {
         $bill->State = 2;
         $bill->save();
     }
     $response['state'] = 'Success';
     $response['message'] = 'Pago agregado exitosamente!';
     // Return result.
     return response()->json($response);
 }
Ejemplo n.º 5
0
 /**
  * Function that adds a loan to defined worker.
  *
  * @return Response
  */
 public function loanStaff()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('worker' => 'required', 'formData' => 'required'));
     if ($validator->fails()) {
         // No reason why staffId and dayType would not be provided so return nothing.
         return response()->json(array());
     }
     // Check that user is part of authorized staff.
     if (Auth::user()->Type != 1) {
         // If they are unauthorized no point in returning anything.
         return response()->json(array());
     }
     // Check if user has permission to give loans.
     $userToVerify = User::where('Username', '=', Input::get('formData')['plsusername'])->first();
     if (!$userToVerify) {
         $response['state'] = 'Error';
         $response['error'] = 'Este usuario no existe!';
         return response()->json($response);
     }
     if (Auth::validate(array('Username' => Input::get('formData')['plsusername'], 'password' => Input::get('formData')['plspassword'] . $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->staff->loan->can != "true") {
             $response['state'] = 'Error';
             $response['error'] = 'Este usuario no tiene permitido dar prestamos!';
             return response()->json($response);
         }
         // Get the worker.
         $worker = Worker::where('Cedula', '=', Input::get('worker'))->first();
         if (!$worker) {
             $response['state'] = 'Error';
             $response['error'] = 'No se encontro el trabajador!';
             return response()->json($response);
         }
         // Get the current cashbox.
         $cashbox = Cashbox::where('UserId', '=', Auth::user()->Id)->where('Close', '=', NULL)->first();
         if (!$cashbox) {
             $response['state'] = 'Error';
             $response['error'] = 'No hay una caja abierta de la cual se pueda retirar fondos!';
             return response()->json($response);
         }
         // Now give em the loan.
         $loan = WorkerLoan::create(array('Date' => date('Y-m-d'), 'Amount' => Input::get('formData')['plsamount'], 'State' => 2, 'Type' => 1, 'Processed' => false, 'WorkerId' => $worker->Id));
         // Make the transaction.
         $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 3, 'Amount' => Input::get('formData')['plsamount'], 'Reason' => 'Prestamo a ' . $worker->Name));
         $response['state'] = 'Success';
         $response['message'] = 'El prestamo fue realizado exitosamente!';
         return response()->json($response);
     } else {
         $response['state'] = 'Error';
         $response['error'] = 'Este usuario o contraseña incorrectos!';
         return response()->json($response);
     }
 }
Ejemplo n.º 6
0
 /**
  * Function that gets the client's credit information.
  *
  * @return Response
  */
 public function creditDebtPayment()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('formData' => 'required', 'debt' => '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 the user's cashbox.
     $cashbox = Cashbox::where('Close', '=', null)->where('UserId', '=', Auth::user()->Id)->first();
     if (!$cashbox) {
         $response['state'] = 'Error';
         $response['error'] = 'Debe abrir la caja para realizar este pago!';
         return response()->json($response);
     }
     // Get the debt we are paying.
     $debt = Sale::find(Input::get('debt'));
     $totalDebt = $debt->Value + $debt->Tax;
     // Check to see if there have been any previous payments.
     $pastPaymentTotal = 0;
     $payments = CashReceipt::where('Type', '=', 2)->where('TypeId', '=', $debt->Id)->get();
     foreach ($payments as $payment) {
         $pastPaymentTotal += $payment->Value;
     }
     // Check if we are paying too much money.
     if (Input::get('formData')['cdpAmount'] > $totalDebt - $pastPaymentTotal) {
         $response['state'] = 'Error';
         $response['error'] = 'Esta pagando mas del valor pendiente de la factura!';
         return response()->json($response);
     }
     // Realizar pago.
     $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 8, 'Amount' => Input::get('formData')['cdpAmount'], 'Reason' => 'Pago a Deuda de Credito'));
     $payment = CashReceipt::create(array('TransactionId' => $transaction->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Reason' => 'Pago a Deuda de Credito', 'Value' => Input::get('formData')['cdpAmount'], 'Type' => 2, 'TypeId' => $debt->Id));
     if (Input::get('formData')['cdpAmount'] == $totalDebt - $pastPaymentTotal) {
         $debt->Cancelled = true;
         $debt->save();
     }
     $response['state'] = 'Success';
     $response['message'] = 'Pago realizado exitosamente!';
     $response['payment'] = $payment;
     return response()->json($response);
 }
Ejemplo n.º 7
0
 /**
  * Function that makes a payment to the defined contract.
  *
  * @return Response
  */
 public function contractPayment()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('id' => 'required', 'cash' => '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) {
         // If they are unauthorized no point in returning anything.
         return response()->json(array());
     }
     // Get user's cashbox.
     $cashbox = Cashbox::where('UserId', '=', Auth::user()->Id)->where('Close', '=', NULL)->first();
     if (!$cashbox) {
         $response['state'] = 'Error';
         $response['error'] = 'La caja no esta abierta, por lo tanto no se puede realizar el pago al contrato!';
         return response()->json($response);
     }
     // Get the contract information.
     $contract = Contract::find(Input::get('id'));
     // Get current configuration.
     $config = Configuration::find(0);
     // Now make the payment.
     $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 7, 'Amount' => Input::get('cash'), 'Reason' => 'Pago a Contrato.'));
     // Type = 1 when it's a contract payment.
     $cashReceipt = CashReceipt::create(array('TransactionId' => $transaction->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Reason' => 'Pago a Contrato.', 'Value' => Input::get('cash') / $config->Dollar, 'Type' => 1, 'TypeId' => $contract->Id));
     // Now let's check if it the contract's state was late and if it was let's see if we have to update it.
     $contractPayments = CashReceipt::where('Type', '=', 1)->where('TypeId', '=', $contract->Id)->get();
     if ($contract->State == 'late') {
         // Get today's date.
         $today = date_create(date('Y-m-d'));
         // 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 = 'good';
             $contract->save();
         }
     }
     // Check if we have finished paying contract.
     $debt = $contract->Debt;
     foreach ($contractPayments as $contractPayment) {
         $debt -= $contractPayment->Value;
     }
     if ($debt <= 0) {
         $contract->State = 'paid';
         $contract->save();
     }
     $response['receipt'] = $cashReceipt->Id;
     $response['state'] = 'Success';
     // Return response.
     return response()->json($response);
 }
Ejemplo n.º 8
0
 public function refreshCashbox()
 {
     // Check if a cashbox is open and get all transactions, etc from it if there is.
     $cashbox = Cashbox::where('UserId', '=', Auth::user()->Id)->where('Close', '=', NULL)->first();
     if (!$cashbox) {
         $response['state'] = 'Error';
         $response['error'] = 'No hay una caja abierta y por lo tanto no se pudo actualizar los valores de la caja!';
         return response()->json($response);
     }
     $transactions = CashboxTransaction::where('CashboxId', '=', $cashbox->Id)->get();
     $cash = 0;
     $card = 0;
     $providers = 0;
     $staff = 0;
     $others = 0;
     $withdrawals = 0;
     $refunds = 0;
     $sales = 0;
     $initial = 0;
     $creditSales = 0;
     $creditPayments = 0;
     if ($cashbox) {
         // Count the initial cash.
         $bills = json_decode($cashbox->Open);
         foreach ($bills as $bill => $amount) {
             if ($bill != 'dollar') {
                 $cash += $bill * $amount;
             } else {
                 $cash += Configuration::find(0)->Dollar * $amount;
             }
         }
         $initial = $cash;
         // Now count all the other transactions.
         foreach ($transactions as $transaction) {
             switch ($transaction->Type) {
                 case 1:
                     $sales += $transaction->Amount;
                     // Check if a credit card was used for sale.
                     if (Sale::where('TransactionId', '=', $transaction->Id)->first()->Card) {
                         $card += $transaction->Amount;
                     } else {
                         $cash += $transaction->Amount;
                     }
                     break;
                 case 2:
                     $providers += $transaction->Amount;
                     break;
                 case 3:
                     $staff += $transaction->Amount;
                     break;
                 case 4:
                     $others += $transaction->Amount;
                     break;
                 case 5:
                     $withdrawals += $transaction->Amount;
                     break;
                 case 6:
                     $refunds += $transaction->Amount;
                     break;
                     // Contract Payments.
                 // Contract Payments.
                 case 7:
                     $sales += $transaction->Amount;
                     $cash += $transaction->Amount;
                     break;
                     // Credit sales.
                 // Credit sales.
                 case 8:
                     $creditSales += $transaction->Amount;
                     $sales += $transaction->Amount;
                     break;
                     // Deposits for reservations.
                 // Deposits for reservations.
                 case 9:
                     $sales += $transaction->Amount;
                     $cash += $transaction->Amount;
                     break;
                 case 10:
                     $creditPayments += $transaction->Amount;
                     $cash += $transaction->Amount;
                     break;
             }
         }
         $total = $initial + $sales + $refunds + $creditPayments - $providers - $staff - $withdrawals - $others - $creditSales;
         $cash = $cash + $refunds + $creditPayments - $providers - $staff - $withdrawals - $others;
         // Inform user operation was completed succesfully.
         $response['state'] = 'Success';
         $response['total'] = $total;
         $response['cash'] = $cash;
         $response['card'] = $card;
         $response['providers'] = $providers;
         $response['staff'] = $staff;
         $response['others'] = $others;
         $response['withdrawals'] = $withdrawals;
         $response['refunds'] = $refunds;
         $response['sales'] = $sales;
         $response['creditPayments'] = $creditPayments;
         $response['creditSales'] = $creditSales;
         return response()->json($response);
     }
 }
Ejemplo n.º 9
-1
<?php

use App\Cashbox;
use App\CashboxTransaction;
use App\Configuration;
use App\Sale;
use App\SaleBreakdown;
use App\Stock;
use App\Service;
// Check if a cashbox is open and get all transactions, etc from it if there is.
$cashbox = Cashbox::where('UserId', '=', Auth::user()->Id)->where('Close', '=', NULL)->first();
$transactions = array();
$cash = 0;
$card = 0;
$providers = 0;
$staff = 0;
$others = 0;
$withdrawals = 0;
$refunds = 0;
$sales = 0;
$initial = 0;
$creditSales = 0;
$creditPayments = 0;
if ($cashbox) {
    $transactions = CashboxTransaction::where('CashboxId', '=', $cashbox->Id)->get();
    // Count the initial cash.
    $bills = json_decode($cashbox->Open);
    foreach ($bills as $bill => $amount) {
        if ($bill != 'dollar') {
            $cash += $bill * $amount;
        } else {