示例#1
0
 public function updateStockTakeData()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('stocktake' => '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 branch of the current worker.
     $worker = Worker::find(Auth::user()->TypeId);
     $branchId = $worker->BranchId;
     $cashbox = Cashbox::where('BranchId', '=', $branchId)->where('Close', '=', null)->where('UserId', '=', Auth::user()->Id)->first();
     if (!$cashbox) {
         $response['state'] = 'Error';
         $response['error'] = 'Es necesario tener la caja abierta para realizar esta accion!';
         return response()->json($response);
     }
     // Let's loop through the stocktake breakdown and start making necessary changes.
     foreach (Input::get('stocktake') as $item) {
         $breakdown = StockTakeBreakdown::find($item['id']);
         // Compare current state to submitted state and that difference is more or less than 0.
         if ($breakdown->State != $item['state'] && $breakdown->Difference != 0) {
             // If we are changing state make sure to undo any previous changes if we have to.
             if ($breakdown->State > 1 && $breakdown->State < 4) {
                 if ($breakdown->State == 2) {
                     // Get the salebreakdown.
                     $salebreakdown = SaleBreakdown::find(json_decode($breakdown->ExtraData)->salebreakdownId);
                     // Now the sale.
                     $sale = Sale::find($salebreakdown->SaleId);
                     // Now the transaction.
                     $transaction = CashboxTransaction::find($sale->TransactionId);
                     // Now delete them all.
                     $transaction->delete();
                     $sale->delete();
                     $salebreakdown->delete();
                     $breakdown->ExtraData = '';
                     $breakdown->save();
                 }
                 $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $branchId)->first();
                 $product->Quantity -= $breakdown->Difference;
                 $product->save();
             }
             // Make changes.
             if ($item['state'] == 2) {
                 // Get the product.
                 $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $branchId)->first();
                 // Now make the sale.
                 if ($breakdown->Difference > 0) {
                     // Make an empty transaction.
                     $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 10, 'Amount' => 0, 'Reason' => 'Correccion de Inventario.'));
                     // Now make the sale so we can reflect the difference.
                     $sale = Sale::create(array('Created' => date('Y-m-d H:i:s'), 'WorkerId' => $worker->Id, 'Value' => 0, 'Tax' => 0, 'Card' => 0, 'TransactionId' => $transaction->Id, 'BranchId' => $branchId, 'Credit' => 0, 'CreditorId' => 0, 'CreditorType' => 1, 'Cancelled' => 1));
                     $salebreakdown = SaleBreakdown::create(array('SaleId' => $sale->Id, 'Code' => $breakdown->Code, 'Quantity' => -1 * $breakdown->Difference, 'Cost' => $product->AverageCost, 'Price' => 0, 'ExtraData' => json_encode(array('stocktakeBreakdownId' => $breakdown->Id))));
                     $product->Quantity += $breakdown->Difference;
                     $product->save();
                     $breakdown->ExtraData = json_encode(array('salebreakdownId' => $salebreakdown->Id));
                     $breakdown->save();
                 } else {
                     if ($breakdown->Difference < 0) {
                         // Make an empty transaction.
                         $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 10, 'Amount' => 0, 'Reason' => 'Correccion de Inventario.'));
                         // Now make the sale so we can reflect the difference.
                         $sale = Sale::create(array('Created' => date('Y-m-d H:i:s'), 'WorkerId' => $worker->Id, 'Value' => 0, 'Tax' => 0, 'Card' => 0, 'TransactionId' => $transaction->Id, 'BranchId' => $branchId, 'Credit' => 0, 'CreditorId' => 0, 'CreditorType' => 1, 'Cancelled' => 1));
                         $salebreakdown = SaleBreakdown::create(array('SaleId' => $sale->Id, 'Code' => $breakdown->Code, 'Quantity' => -1 * $breakdown->Difference, 'Cost' => $product->AverageCost, 'Price' => 0, 'ExtraData' => json_encode(array('stocktakeBreakdownId' => $breakdown->Id))));
                         $product->Quantity += $breakdown->Difference;
                         $product->save();
                         $breakdown->ExtraData = json_encode(array('salebreakdownId' => $salebreakdown->Id));
                         $breakdown->save();
                     }
                 }
             } else {
                 if ($item['state'] == 3) {
                     // Get the product.
                     $product = Stock::where('Code', '=', $breakdown->Code)->where('BranchId', '=', $branchId)->first();
                     $product->Quantity += $breakdown->Difference;
                     $product->save();
                 }
             }
         }
         // Now update breakdown State.
         $breakdown->State = $item['state'];
         $breakdown->save();
     }
     $response['state'] = 'Success';
     return response()->json($response);
 }
<?php

use App\Contract;
use App\CashboxTransaction;
use App\CashReceipt;
// Get transactions of contract payments.
$transactions = array();
if (isset($contractId) && $contractId != 0) {
    $paymentReceipts = CashReceipt::where('Type', '=', 1)->where('TypeId', '=', $contractId)->get();
    foreach ($paymentReceipts as $paymentReceipt) {
        // Get the transaction.
        $transaction = CashboxTransaction::find($paymentReceipt->TransactionId);
        array_push($transactions, $transaction);
    }
}
?>
@foreach($transactions as $transaction)
	<tr id='transaction-{{ $transaction->Id }}'><td>{{ $transaction->DateTime }}</td><td>Pago a Contrato.</td><td>{{ $transaction->Amount }}</td></tr>
@endforeach
 /**
  * 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);
             }
         }
     }
 }