/**
  * Display a listing of the resource.
  *
  * @return Response
  */
 public function index()
 {
     $exclude = \App\EventCheckin::lists('sale_checkin_id');
     $ticketsales = \App\Sale::where('created_at', '>', \Carbon::parse('1/31/2016'))->whereNotIn('cart_id', $exclude)->with('cartsBySale', 'cartsBySale.product')->get();
     $checkedin = \App\Sale::where('created_at', '>', \Carbon::parse('1/31/2016'))->WhereIn('cart_id', $exclude)->with('cartsBySale', 'cartsBySale.product')->get();
     return view('orders.index', compact('ticketsales', 'checkedin'));
 }
Beispiel #2
0
 public function getPartydue($invoiceId)
 {
     $totalPrice = 0;
     $totalAmount = 0;
     $sale = Sale::where('invoice_id', '=', $invoiceId)->first();
     $saleDetails = SAleDetail::where('invoice_id', '=', $invoiceId)->get();
     $transactions = Transaction::where('invoice_id', '=', $invoiceId)->where('payment_method', '=', 'Check')->where('type', '=', 'Receive')->where('cheque_status', '=', 1)->get();
     foreach ($saleDetails as $saleDetail) {
         $totalPrice = $totalPrice + $saleDetail->price * $saleDetail->quantity;
     }
     $totalPrice -= $sale->discount_percentage;
     foreach ($transactions as $transaction) {
         $totalAmount = $totalAmount + $transaction->amount;
     }
     $transactions2 = Transaction::where('invoice_id', '=', $invoiceId)->where('type', '=', 'Receive')->where('payment_method', '!=', 'Check')->get();
     foreach ($transactions2 as $transaction) {
         $totalAmount = $totalAmount + $transaction->amount;
     }
     $due = $totalPrice - $totalAmount;
     if ($due > 0) {
         return "Due is {$due}";
     } else {
         return 'No due';
     }
 }
Beispiel #3
0
 public function search_return_invoice()
 {
     $invoice_id = Input::get('invoice_id');
     $shop_id = Input::get('shop_id');
     $return_invoice_date = date("Y-m-d", strtotime(Input::get('return_invoice_date')));
     $rules = array('invoice_id' => 'required', 'shop_id' => 'required');
     // Create a new validator instance from our validation rules
     $validator = Validator::make(Input::all(), $rules);
     // If validation fails, we'll exit the operation now.
     if ($validator->fails()) {
         return Redirect::back()->withInput()->withErrors($validator);
     }
     $data = new Sale();
     $data->invoice_id = $invoice_id;
     $matchThese = ['invoice_id' => $invoice_id, 'created_at' => $return_invoice_date, 'shop_id' => $shop_id];
     Sale::where($matchThese)->update(['invoice_id' => $data->invoice_id, 'return_id' => 1]);
     Session::flash('message', 'Invoice has been successful returned!');
     return redirect()->route("return_invoice");
 }
Beispiel #4
0
 /**
  * Function that generates order.
  *
  * @return Response
  */
 public function aiOrder()
 {
     // Get all branches.
     $branches = Branch::all();
     // Get all providers.
     $providers = Provider::where('AIManaged', '=', true)->get();
     // Prepare order array.
     $order = array();
     // Loop through providers.
     foreach ($providers as $provider) {
         $order[$provider->Id] = array();
         // Get all products.
         $products = Stock::where('Provider', '=', $provider)->get();
         foreach ($products as $product) {
             $order[$provider->Id][$product->Code][$provider->BranchId] = array('Code' => $product->Code, 'Description' => $product->Description, 'Exist' => $product->Quantity, 'Cost' => $product->Cost, 'Minimum' => $product->Minimum, 'Order' => 0, 'Average' => 0, 'Sold' => 0);
         }
         // Get all the products sold in selected sample range.
         $today = date('Y-m-d H:i:s');
         switch ($provider->SampleRange) {
             case '1week':
                 $startDate = date('Y-m-d H:i:s', strtotime($today) - 604800);
                 $sales = Sale::where('BranchId', '=', $branchId)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get();
                 foreach ($sales as $sale) {
                     $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
                     foreach ($breakdown as $item) {
                         if (array_key_exists($item->Code, $order)) {
                             $order[$item->Code]['Sold'] += $item->Quantity;
                         }
                     }
                 }
                 // Now calculate average of each product.
                 foreach ($order as $index => $product) {
                     $order[$index]['Average'] = $product['Sold'] / 7;
                 }
                 break;
             case '2week':
                 $startDate = date('Y-m-d H:i:s', strtotime($today) - 1209600);
                 $sales = Sale::where('BranchId', '=', $branchId)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get();
                 foreach ($sales as $sale) {
                     $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
                     foreach ($breakdown as $item) {
                         if (array_key_exists($item->Code, $order)) {
                             $order[$item->Code]['Sold'] += $item->Quantity;
                         }
                     }
                 }
                 // Now calculate average of each product.
                 foreach ($order as $index => $product) {
                     $order[$index]['Average'] = $product['Sold'] / 14;
                 }
                 break;
             case '1month':
                 $startDate = date('Y-m-d H:i:s', strtotime($today) - 2419200);
                 $sales = Sale::where('BranchId', '=', $branchId)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get();
                 foreach ($sales as $sale) {
                     $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
                     foreach ($breakdown as $item) {
                         if (array_key_exists($item->Code, $order)) {
                             $order[$item->Code]['Sold'] += $item->Quantity;
                         }
                     }
                 }
                 // Now calculate average of each product.
                 foreach ($order as $index => $product) {
                     $order[$index]['Average'] = $product['Sold'] / 30;
                 }
                 break;
             case '3month':
                 $startDate = date('Y-m-d H:i:s', strtotime($today) - 7257600);
                 $sales = Sale::where('BranchId', '=', $branchId)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get();
                 foreach ($sales as $sale) {
                     $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
                     foreach ($breakdown as $item) {
                         if (array_key_exists($item->Code, $order)) {
                             $order[$item->Code]['Sold'] += $item->Quantity;
                         }
                     }
                 }
                 // Now calculate average of each product.
                 foreach ($order as $index => $product) {
                     $order[$index]['Average'] = $product['Sold'] / 90;
                 }
                 break;
             case '1year':
                 $startDate = date('Y-m-d H:i:s', strtotime($today) - 29030400);
                 $sales = Sale::where('BranchId', '=', $branchId)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get();
                 foreach ($sales as $sale) {
                     $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
                     foreach ($breakdown as $item) {
                         if (array_key_exists($item->Code, $order)) {
                             $order[$item->Code]['Sold'] += $item->Quantity;
                         }
                     }
                 }
                 // Now calculate average of each product.
                 foreach ($order as $index => $product) {
                     $order[$index]['Average'] = $product['Sold'] / 365;
                 }
                 break;
         }
     }
     // Now calculate amount to order based on average, existence, minimum and order range.
     switch (Input::get('orderRange')) {
         case '3day':
             foreach ($order as $index => $product) {
                 $estimatedOrder = $product['Average'] * 3;
                 // Order should be at least twice minimum required with existence influded.
                 if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) {
                     $estimatedOrder = $product['Minimum'] * 2;
                 }
                 $order[$index]['Order'] = round($estimatedOrder);
             }
             break;
         case '1week':
             foreach ($order as $index => $product) {
                 $estimatedOrder = $product['Average'] * 7;
                 // Order should be at least twice minimum required with existence influded.
                 if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) {
                     $estimatedOrder = $product['Minimum'] * 2;
                 }
                 $order[$index]['Order'] = round($estimatedOrder);
             }
             break;
         case '2week':
             foreach ($order as $index => $product) {
                 $estimatedOrder = $product['Average'] * 14;
                 // Order should be at least twice minimum required with existence influded.
                 if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) {
                     $estimatedOrder = $product['Minimum'] * 2;
                 }
                 $order[$index]['Order'] = round($estimatedOrder);
             }
             break;
         case '1month':
             foreach ($order as $index => $product) {
                 $estimatedOrder = $product['Average'] * 30;
                 // Order should be at least twice minimum required with existence influded.
                 if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) {
                     $estimatedOrder = $product['Minimum'] * 2;
                 }
                 $order[$index]['Order'] = round($estimatedOrder);
             }
             break;
         case '3month':
             foreach ($order as $index => $product) {
                 $estimatedOrder = $product['Average'] * 90;
                 // Order should be at least twice minimum required with existence influded.
                 if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) {
                     $estimatedOrder = $product['Minimum'] * 2;
                 }
                 $order[$index]['Order'] = round($estimatedOrder);
             }
             break;
     }
     // Check if we have recently made an order for this provider to fix order.
     $aiOrders = AIOrder::where('GenerationDate', '>', date('Y-m-d H:i:s', strtotime($today) - 259200))->where('Received', '=', false)->get();
     foreach ($aiOrders as $o) {
         // Get breakdown and remove quantity from order.
         $breakdown = AIOrderBreakdown::where('AIOrderId', '=', $o->Id)->get();
         foreach ($breakdown as $item) {
             if (array_key_exists($item->Code, $order)) {
                 $order[$item->Code]['Order'] -= $item->Quantity;
             }
         }
     }
     $order = AIOrder::findOrFail(1);
     $breakdown = AIOrderBreakdown::where('AIOrderId', '=', $order->Id)->get();
     // Ship order...
     Mail::send('emails.ai.makeOrder', ['order' => $order, 'breakdown' => $breakdown], function ($message) {
         $message->to('*****@*****.**');
         $message->subject('Orden de Compra');
     });
     $response['state'] = 'Success';
     $response['message'] = 'Servicio eliminado exitosamente!';
     return response()->json($response);
 }
Beispiel #5
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     // Let's get all credit sales that have not been paid yet.
     $creditSales = Sale::where('Credit', '=', true)->where('Cancelled', '=', false)->get();
     // Check if any of them are due soon.
     $today = date('Y-m-d H:i:s');
     foreach ($creditSales as $sale) {
         // Get the client or institution that made the credit purchase.
         $creditor = null;
         if ($sale->CreditorType == 1) {
             $creditor = Client::find($sale->CreditorId);
         } else {
             $creditor = Institution::find($sale->CreditorId);
         }
         // First check if the payment is late.
         if (date('Y-m-d H:i:s', strtotime($sale->Created) + $creditor->CreditDays * 86400) < $today) {
             // If it's past due for more than a month notify admins so they can deal with it.
             if (date('Y-m-d H:i:s', strtotime($sale->Created) + ($creditor->CreditDays + 30) * 86400) < $today) {
                 // 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 ha tratado de cobrar la venta de credito con factura: ' . $sale->Id . ', sin embargo no se ha registrado el pago de la factura y esta tiene mas de un mes de vencimiento. Aergia no seguira tratando de cobrar esta factura, por favor darle seguimiento al caso.', 'Url' => '/creditdue/' . $sale->Id, 'Seen' => false));
                 }
             } else {
                 // Check to see if there is a transport request active to collect payment.
                 $transport = Transport::where('Type', '=', 7)->where('ReasonId', '=', $sale->Id)->where('Date', '>', date('Y-m-d'))->get();
                 if (count($transport) == 0) {
                     // Get a vehicle that can be used to go to charge creditor.
                     $vehicles = Vehicle::where('BranchId', '=', $sale->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 to go charge creditor 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 de la factura: ' . $sale->Id . ' ya que no tuvo vehiculos disponibles para hacerlo. Por favor organizar el cobro de la factura.', 'Url' => '/creditdue/' . $sale->Id, 'Seen' => false));
                         }
                     } else {
                         // Get location of creditor.
                         $location = Location::find($creditor->LocationId);
                         $paymentCollection = Transport::create(array('Date' => date('Y-m-d', strtotime("+1 day")), 'Time' => '00:00:00', 'VehicleId' => $vehicle->Id, 'DriverId' => 0, 'StartLatitude' => 0, 'StartLongitude' => 0, 'Journey' => '[]', 'EndLatitude' => $location->Latitude, 'EndLongitude' => $location->Longitude, 'EndAddress' => $creditor->Address, 'Distance' => 0, 'ReasonId' => $sale->Id, 'Type' => 7, 'State' => 2, 'Order' => 0, 'Depreciation' => 0));
                         // Inform creditor of when you shall collect payment.
                         if ($creditor->Email != '') {
                             Mail::send('emails.ai.creditorReminder', ['sale' => $sale, 'creditor' => $creditor, 'transport' => $paymentCollection], function ($message) use($sale, $creditor) {
                                 $message->to($creditor->Email);
                                 $message->subject('Cobro Factura: ' . $sale->Id);
                             });
                         }
                     }
                 }
             }
         }
     }
 }
Beispiel #6
0
                                    DV-{{$transaction->id}}
                                @endif
                            </td></tr>
                        <tr><td>Recieved by: {{$transaction->user->name}}</td></tr>
                    </table>
                </td>
            </tr>
        </table>


        <table class="col-md-12"  style="width: 100%;" >
            <tr style="border:1px solid black; background: url('../../assets/img/lightBlueBackground.jpg');">
                <td colspan="2">Received from:
                    @if($transaction->type == "Receive")
                        <?php 
$sales = \App\Sale::where('invoice_id', '=', $transaction->invoice_id)->first();
?>
                        {{$sales->party->name}}
                    @elseif($transaction->type == "Payment")
                        <?php 
$sales = \App\PurchaseInvoice::where('invoice_id', '=', $transaction->invoice_id)->first();
?>
                        {{$sales->party->name}}
                    @endif
                </td>
                <td style="border:1px solid black;" class="text-center">
                    Amount
                </td>
            </tr>
            <tr style="border:1px solid black;">
                <td colspan="2">
function transactionType($transaction)
{
    switch ($transaction->Type) {
        case 1:
            // Check if a credit card was used for sale.
            if (Sale::where('TransactionId', '=', $transaction->Id)->first()->Card) {
                return 'Venta con Tarjeta';
            } else {
                return $transaction->Reason;
            }
            break;
        case 2:
            return $transaction->Reason;
            break;
        case 3:
            return $transaction->Reason;
            break;
        case 4:
            return 'Otros Gastos';
            break;
        case 5:
            return 'Retiro de Caja';
            break;
        case 6:
            return 'Reembolso de Caja';
            break;
        case 7:
            return 'Pago de Contrato';
            break;
        case 8:
            return 'Pago de Credito';
            break;
        case 9:
            return $transaction->Reason;
            break;
        case 10:
            return $transaction->Reason;
            break;
    }
}
Beispiel #8
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     // Get providers.
     $providers = Provider::all();
     // Get the branches.
     $branches = Branch::all();
     // Loop through them and check which ones are set to auto order.
     foreach ($providers as $provider) {
         if ($provider->AIManaged) {
             foreach ($branches as $branch) {
                 // Now let's get all the products for this provider.
                 $products = Stock::where('BranchId', '=', $branch->Id)->where('ProviderId', '=', $provider->Id)->get();
                 $order = array();
                 foreach ($products as $product) {
                     if ($product->Quantity <= $product->Minimum) {
                         $order[$product->Code] = array('Code' => $product->Code, 'Description' => $product->Description, 'Exist' => $product->Quantity, 'Cost' => $product->Cost, 'Minimum' => $product->Minimum, 'Order' => 0, 'Average' => 0, 'Sold' => 0);
                     }
                 }
                 // Get all the products sold in selected sample range.
                 $today = date('Y-m-d H:i:s');
                 switch ($provider->SampleRange) {
                     case '1week':
                         $startDate = date('Y-m-d H:i:s', strtotime($today) - 604800);
                         $sales = Sale::where('BranchId', '=', $branch->Id)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get();
                         foreach ($sales as $sale) {
                             $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
                             foreach ($breakdown as $item) {
                                 if (array_key_exists($item->Code, $order)) {
                                     $order[$item->Code]['Sold'] += $item->Quantity;
                                 }
                             }
                         }
                         // Now calculate average of each product.
                         foreach ($order as $index => $product) {
                             $order[$index]['Average'] = $product['Sold'] / 7;
                         }
                         break;
                     case '2week':
                         $startDate = date('Y-m-d H:i:s', strtotime($today) - 1209600);
                         $sales = Sale::where('BranchId', '=', $branch->Id)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get();
                         foreach ($sales as $sale) {
                             $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
                             foreach ($breakdown as $item) {
                                 if (array_key_exists($item->Code, $order)) {
                                     $order[$item->Code]['Sold'] += $item->Quantity;
                                 }
                             }
                         }
                         // Now calculate average of each product.
                         foreach ($order as $index => $product) {
                             $order[$index]['Average'] = $product['Sold'] / 14;
                         }
                         break;
                     case '1month':
                         $startDate = date('Y-m-d H:i:s', strtotime($today) - 2419200);
                         $sales = Sale::where('BranchId', '=', $branch->Id)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get();
                         foreach ($sales as $sale) {
                             $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
                             foreach ($breakdown as $item) {
                                 if (array_key_exists($item->Code, $order)) {
                                     $order[$item->Code]['Sold'] += $item->Quantity;
                                 }
                             }
                         }
                         // Now calculate average of each product.
                         foreach ($order as $index => $product) {
                             $order[$index]['Average'] = $product['Sold'] / 30;
                         }
                         break;
                     case '3month':
                         $startDate = date('Y-m-d H:i:s', strtotime($today) - 7257600);
                         $sales = Sale::where('BranchId', '=', $branch->Id)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get();
                         foreach ($sales as $sale) {
                             $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
                             foreach ($breakdown as $item) {
                                 if (array_key_exists($item->Code, $order)) {
                                     $order[$item->Code]['Sold'] += $item->Quantity;
                                 }
                             }
                         }
                         // Now calculate average of each product.
                         foreach ($order as $index => $product) {
                             $order[$index]['Average'] = $product['Sold'] / 90;
                         }
                         break;
                     case '1year':
                         $startDate = date('Y-m-d H:i:s', strtotime($today) - 29030400);
                         $sales = Sale::where('BranchId', '=', $branch->Id)->where('Created', '>=', $startDate)->where('Created', '<=', $today)->get();
                         foreach ($sales as $sale) {
                             $breakdown = SaleBreakdown::where('SaleId', '=', $sale->Id)->get();
                             foreach ($breakdown as $item) {
                                 if (array_key_exists($item->Code, $order)) {
                                     $order[$item->Code]['Sold'] += $item->Quantity;
                                 }
                             }
                         }
                         // Now calculate average of each product.
                         foreach ($order as $index => $product) {
                             $order[$index]['Average'] = $product['Sold'] / 365;
                         }
                         break;
                 }
                 // Now calculate amount to order based on average, existence, minimum and order range.
                 switch ($provider->OrderRange) {
                     case '3day':
                         foreach ($order as $index => $product) {
                             $estimatedOrder = $product['Average'] * 3;
                             // Order should be at least twice minimum required with existence influded.
                             if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) {
                                 $estimatedOrder = $product['Minimum'] * 2;
                             }
                             $order[$index]['Order'] = ceil($estimatedOrder);
                         }
                         break;
                     case '1week':
                         foreach ($order as $index => $product) {
                             $estimatedOrder = $product['Average'] * 7;
                             // Order should be at least twice minimum required with existence influded.
                             if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) {
                                 $estimatedOrder = $product['Minimum'] * 2;
                             }
                             $order[$index]['Order'] = ceil($estimatedOrder);
                         }
                         break;
                     case '2week':
                         foreach ($order as $index => $product) {
                             $estimatedOrder = $product['Average'] * 14;
                             // Order should be at least twice minimum required with existence influded.
                             if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) {
                                 $estimatedOrder = $product['Minimum'] * 2;
                             }
                             $order[$index]['Order'] = ceil($estimatedOrder);
                         }
                         break;
                     case '1month':
                         foreach ($order as $index => $product) {
                             $estimatedOrder = $product['Average'] * 30;
                             // Order should be at least twice minimum required with existence influded.
                             if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) {
                                 $estimatedOrder = $product['Minimum'] * 2;
                             }
                             $order[$index]['Order'] = ceil($estimatedOrder);
                         }
                         break;
                     case '3month':
                         foreach ($order as $index => $product) {
                             $estimatedOrder = $product['Average'] * 90;
                             // Order should be at least twice minimum required with existence influded.
                             if ($estimatedOrder + $product['Exist'] < $product['Minimum'] * 2) {
                                 $estimatedOrder = $product['Minimum'] * 2;
                             }
                             $order[$index]['Order'] = ceil($estimatedOrder);
                         }
                         break;
                 }
                 // Check if we have recently made an order for this provider to fix order.
                 $aiOrders = AIOrder::where('GenerationDate', '>', date('Y-m-d H:i:s', strtotime($today) - 259200))->where('Received', '=', false)->where('BranchId', '=', $branch->Id)->get();
                 foreach ($aiOrders as $o) {
                     // Get breakdown and remove quantity from order.
                     $breakdown = AIOrderBreakdown::where('AIOrderId', '=', $o->Id)->get();
                     foreach ($breakdown as $item) {
                         if (array_key_exists($item->Code, $order)) {
                             $order[$item->Code]['Order'] -= $item->Quantity;
                         }
                     }
                 }
                 // Check if we have anything to order.
                 $sendOrder = false;
                 foreach ($order as $item) {
                     if ($item['Order'] > 0) {
                         $sendOrder = true;
                     }
                 }
                 if (!$sendOrder) {
                     return 1;
                 }
                 // Generate Order.
                 $aiOrder = AIOrder::create(array('GenerationDate' => date('Y-m-d H:i:s'), 'ConfirmationDate' => '0000-00-00 00:00:00', 'ProviderId' => $provider->Id, 'BranchId' => $branch->Id, 'Received' => false, 'EstimatedDelivery' => date('Y-m-d', strtotime("+3 days"))));
                 foreach ($order as $item) {
                     AIOrderBreakdown::create(array('AIOrderId' => $aiOrder->Id, 'Code' => $item['Code'], 'Quantity' => $item['Order']));
                 }
                 $breakdown = AIOrderBreakdown::where('AIOrderId', '=', $aiOrder->Id)->get();
                 // Now if the provider has delivery send email with order.
                 if ($provider->Delivery) {
                     // Now check what method we will use to make order.
                     if ($provider->Method == 'email') {
                         try {
                             Mail::send('emails.ai.makeOrder', ['order' => $aiOrder, 'breakdown' => $breakdown], function ($message) use($provider, $aiOrder) {
                                 $message->to($provider->Email);
                                 $message->subject('Orden de Compra: ' . $aiOrder->Id);
                             });
                         } catch (\Exception $e) {
                             // In this case we should let an administrator know that the email order failed.
                             $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 un pedido via correo para ' . $provider->Name . '. Por favor revisar orden y organizar su compra.', 'Url' => '/ai/order/' . $aiOrder->Id, 'Seen' => false));
                             }
                         }
                     } else {
                         if ($provider->Method == 'ai') {
                             // TODO: Establish Contact via AI.
                         }
                     }
                 } else {
                     // If the provider doesn't have delivery program a trip to make purchase.
                     $vehicles = Vehicle::where('BranchId', '=', $branch->Id)->where('Repair', '=', false)->get();
                     $vehicle = null;
                     foreach ($vehicles as $v) {
                         if (!$vehicle) {
                             $vehicle = $v;
                         }
                         // In this case the bigger 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 un pedido a para ' . $provider->Name . '. Por favor revisar orden y organizar su compra.', 'Url' => '/ai/order/' . $aiOrder->Id, 'Seen' => false));
                         }
                     } else {
                         // Get location of provider.
                         $location = Location::find($provider->LocationId);
                         $transport = Transport::create(array('Date' => date('Y-m-d', strtotime("+1 day")), 'Time' => '00:00:00', 'VehicleId' => $vehicle->Id, 'DriverId' => 0, 'StartLatitude' => 0, 'StartLongitude' => 0, 'Journey' => '[]', 'EndLatitude' => $location->Latitude, 'EndLongitude' => $location->Longitude, 'EndAddress' => $provider->Address, 'Distance' => 0, 'ReasonId' => $aiOrder->Id, 'Type' => 9, 'State' => 2, 'Order' => 0, 'Depreciation' => 0));
                         // Update Estimated Delivery Date.
                         $aiOrder->EstimatedDelivery = date('Y-m-d', strtotime("+1 day"));
                         $aiOrder->save();
                     }
                 }
             }
         }
     }
 }
Beispiel #9
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     // Get all workers that haven't been fired.
     $workers = Worker::where('Fired', '=', false)->get();
     foreach ($workers as $worker) {
         // First let's check if it has a long term loan active.
         $currentMonth = date('Y-m');
         if ($worker->Loan > 0) {
             // Let's check if we have gotten this months loan payment.
             $loans = WorkerLoan::where('WorkerId', '=', $worker->Id)->where('Date', '>', $currentMonth . '-01')->where('Type', '=', 2)->get();
             if (count($loans) == 0) {
                 // Charge worker for loan.
                 $charge = $worker->Loan / $worker->Months;
                 $loan = WorkerLoan::create(array('Date' => date('Y-m-d'), 'Amount' => $charge, 'Processed' => false, 'State' => 2, 'Type' => 2, 'WorkerId' => $worker->Id));
                 $worker->Loan -= $charge;
                 $worker->Months--;
                 $worker->save();
             }
         }
         // Now let's check if we have gotten this month's insurance fee.
         $loans = WorkerLoan::where('WorkerId', '=', $worker->Id)->where('Date', '>', $currentMonth . '-01')->where('Type', '=', 3)->get();
         if (count($loans) == 0) {
             // Charge worker for loan.
             $charge = $worker->Insurance - $worker->Patron;
             if ($charge > 0) {
                 $loan = WorkerLoan::create(array('Date' => date('Y-m-d'), 'Amount' => $charge, 'Processed' => false, 'State' => 2, 'Type' => 3, 'WorkerId' => $worker->Id));
             }
         }
         // Get workers days.
         $days = WorkerSalary::where('SystemProcess', '=', false)->where('WorkerId', '=', $worker->Id)->get();
         // Now let's check if we need to add a bonus to the worker.
         if ($worker->BonusPercentage > 0) {
             switch ($worker->BonusSource) {
                 case 'production':
                     foreach ($days as $day) {
                         if ($day->DayType != 3 && ($day->DayType < 5 || $day->DayType == 7)) {
                             // If worker is on general production then let's get what was produced and the price of what was produced.
                             $produced = ProductionStage::where('Date', '>', $day->Date . ' 00:00:01')->get();
                             $totalProduced = 0;
                             $pIds = array();
                             foreach ($produced as $p) {
                                 // Check if we have already checked this product.
                                 if (!in_array($p->ProductionId, $pIds)) {
                                     array_push($pIds, $p->ProductionId);
                                     // Check if product is finished.
                                     $product = Production::find($p->ProductionId);
                                     if ($product->Stage == $product->maxStage()) {
                                         $finalProduct = Stock::where('Code', '=', $product->Code)->where('BranchId', '=', $product->BranchId)->first();
                                         $totalProduced += $finalProduct->Price;
                                     }
                                 }
                             }
                             $day->Bonus += $totalProduced * ($worker->BonusPercentage / 100);
                         }
                         // Add insurance Patron Value for the day.
                         // TODO: I should check how many days are in this month,
                         $day->Insurance = $worker->Patron / 30;
                         $day->save();
                     }
                     break;
                 case 'productionsingle':
                     foreach ($days as $day) {
                         if ($day->DayType != 3 && ($day->DayType < 5 || $day->DayType == 7)) {
                             // If worker is on single production then let's get what he produced and the price of what was produced.
                             $produced = ProductionStage::where('Date', '>', $day->Date . ' 00:00:01')->where('WorkerId', '=', $worker->Id)->get();
                             $totalProduced = 0;
                             $pIds = array();
                             foreach ($produced as $p) {
                                 // Check if we have already checked this product.
                                 if (!in_array($p->ProductionId, $pIds)) {
                                     array_push($pIds, $p->ProductionId);
                                     // Check if product is finished.
                                     $product = Production::find($p->ProductionId);
                                     if ($product->Stage == $product->maxStage()) {
                                         $finalProduct = Stock::where('Code', '=', $product->Code)->where('BranchId', '=', $product->BranchId)->first();
                                         $totalProduced += $finalProduct->Price;
                                     }
                                 }
                             }
                             $day->Bonus += $totalProduced * ($worker->BonusPercentage / 100);
                         }
                         // Add insurance Patron Value for the day.
                         // TODO: I should check how many days are in this month,
                         $day->Insurance = $worker->Patron / 30;
                         $day->save();
                     }
                     break;
                 case 'sales':
                     foreach ($days as $day) {
                         if ($day->DayType != 3 && ($day->DayType < 5 || $day->DayType == 7)) {
                             // If worker is on general sales then let's get all sales.
                             $sales = Sale::where('Created', '>=', $day->Date . ' 00:00:01')->where('Created', '<=', $day->Date . ' 23:59:59')->where('BranchId', '=', $worker->BranchId)->get();
                             $totalSales = 0;
                             foreach ($sales as $sale) {
                                 $totalSales += $sale->Value;
                             }
                             $day->Bonus += $totalSales * ($worker->BonusPercentage / 100);
                         }
                         // Add insurance Patron Value for the day.
                         // TODO: I should check how many days are in this month,
                         $day->Insurance = $worker->Patron / 30;
                         $day->save();
                     }
                     break;
                 case 'salessingle':
                     foreach ($days as $day) {
                         if ($day->DayType != 3 && ($day->DayType < 5 || $day->DayType == 7)) {
                             // If worker is on general sales then let's get all sales.
                             $sales = Sale::where('Created', '>=', $day->Date . ' 00:00:01')->where('Created', '<=', $day->Date . ' 23:59:59')->where('WorkerId', '=', $worker->Id)->get();
                             $totalSales = 0;
                             foreach ($sales as $sale) {
                                 $totalSales += $sale->Value;
                             }
                             $day->Bonus += $totalSales * ($worker->BonusPercentage / 100);
                         }
                         // Add insurance Patron Value for the day.
                         // TODO: I should check how many days are in this month,
                         $day->Insurance = $worker->Patron / 30;
                         $day->save();
                     }
                     break;
             }
         }
     }
     // Get all days that have not been processed and set them as being processed.
     $allDays = WorkerSalary::where('SystemProcess', '=', false)->get();
     foreach ($allDays as $day) {
         $day->SystemProcess = true;
         $day->save();
     }
 }
 /**
  * Function that gets the institution's credit information.
  *
  * @return Response
  */
 public function institutionCredit()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('institution' => '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 institution.
     $institution = Institution::where('Id', '=', Input::get('institution'))->first();
     // Now get institution's unpaid bills.
     $pendingBills = Sale::where('CreditorId', '=', $institution->Id)->where('CreditorType', '=', 0)->where('Credit', '=', true)->where('Cancelled', '=', false)->get();
     // Get any payments to the unpaid bills.
     $creditInfo = array();
     $totalDebt = 0;
     foreach ($pendingBills as $pendingBill) {
         $created = $pendingBill->Created;
         $today = date('Y-m-d');
         $diff = abs(strtotime($today) - strtotime($created));
         $days = floor($diff / (60 * 60 * 24));
         $total = $pendingBill->Value + $pendingBill->Tax;
         $state = $days > $institution->CreditDays ? 'Atrasado' : 'Pendiente';
         $pending = $total;
         $payments = CashReceipt::where('Type', '=', 2)->where('TypeId', '=', $pendingBill->Id)->get();
         foreach ($payments as $payment) {
             $pending -= $payment->Value;
         }
         $totalDebt += $pending;
         array_push($creditInfo, array('Id' => $pendingBill->Id, 'Total' => $total, 'Pending' => $pending, 'State' => $state));
     }
     $response['state'] = 'Success';
     $response['institution'] = $institution;
     $response['totalDebt'] = $totalDebt;
     $response['pending'] = $creditInfo;
     return response()->json($response);
 }
 public function postSaveSalesReturn()
 {
     $ruless = array('party_id' => 'required', 'cus_ref_no' => 'required', 'branch_id' => 'required', 'product_type' => 'required', 'product_id' => 'required', 'quantity' => 'required', 'return_amount' => 'required', 'consignment_name' => 'required');
     $validate = Validator::make(Input::all(), $ruless);
     if ($validate->fails()) {
         return Redirect::to('salesreturn/create')->withErrors($validate);
     } else {
         $salesreturn = new SalesReturn();
         $this->setSalesReturnData($salesreturn);
         //automatically reduce sales payment starts
         $return_amount = Input::get('return_amount');
         $remaining_amount = $return_amount;
         //var_dump($remaining_amount);
         $partyId = Input::get('party_id');
         if ($remaining_amount > 0) {
             $invoiceId = Sale::where('party_id', '=', $partyId)->get();
             foreach ($invoiceId as $invid) {
                 $price = SAleDetail::where('invoice_id', '=', $invid->invoice_id)->get();
                 $detailsPrice = 0;
                 foreach ($price as $prc) {
                     $detailsPrice = $detailsPrice + $prc->price * $prc->quantity;
                 }
                 var_dump($detailsPrice);
                 $amount = Transaction::where('invoice_id', '=', $invid->invoice_id)->where('type', '=', 'Receive')->get();
                 $paid = 0;
                 foreach ($amount as $amnt) {
                     $paid = $paid + $amnt->amount;
                 }
                 $difference = $detailsPrice - $paid;
                 if ($difference > 0) {
                     echo 'greater than 0 difference';
                     if ($remaining_amount <= $difference) {
                         $transaction = new Transaction();
                         $transaction->invoice_id = $invid->invoice_id;
                         $transaction->amount = $remaining_amount;
                         $transaction->type = 'Receive';
                         $transaction->payment_method = 'Sales Return';
                         $transaction->account_category_id = 7;
                         $transaction->remarks = 'Sales Return';
                         $transaction->account_name_id = 8;
                         $transaction->user_id = Session::get('user_id');
                         $transaction->cheque_no = '';
                         $branch = SAleDetail::where('invoice_id', '=', $invid->invoice_id)->first();
                         $transaction->branch_id = $branch->branch_id;
                         $transaction->save();
                         $remaining_amount = 0;
                     } elseif ($remaining_amount > $difference) {
                         $toBePaid = $remaining_amount - $difference;
                         $transaction = new Transaction();
                         $transaction->invoice_id = $invid->invoice_id;
                         $transaction->amount = $difference;
                         $transaction->type = 'Receive';
                         $transaction->payment_method = 'Sales Return';
                         $transaction->account_category_id = 7;
                         $transaction->remarks = 'Sales Return';
                         $transaction->account_name_id = 8;
                         $transaction->user_id = Session::get('user_id');
                         $transaction->cheque_no = '';
                         $branch = SAleDetail::where('invoice_id', '=', $invid->invoice_id)->first();
                         $transaction->branch_id = $branch->branch_id;
                         $transaction->save();
                         $remaining_amount = $toBePaid;
                     }
                 }
             }
         }
         /*if($remaining_amount>0)
           {
               echo "How come its possible! Consult with DEVELOPERS!!!";
           }*/
         //automatically reduce sales payment ends
         return Redirect::to('salesreturn/create');
     }
 }
<?php

use App\Sale;
use App\CashReceipt;
use App\Client;
use App\Institution;
// Get all the outstanding credit bills.
$lateBills = array();
$outstandingBills = Sale::where('Credit', '=', 1)->where('Cancelled', '=', false)->get();
foreach ($outstandingBills as $bill) {
    // Get amount of days passed.
    $created = $bill->Created;
    $today = date('Y-m-d');
    $diff = abs(strtotime($today) - strtotime($created));
    $days = floor($diff / (60 * 60 * 24));
    // Check if it is late.
    if ($bill->CreditorType == 1) {
        // Get the client.
        $client = Client::find($bill->CreditorId);
        if ($days > $client->CreditDays) {
            // Get any payments made to it.
            $paid = 0;
            $payments = CashReceipt::where('Type', '=', 2)->where('TypeId', '=', $bill->Id)->get();
            foreach ($payments as $payment) {
                $paid += $payment->Value;
            }
            $total = $bill->Value + $bill->Tax;
            $pending = $total - $paid;
            array_push($lateBills, array('Id' => $bill->Id, 'Total' => $total, 'Pending' => $pending, 'State' => 'Atrasado'));
        }
    } else {
Beispiel #13
0
 public function postSaveReceiveAll()
 {
     $transactionId = 0;
     $ruless = array('party_id' => 'required', 'branch_id' => 'required', 'account_category_id' => 'required', 'account_name_id' => 'required', 'payment_method' => 'required', 'amount' => 'required');
     $validate = Validator::make(Input::all(), $ruless);
     if ($validate->fails()) {
         return Redirect::to('sales/index/')->withErrors($validate);
     } else {
         //$this->setReceiveSalePaymentAll();
         //return Redirect::to('sales/index');
         //$salesreturn = new SalesReturn();
         //$this->setSalesReturnData($salesreturn);
         //automatically reduce sales payment starts
         $return_amount = Input::get('amount');
         $remaining_amount = $return_amount;
         //var_dump($remaining_amount);
         $partyId = Input::get('party_id');
         if ($remaining_amount > 0) {
             $invoiceId = Sale::where('party_id', '=', $partyId)->where('is_sale', '=', 1)->get();
             foreach ($invoiceId as $invid) {
                 $detailsPrice = 0;
                 $paid = 0;
                 $saleDetails = SAleDetail::where('invoice_id', '=', $invid->invoice_id)->get();
                 $transactions = Transaction::where('invoice_id', '=', $invid->invoice_id)->where('payment_method', '=', 'Check')->where('type', '=', 'Receive')->where('cheque_status', '=', 1)->get();
                 $salef = Sale::find($invid->id);
                 foreach ($saleDetails as $saleDetail) {
                     $salePriceCalculated = $saleDetail->price * $saleDetail->quantity;
                     $detailsPrice = $detailsPrice + $salePriceCalculated;
                 }
                 $detailsPrice -= $invid->discount_percentage;
                 foreach ($transactions as $transaction) {
                     $paid = $paid + $transaction->amount;
                 }
                 $transactions2 = Transaction::where('invoice_id', '=', $invid->invoice_id)->where('type', '=', 'Receive')->where('payment_method', '!=', 'Check')->get();
                 foreach ($transactions2 as $transaction) {
                     $paid = $paid + $transaction->amount;
                 }
                 $difference = $detailsPrice - $paid;
                 //echo $difference; die();
                 if ($difference > 0) {
                     //echo 'greater than 0 difference';
                     if ($remaining_amount <= $difference) {
                         if ($remaining_amount > 0) {
                             $sale = Sale::find($invid->id);
                             if ($remaining_amount < $difference) {
                                 $sale->status = "Partial";
                             } elseif ($remaining_amount == $difference) {
                                 $sale->status = "Completed";
                             }
                             $transaction = new Transaction();
                             $transaction->invoice_id = $invid->invoice_id;
                             $transaction->amount = $remaining_amount;
                             $transaction->type = 'Receive';
                             $transaction->payment_method = Input::get('payment_method');
                             $transaction->account_category_id = Input::get('account_category_id');
                             $transaction->remarks = Input::get('remarks');
                             $transaction->account_name_id = Input::get('account_name_id');
                             $transaction->user_id = Session::get('user_id');
                             $transaction->cheque_no = Input::get('cheque_no');
                             $branch = SAleDetail::where('invoice_id', '=', $invid->invoice_id)->first();
                             $transaction->branch_id = $branch->branch_id;
                             $transaction->cheque_date = Input::get('cheque_date');
                             $transaction->cheque_bank = Input::get('cheque_bank');
                             if ($transaction->payment_method != "Check") {
                                 $accountPayment = NameOfAccount::find(Input::get('account_name_id'));
                                 $accountPayment->opening_balance = $accountPayment->opening_balance + $remaining_amount;
                                 $accountPayment->save();
                             }
                             $transaction->save();
                             $transactionId = $transaction->id;
                             $remaining_amount = 0;
                         }
                     } elseif ($remaining_amount > $difference) {
                         if ($remaining_amount > 0) {
                             $sale = Sale::find($invid->id);
                             $sale->status = "Completed";
                             $toBePaid = $remaining_amount - $difference;
                             $transaction = new Transaction();
                             $transaction->invoice_id = $invid->invoice_id;
                             $transaction->amount = $difference;
                             $transaction->type = 'Receive';
                             $transaction->payment_method = Input::get('payment_method');
                             $transaction->account_category_id = Input::get('account_category_id');
                             $transaction->remarks = Input::get('remarks');
                             $transaction->account_name_id = Input::get('account_name_id');
                             $transaction->user_id = Session::get('user_id');
                             $transaction->cheque_no = Input::get('cheque_no');
                             $branch = SAleDetail::where('invoice_id', '=', $invid->invoice_id)->first();
                             $transaction->branch_id = $branch->branch_id;
                             $transaction->cheque_date = Input::get('cheque_date');
                             $transaction->cheque_bank = Input::get('cheque_bank');
                             if ($transaction->payment_method != "Check") {
                                 $accountPayment = NameOfAccount::find(Input::get('account_name_id'));
                                 $accountPayment->opening_balance = $accountPayment->opening_balance + $difference;
                                 $accountPayment->save();
                             }
                             $transaction->save();
                             $transactionId = $transaction->id;
                             $remaining_amount = $toBePaid;
                         }
                     }
                     $sale->save();
                 }
             }
         }
         /*if($remaining_amount>0)
           {
               echo "How come its possible! Consult with DEVELOPERS!!!";
           }*/
         //automatically reduce sales payment ends
         return Redirect::to('sales/voucher/' . $transactionId);
     }
 }
 /**
  * Function that pays tab with a cash transaction.
  *
  * @return Response
  */
 public function payBill()
 {
     // Validate Input.
     $validator = Validator::make(Input::all(), array('items' => 'required', 'institution' => 'required', 'discount' => 'required', 'card' => 'required', 'credit' => 'required', 'authCode' => 'required'));
     $response = array();
     if ($validator->fails()) {
         $response['state'] = 'Error';
         $response['error'] = 'No se proporciono toda la informacion necesaria para realizar transaccion!';
         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 user branch.
     $worker = Worker::find(Auth::user()->TypeId);
     $userBranch = $worker->BranchId;
     $branch = Branch::find($userBranch);
     $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);
     }
     // 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 all items.
     $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);
             }
             // 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)->first();
                 // If we have enough in stock withdraw it.
                 if ($stock->Quantity >= $quantity * $info->quantity) {
                     $stock->Quantity -= $quantity * $info->quantity;
                     $stock->save();
                 } else {
                     // Return all items and materials withdrawn so far.
                     $this->returnItems($items, $code);
                     $response['state'] = 'Error';
                     $response['error'] = 'No hay suficientes materiales o productos!';
                     return response()->json($response);
                 }
             }
             // Add price to total of factura.
             $salePrice += $service->Price * $info->quantity;
             // 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 >= $info->quantity) {
                 // Reduce products from stock.
                 $product->Quantity -= $info->quantity;
                 $product->save();
             } else {
                 // Return all items and materials withdrawn so far.
                 $this->returnItems($items, $code);
                 $response['state'] = 'Error';
                 $response['error'] = 'No hay suficientes materiales o productos!';
                 return response()->json($response);
             }
             // Add price to total of factura.
             $salePrice += $product->Price * $info->quantity;
         }
     }
     $subTotal = $salePrice;
     $discount = $salePrice * (Input::get('discount') / 100);
     // Give discount.
     $salePrice = $salePrice * (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);
         }
     }
     // Check if credit that creditor has enough credit available,
     // otherwise check that enough cash is being paid.
     $change = 0;
     if (Input::get('credit') == 1) {
         if (Input::get('institution') != 0) {
             // Get institution debt.
             $debt = 0;
             $pendingBills = Sale::where('CreditorId', '=', $institution->Id)->where('CreditorType', '=', 2)->where('Cancelled', '=', false)->get();
             foreach ($pendingBills as $pendingBill) {
                 $debt += $pendingBill->Value + $pendingBill->Tax;
             }
             // Check they have enough credit available.
             if ($debt + $salePrice + $tax > $institution->CreditLimit) {
                 $this->returnItems($items, '');
                 $response['state'] = 'Error';
                 $response['error'] = 'Esta institucion no tiene suficiente credito disponible para cancelar esta factura!';
                 return response()->json($response);
             }
         } else {
             if (!$client) {
                 $response['state'] = 'Error';
                 $response['error'] = 'No se definio un cliente para asignar factura a credito!';
                 return response()->json($response);
             }
             // Get client debt.
             $debt = 0;
             $pendingBills = Sale::where('CreditorId', '=', $client->Id)->where('CreditorType', '=', 1)->where('Cancelled', '=', false);
             foreach ($pendingBills as $pendingBill) {
                 $debt += $pendingBill->Value + $pendingBill->Tax;
             }
             // Check they have enough credit available.
             if ($debt + $salePrice + $tax > $client->CreditLimit) {
                 $this->returnItems($items, '');
                 $response['state'] = 'Error';
                 $response['error'] = 'Este cliente no tiene suficiente credito disponible para cancelar esta factura!';
                 return response()->json($response);
             }
         }
     } else {
         // Check enough cash is being paid.
         $change = Input::get('cash') - ($salePrice + $tax);
         if ($change < 0) {
             $this->returnItems($items, '');
             $response['state'] = 'Error';
             $response['error'] = 'Debe pagar con un valor igual o mayor al costo de lo facturado!';
             return response()->json($response);
         }
     }
     // Make cashbox transaction.
     $transaction;
     if (Input::get('credit') == 1) {
         $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 10, 'Amount' => $salePrice + $tax, 'Reason' => 'Venta de Credito.'));
     } else {
         $transaction = CashboxTransaction::create(array('CashboxId' => $cashbox->Id, 'DateTime' => date('Y-m-d H:i:s'), 'Type' => 1, 'Amount' => $salePrice + $tax, 'Reason' => 'Venta.'));
     }
     // Make sale.
     $card = 0;
     if (Input::get('card') != 0) {
         $config = Configuration::find(0);
         $card = $salePrice * ($config->POS / 100);
     }
     $sale;
     $type = 'contado';
     if (Input::get('credit') == 1) {
         $type = 'credito';
         if (Input::get('institution') != 0) {
             // Creditor Type 1 = Client, 2 = Institution.
             $sale = Sale::create(array('WorkerId' => $worker->Id, 'Value' => $salePrice, 'Tax' => $tax, 'Card' => $card, 'TransactionId' => $transaction->Id, 'BranchId' => $userBranch, 'Credit' => 1, 'CreditorId' => Input::get('institution'), 'CreditorType' => 2, 'Cancelled' => 0));
         } else {
             $sale = Sale::create(array('WorkerId' => $worker->Id, 'Value' => $salePrice, 'Tax' => $tax, 'Card' => $card, 'TransactionId' => $transaction->Id, 'BranchId' => $userBranch, 'Credit' => 1, 'CreditorId' => $client->Id, 'CreditorType' => 1, 'Cancelled' => 0));
         }
     } else {
         if (Input::get('institution') != 0) {
             // Creditor Type 1 = Client, 2 = Institution.
             $sale = Sale::create(array('WorkerId' => $worker->Id, 'Value' => $salePrice, 'Tax' => $tax, 'Card' => $card, 'TransactionId' => $transaction->Id, 'BranchId' => $userBranch, 'Credit' => 0, 'CreditorId' => Input::get('institution'), 'CreditorType' => 2, 'Cancelled' => 1));
         } else {
             if (!$client) {
                 $sale = Sale::create(array('WorkerId' => $worker->Id, 'Value' => $salePrice, 'Tax' => $tax, 'Card' => $card, 'TransactionId' => $transaction->Id, 'BranchId' => $userBranch, 'Credit' => 0, 'CreditorId' => 0, 'CreditorType' => 1, 'Cancelled' => 1));
             } else {
                 $sale = Sale::create(array('WorkerId' => $worker->Id, 'Value' => $salePrice, 'Tax' => $tax, 'Card' => $card, 'TransactionId' => $transaction->Id, 'BranchId' => $userBranch, 'Credit' => 0, 'CreditorId' => $client->Id, 'CreditorType' => 1, 'Cancelled' => 1));
             }
         }
     }
     // Now add sales 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();
             $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' => $code, 'Quantity' => $info->quantity, 'Cost' => $cost, 'Price' => $service->Price));
         } else {
             SaleBreakdown::create(array('SaleId' => $sale->Id, 'Code' => $code, 'Quantity' => $info->quantity, 'Cost' => $product->AverageCost, 'Price' => $product->Price));
         }
     }
     // Return success message and bill information.
     $response['state'] = 'Success';
     $response['change'] = $change;
     $response['billInfo'] = array('SubTotal' => $subTotal, 'Discount' => $discount, 'Tax' => $tax, 'Total' => $salePrice + $tax, 'SaleId' => $sale->Id, 'Date' => date('d/m/Y'), 'Type' => $type);
     $response['clientInfo'] = $clientInfo;
     $response['total'] = $salePrice + $tax;
     return response()->json($response);
 }
 public function getDelete($id)
 {
     $salesreturn = SalesReturnDetail::find($id);
     $saleReturnInvoice = SalesReturnInvoice::where('invoice_id', '=', $salesreturn->invoice_id)->first();
     $remaining_amount = $salesreturn->return_amount;
     $partyId = $saleReturnInvoice->party_id;
     if ($remaining_amount > 0) {
         $invoiceId = Sale::where('party_id', '=', $partyId)->where('is_sale', '=', 1)->get();
         foreach ($invoiceId as $invid) {
             $amount = Transaction::where('invoice_id', '=', $invid->invoice_id)->where('type', '=', 'Receive')->where('account_category_id', '=', 7)->get();
             foreach ($amount as $amnt) {
                 if ($amnt->amount > $remaining_amount) {
                     $transaction = Transaction::find($amnt->id);
                     $transaction->amount = $transaction->amount - $remaining_amount;
                     $transaction->save();
                     $sale = Sale::find($invid->id);
                     $sale->status = 'Partial';
                     $sale->save();
                     $remaining_amount = 0;
                 } elseif ($amnt->amount < $remaining_amount) {
                     $transaction = Transaction::find($amnt->id);
                     $transacamount = $transaction->amount;
                     $transaction->delete();
                     $sale = Sale::find($invid->id);
                     $sale->status = 'Partial';
                     $sale->save();
                     $remaining_amount = $remaining_amount - $transacamount;
                 } elseif ($amnt->amount == $remaining_amount) {
                     $transaction = Transaction::find($amnt->id);
                     $transaction->delete();
                     $sale = Sale::find($invid->id);
                     $sale->status = 'Partial';
                     $sale->save();
                     $remaining_amount = 0;
                 }
             }
         }
     }
     $salesreturn->delete();
     $saleReturnDetail = SalesReturnDetail::where('invoice_id', '=', $saleReturnInvoice->invoice_id)->get();
     if (empty($saleReturnDetail[0])) {
         echo 'deleted';
         $saleReturnInvoice->delete();
     }
 }
Beispiel #16
0
             // Deposits for reservations.
         // Deposits for reservations.
         case 9:
             $sales += $transaction->Amount;
             $cash += $transaction->Amount;
             break;
         case 10:
             $creditSales += $transaction->Amount;
             $sales += $transaction->Amount;
             break;
     }
 }
 $sold = array();
 // Get only sales transactions.
 foreach (CashboxTransaction::where('CashboxId', '=', $cashbox->Id)->where('Type', '=', 1)->get() as $transaction) {
     foreach (Sale::where('TransactionId', '=', $transaction->Id)->get() as $sale) {
         // Go through sale breackdown.
         foreach (SaleBreakdown::where('SaleId', '=', $sale->Id)->get() as $salebreakdown) {
             // Extract Product or Service.
             // TODO: Get only stock from user's branch.
             $product = Stock::where('Code', '=', $salebreakdown->Code)->first();
             if ($product) {
                 // Check if we have already sold this product.
                 if (array_key_exists($product->Code, $sold)) {
                     $sold[$salebreakdown->Code]['Quantity'] += $salebreakdown->Quantity;
                 } else {
                     $sold[$salebreakdown->Code] = array('Description' => $product->Description, 'Quantity' => $salebreakdown->Quantity);
                 }
             } else {
                 $service = Service::where('Code', '=', $salebreakdown->Code)->first();
                 if ($service) {
Beispiel #17
0
                                    <th>Bank Name</th>
                                    <th>Cheque No</th>
                                    <th>Cheque Date</th>
                                    <th>Amount</th>
                                    <th>Received by</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                                </thead>
                                <tbody>
                                <?php 
$slNo = 1;
?>
                                @foreach($register as $reg)
                                    <?php 
$sale = \App\Sale::where('invoice_id', '=', $reg->invoice_id)->first();
$partyname = \App\Party::find($sale->party_id);
$time = strtotime($reg->cheque_date);
$newformat = date('d', $time);
$today = date('d', time());
?>
                                    <tr>
                                        <td <?php 
if ($newformat >= $today - 2 && $newformat <= $today + 2) {
    echo "class='blink'";
}
?>
>{{$slNo}}</td>
                                        <td <?php 
if ($newformat >= $today - 2 && $newformat <= $today + 2) {
    echo "class='blink'";
 public function getSale($invoice_id)
 {
     $saleDetails = SAleDetail::where('invoice_id', '=', $invoice_id)->get();
     $sale = Sale::where('invoice_id', '=', $invoice_id)->get();
     foreach ($saleDetails as $saleDetail) {
         $stock = new Stock();
         $stock->branch_id = $saleDetail->branch_id;
         $stock->product_id = $saleDetail->product_id;
         $stock->product_type = $saleDetail->product_type;
         $stock->product_quantity = $saleDetail->quantity;
         $stock->entry_type = "StockOut";
         $stock->remarks = $saleDetail->remarks;
         $stock->user_id = Session::get('user_id');
         $stock->stock_info_id = $saleDetail->stock_info_id;
         $stock->status = "Activate";
         $stockCount = StockCount::where('product_id', '=', $saleDetail->product_id)->where('stock_info_id', '=', $saleDetail->stock_info_id)->get();
         if (!empty($stockCount[0])) {
             if ($stockCount[0]->product_quantity >= $saleDetail->quantity) {
                 $stockCount[0]->product_quantity = $stockCount[0]->product_quantity - $saleDetail->quantity;
                 $stock->save();
                 $stockCount[0]->save();
                 $sale[0]->is_sale = 1;
                 $sale[0]->save();
                 Session::flash('message', 'Stock  has been Successfully Balanced.');
             } else {
                 Session::flash('message', 'You Dont have enough products in Stock');
             }
         } else {
             Session::flash('message', 'You Dont have This products in This Stock');
         }
     }
     return Redirect::to('sales/index');
 }
 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);
     }
 }