Can anyone help me? how can i check all the product selected on the select or in the option? i'm using codeigniter 3 and i want to check if there was an available stock or none but i'm new and don't know how to do it i wish someone can help me. first it was working if i select a product with 0 quantity it will not process but if i select a first product with a quantity on hand greater than 0 and selected the second one with empty qty it will still process because it only check the stocks of the first product. how can i check all the qty selected in my select option?
my model:
public function create()
{
$user_id = $this->session->userdata('id');
// get store id from user id
$user_data = $this->model_users->getUserData($user_id);
$bill_no = 'BUBBLE-'.strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 4));
$data = array(
'bill_no' => $bill_no,
'date_time' => strtotime(date('Y-m-d h:i:s a')),
'gross_amount' => $this->input->post('gross_amount_value'),
'service_charge_rate' => $this->input->post('service_charge_rate'),
'service_charge_amount' => ($this->input->post('service_charge_value') > 0) ?$this->input->post('service_charge_value'):0,
'vat_charge_rate' => $this->input->post('vat_charge_rate'),
'vat_charge_amount' => ($this->input->post('vat_charge_value') > 0) ? $this->input->post('vat_charge_value') : 0,
'net_amount' => $this->input->post('net_amount_value'),
'discount' => $this->input->post('discount_amount_value'),
'paid_status' => 3,
'user_id' => $user_id,
'table_id' => $this->input->post('table_name'),
'discount_id' => json_encode($this->input->post('discount')),
'discount_percent' => $this->input->post('discount_perct_value'),
'datetoday' => date('Y-m-d h:i:s a'),
'payment_id' => json_encode($this->input->post('payment')),
);
$count_product = count($this->input->post('product'));
for($x = 0; $x < $count_product; $x++) {
$prodid = $this->input->post('product')[$x];
$prod_quan = $this->model_products->getProductData($prodid);
$inputQuantity = (int)$this->input->post('qty')[$x];
$check = $this->model_orders->check_stock($prodid, $inputQuantity);
if($check == TRUE)
{
$insert = $this->db->insert('orders', $data);
$order_id = $this->db->insert_id();
$count_product = count($this->input->post('product'));
for($x = 0; $x < $count_product; $x++) {
$items = array(
'order_id' => $order_id,
'product_id' => $this->input->post('product')[$x],
'qty' => $this->input->post('qty')[$x],
'rate' => $this->input->post('rate_value')[$x],
'amount' => $this->input->post('amount_value')[$x],
);
$this->db->insert('order_items', $items);
}
$this->load->model('model_tables');
$this->model_tables->update($this->input->post('table_name'), array('available' => 2));
return ($order_id) ? $order_id : false;
}
else
{
return false;
}
}
}
public function check_stock($productId, $inputQuantity)
{
$product = $this->db->get_where('products', ['id' => $productId])->row();
if(isset($product))
{
if($product->qty < $inputQuantity)
{
$this->session->set_flashdata('error','No more stock on some selected items');
return false;
}
else
{
return true;
}
}
}
and my select in view is something like this:
<select class="form-control select_group update-select" data-row-id="row_1" id="product_1" name="product[]" style="width:100%;" onchange="getProductData(1)" required>
<option disabled selected hidden value=''>--Select Products--</option>
<?php foreach ($products as $k => $v): ?>
<option value="<?php echo $v['id'] ?>"><?php echo $v['name'] ?></option>
<?php endforeach ?>
</select>
Easiest solution is to return false as soon as you find a product that is out of stock, something like the following:
Loop through the selected products and for each one check the stock. If you encounter a product that is out of stock, return false.
If all products are in stock, create the order, then loop through the selected products again and add those to the order in the database.
I haven't tested the code below, so there may be errors. I only changed the if($check == TRUE) part and some curly braces.
public function create()
{
$user_id = $this->session->userdata('id');
// get store id from user id
$user_data = $this->model_users->getUserData($user_id);
$bill_no = 'BUBBLE-'.strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 4));
$data = array(
'bill_no' => $bill_no,
'date_time' => strtotime(date('Y-m-d h:i:s a')),
'gross_amount' => $this->input->post('gross_amount_value'),
'service_charge_rate' => $this->input->post('service_charge_rate'),
'service_charge_amount' => ($this->input->post('service_charge_value') > 0) ?$this->input->post('service_charge_value'):0,
'vat_charge_rate' => $this->input->post('vat_charge_rate'),
'vat_charge_amount' => ($this->input->post('vat_charge_value') > 0) ? $this->input->post('vat_charge_value') : 0,
'net_amount' => $this->input->post('net_amount_value'),
'discount' => $this->input->post('discount_amount_value'),
'paid_status' => 3,
'user_id' => $user_id,
'table_id' => $this->input->post('table_name'),
'discount_id' => json_encode($this->input->post('discount')),
'discount_percent' => $this->input->post('discount_perct_value'),
'datetoday' => date('Y-m-d h:i:s a'),
'payment_id' => json_encode($this->input->post('payment')),
);
$count_product = count($this->input->post('product'));
for($x = 0; $x < $count_product; $x++) {
$prodid = $this->input->post('product')[$x];
$prod_quan = $this->model_products->getProductData($prodid);
$inputQuantity = (int)$this->input->post('qty')[$x];
$check = $this->model_orders->check_stock($prodid, $inputQuantity);
if($check != TRUE)
{
return false;
}
}
$insert = $this->db->insert('orders', $data);
$order_id = $this->db->insert_id();
$count_product = count($this->input->post('product'));
for($x = 0; $x < $count_product; $x++) {
$items = array(
'order_id' => $order_id,
'product_id' => $this->input->post('product')[$x],
'qty' => $this->input->post('qty')[$x],
'rate' => $this->input->post('rate_value')[$x],
'amount' => $this->input->post('amount_value')[$x],
);
$this->db->insert('order_items', $items);
}
$this->load->model('model_tables');
$this->model_tables->update($this->input->post('table_name'), array('available' => 2));
return ($order_id) ? $order_id : false;
}
Related
daily_attendances database
below is under crud_model
public function take_attendance()
{
$students = $this->input->post('student_id');
$data['timestamp'] = strtotime($this->input->post('date'));
$data['class_id'] = html_escape($this->input->post('class_id'));
$data['section_id'] = html_escape($this->input->post('section_id'));
$data['school_id'] = $this->school_id;
$data['session_id'] = $this->active_session;
$check_data = $this->db->get_where('daily_attendances', array('timestamp' => $data['timestamp'], 'class_id' => $data['class_id'], 'section_id' => $data['section_id'], 'session_id' => $data['session_id'], 'school_id' => $data['school_id']));
if($check_data->num_rows() > 0){
foreach($students as $key => $student):
$data['status'] = $this->input->post('status-'.$student);
$data['student_id'] = $student;
$attendance_id = $this->input->post('attendance_id');
$this->db->where('id', $attendance_id[$key]);
$this->db->update('daily_attendances', $data);
endforeach;
}else{
foreach($students as $student):
$data['status'] = $this->input->post('status-'.$student);
$data['student_id'] = $student;
$this->db->insert('daily_attendances', $data);
endforeach;
}
$this->settings_model->last_updated_attendance_data();
$response = array(
'status' => true,
'notification' => get_phrase('attendance_updated_successfully')
);
return json_encode($response);
}
public function get_presentcount_by_student_id($student_id="",$status ="") {
$checker = array(
'student_id' => $student_id,
'status' => 1
);
$presentcount_by_student_id = $this->db->get_where('daily_attendances', $checker);
return $presentcount_by_student_id->num_rows();
}
under the list.php where it shows the student name and the number of days present for each student.The code is below but it does not count number of presents for each student.It still remains 0
<td>
<?php echo $this->crud_model->get_presentcount_by_student_id($student['user_id'],'status');?>
<br>
</td>
Student detail list shown in table format
student_detail_list
use this
$count=DB::select("SELECT COUNT(*) as num FROM 'your-table-name' where status = 1 ")->get();
and you can access this by $count[0]->num
I make a parser of items from DotA 2 user inventory in the Steam service. Every time I try to parse user data, I get an empty value:
{"success":true,"items":[]}, but there are items in my Steam inventory.
My function to parse items:
public function loadMyInventory() {
if(Auth::guest()) return ['success' => false];
$prices = json_decode(Storage::get('prices.txt'), true);
$response = json_decode(file_get_contents('https://steamcommunity.com/inventory/'.$this->user->steamid64.'/570/2?l=russian&count=5000'), true);
if(time() < (Session::get('InvUPD') + 5)) {
return [
'success' => false,
'msg' => 'Error, repeat in '.(Session::get('InvUPD') - time() + 5).' сек.',
'status' => 'error'
];
}
//return $response;
$inventory = [];
foreach($response['assets'] as $item) {
$find = 0;
foreach($response['descriptions'] as $descriptions) {
if($find == 0) {
if(($descriptions['classid'] == $item['classid']) && ($descriptions['instanceid'] == $item['instanceid'])) {
$find++;
# If we find the price of an item, then move on.
if(isset($prices[$descriptions['market_hash_name']])) {
# Search data
$price = $prices[$descriptions['market_hash_name']]*$this->config->curs;
$class = false;
$text = false;
if($price <= $this->config->min_dep_sum) {
$price = 0;
$text = 'Cheap';
$class = 'minPrice';
}
if(($descriptions['tradable'] == 0) || ($descriptions['marketable'] == 0)) {
$price = 0;
$class = 'minPrice';
$text = 'Not tradable';
}
# Adding to Array
$inventory[] = [
'name' => $descriptions['market_name'],
'price' => floor($price),
'color' => $this->getRarity($descriptions['tags']),
'tradable' => $descriptions['tradable'],
'class' => $class,
'text' => $text,
'classid' => $item['classid'],
'assetid' => $item['assetid'],
'instanceid' => $item['instanceid']
];
}
}
}
}
}
Session::put('InvUPD', (time() + 5));
return [
'success' => true,
'items' => $inventory
];
}
But should return approximately the following value:
{"success":true,"items":[{"classid":"2274725521","instanceid":"57949762","assetid":"18235196074","market_hash_name":"Full-Bore Bonanza","price":26}]}
Where my mistake?
First of all, you are iterating on descriptions for every assets, which is assets*descriptions iteration, it's quite a lot, but you can optimize this.
let's loop once for descriptions and assign classid and instanceid as object key.
$assets = $response["assets"];
$descriptions = $response["descriptions"];
$newDescriptions=[];
foreach($descriptions as $d){
$newDescriptions[$d["classid"]][$d["instanceid"]] = $d;
}
this will give as the ability to not loop over description each time, we can access the description of certain asset directly $newDescriptions[$classid][$instanceid]]
foreach($assets as $a){
if(isset($newDescriptions[$a["classid"]]) && isset($newDescriptions[$a["classid"]][$a["instanceid"]])){
$assetDescription = $newDescriptions[$a["classid"]][$a["instanceid"]];
$inventory = [];
if(isset($prices[$assetDescription["market_hash_name"]])){
$price = $prices[$assetDescription['market_hash_name']]["price"]*$this->config->curs;
$class = false;
$text = false;
if($price <= $this->config->min_dep_sum) {
$price = 0;
$text = 'Cheap';
$class = 'minPrice';
}
if(($assetDescription['tradable'] == 0) || ($assetDescription['marketable'] == 0)) {
$price = 0;
$class = 'minPrice';
$text = 'Not tradable';
}
$inventory["priceFound"][] = [
'name' => $assetDescription['market_name'],
'price' => floor($price),
'color' => $this->getRarity($assetDescription['tags']),
'tradable' => $assetDescription['tradable'],
'class' => $class,
'text' => $text,
'classid' => $a['classid'],
'assetid' => $a['assetid'],
'instanceid' => $a['instanceid']
];
}else{
$inventory["priceNotFound"][] = $assetDescription["market_hash_name"];
}
}
}
About your mistake:
are you Sure your "prices.txt" contains market_hash_name?
I don't see any other issue yet, operationg on the data you have provided in comment, I got print of variable $assetDescription. Please doublecheck variable $prices.
public function add($quote_id = null)
{
$this->sma->checkPermissions();
$sale_id = $this->input->get('sale_id') ? $this->input->get('sale_id') : NULL;
$this->form_validation->set_message('is_natural_no_zero', lang("no_zero_required"));
$this->form_validation->set_rules('customer', lang("customer"), 'required');
$this->form_validation->set_rules('biller', lang("biller"), 'required');
$this->form_validation->set_rules('sale_status', lang("sale_status"), 'required');
$this->form_validation->set_rules('payment_status', lang("payment_status"), 'required');
if ($this->form_validation->run() == true) {
$reference = $this->input->post('reference_no') ? $this->input->post('reference_no') : $this->site->getReference('so');
if ($this->Owner || $this->Admin) {
$date = $this->sma->fld(trim($this->input->post('date')));
} else {
$date = date('Y-m-d H:i:s');
}
$warehouse_id = $this->input->post('warehouse');
$customer_id = $this->input->post('customer');
$biller_id = $this->input->post('biller');
$total_items = $this->input->post('total_items');
$sale_status = $this->input->post('sale_status');
$payment_status = $this->input->post('payment_status');
$payment_term = $this->input->post('payment_term');
$due_date = $payment_term ? date('Y-m-d', strtotime('+' . $payment_term . ' days', strtotime($date))) : null;
$shipping = $this->input->post('shipping') ? $this->input->post('shipping') : 0;
$customer_details = $this->site->getCompanyByID($customer_id);
$customer = $customer_details->company != '-' ? $customer_details->company : $customer_details->name;
$biller_details = $this->site->getCompanyByID($biller_id);
$biller = $biller_details->company != '-' ? $biller_details->company : $biller_details->name;
$note = $this->sma->clear_tags($this->input->post('note'));
$staff_note = $this->sma->clear_tags($this->input->post('staff_note'));
$quote_id = $this->input->post('quote_id') ? $this->input->post('quote_id') : null;
$total = 0;
$product_tax = 0;
$order_tax = 0;
$product_discount = 0;
$order_discount = 0;
$percentage = '%';
$digital = FALSE;
$i = isset($_POST['product_code']) ? sizeof($_POST['product_code']) : 0;
for ($r = 0; $r < $i; $r++) {
$item_id = $_POST['product_id'][$r];
$item_type = $_POST['product_type'][$r];
$item_code = $_POST['product_code'][$r];
$item_name = $_POST['product_name'][$r];
$item_option = isset($_POST['product_option'][$r]) && $_POST['product_option'][$r] != 'false' && $_POST['product_option'][$r] != 'null' ? $_POST['product_option'][$r] : null;
$real_unit_price = $this->sma->formatDecimal($_POST['real_unit_price'][$r]);
$unit_price = $this->sma->formatDecimal($_POST['unit_price'][$r]);
$item_unit_quantity = $_POST['quantity'][$r];
$item_serial = isset($_POST['serial'][$r]) ? $_POST['serial'][$r] : '';
$item_tax_rate = isset($_POST['product_tax'][$r]) ? $_POST['product_tax'][$r] : null;
$item_discount = isset($_POST['product_discount'][$r]) ? $_POST['product_discount'][$r] : null;
$item_unit = $_POST['product_unit'][$r];
$item_quantity = $_POST['product_base_quantity'][$r];
if (isset($item_code) && isset($real_unit_price) && isset($unit_price) && isset($item_quantity)) {
$product_details = $item_type != 'manual' ? $this->sales_model->getProductByCode($item_code) : null;
// $unit_price = $real_unit_price;
$pr_discount = 0;
if ($item_type == 'digital') {
$digital = TRUE;
}
if (isset($item_discount)) {
$discount = $item_discount;
$dpos = strpos($discount, $percentage);
if ($dpos !== false) {
$pds = explode("%", $discount);
$pr_discount = $this->sma->formatDecimal(((($this->sma->formatDecimal($unit_price)) * (Float) ($pds[0])) / 100), 4);
} else {
$pr_discount = $this->sma->formatDecimal($discount);
}
}
$unit_price = $this->sma->formatDecimal($unit_price - $pr_discount);
$item_net_price = $unit_price;
$pr_item_discount = $this->sma->formatDecimal($pr_discount * $item_unit_quantity);
$product_discount += $pr_item_discount;
$pr_tax = 0;
$pr_item_tax = 0;
$item_tax = 0;
$tax = "";
if (isset($item_tax_rate) && $item_tax_rate != 0) {
$pr_tax = $item_tax_rate;
$tax_details = $this->site->getTaxRateByID($pr_tax);
if ($tax_details->type == 1 && $tax_details->rate != 0) {
if ($product_details && $product_details->tax_method == 1) {
$item_tax = $this->sma->formatDecimal((($unit_price) * $tax_details->rate) / 100, 4);
$tax = $tax_details->rate . "%";
} else {
$item_tax = $this->sma->formatDecimal((($unit_price) * $tax_details->rate) / (100 + $tax_details->rate), 4);
$tax = $tax_details->rate . "%";
$item_net_price = $unit_price - $item_tax;
}
} elseif ($tax_details->type == 2) {
if ($product_details && $product_details->tax_method == 1) {
$item_tax = $this->sma->formatDecimal((($unit_price) * $tax_details->rate) / 100, 4);
$tax = $tax_details->rate . "%";
} else {
$item_tax = $this->sma->formatDecimal((($unit_price) * $tax_details->rate) / (100 + $tax_details->rate), 4);
$tax = $tax_details->rate . "%";
$item_net_price = $unit_price - $item_tax;
}
$item_tax = $this->sma->formatDecimal($tax_details->rate);
$tax = $tax_details->rate;
}
$pr_item_tax = $this->sma->formatDecimal($item_tax * $item_unit_quantity, 4);
}
$product_tax += $pr_item_tax;
$subtotal = (($item_net_price * $item_unit_quantity) + $pr_item_tax);
$unit = $this->site->getUnitByID($item_unit);
$products[] = array(
'product_id' => $item_id,
'product_code' => $item_code,
'product_name' => $item_name,
'product_type' => $item_type,
'option_id' => $item_option,
'net_unit_price' => $item_net_price,
'unit_price' => $this->sma->formatDecimal($item_net_price + $item_tax),
'quantity' => $item_quantity,
'product_unit_id' => $item_unit,
'product_unit_code' => $unit ? $unit->code : NULL,
'unit_quantity' => $item_unit_quantity,
'warehouse_id' => $warehouse_id,
'item_tax' => $pr_item_tax,
'tax_rate_id' => $pr_tax,
'tax' => $tax,
'discount' => $item_discount,
'item_discount' => $pr_item_discount,
'subtotal' => $this->sma->formatDecimal($subtotal),
'serial_no' => $item_serial,
'real_unit_price' => $real_unit_price,
);
$total += $this->sma->formatDecimal(($item_net_price * $item_unit_quantity), 4);
}
}
if (empty($products)) {
$this->form_validation->set_rules('product', lang("order_items"), 'required');
} else {
krsort($products);
}
if ($this->input->post('order_discount')) {
$order_discount_id = $this->input->post('order_discount');
$opos = strpos($order_discount_id, $percentage);
if ($opos !== false) {
$ods = explode("%", $order_discount_id);
$order_discount = $this->sma->formatDecimal(((($total + $product_tax) * (Float) ($ods[0])) / 100), 4);
} else {
$order_discount = $this->sma->formatDecimal($order_discount_id);
}
} else {
$order_discount_id = null;
}
$total_discount = $this->sma->formatDecimal($order_discount + $product_discount);
if ($this->Settings->tax2) {
$order_tax_id = $this->input->post('order_tax');
if ($order_tax_details = $this->site->getTaxRateByID($order_tax_id)) {
if ($order_tax_details->type == 2) {
$order_tax = $this->sma->formatDecimal($order_tax_details->rate);
} elseif ($order_tax_details->type == 1) {
$order_tax = $this->sma->formatDecimal(((($total + $product_tax - $order_discount) * $order_tax_details->rate) / 100), 4);
}
}
} else {
$order_tax_id = null;
}
$total_tax = $this->sma->formatDecimal(($product_tax + $order_tax), 4);
$grand_total = $this->sma->formatDecimal(($total + $total_tax + $this->sma->formatDecimal($shipping) - $order_discount), 4);
$data = array('date' => $date,
'reference_no' => $reference,
'customer_id' => $customer_id,
'customer' => $customer,
'biller_id' => $biller_id,
'biller' => $biller,
'warehouse_id' => $warehouse_id,
'note' => $note,
'staff_note' => $staff_note,
'total' => $total,
'product_discount' => $product_discount,
'order_discount_id' => $order_discount_id,
'order_discount' => $order_discount,
'total_discount' => $total_discount,
'product_tax' => $product_tax,
'order_tax_id' => $order_tax_id,
'order_tax' => $order_tax,
'total_tax' => $total_tax,
'shipping' => $this->sma->formatDecimal($shipping),
'grand_total' => $grand_total,
'total_items' => $total_items,
'sale_status' => $sale_status,
'payment_status' => $payment_status,
'payment_term' => $payment_term,
'due_date' => $due_date,
'paid' => 0,
'created_by' => $this->session->userdata('user_id'),
);
if ($payment_status == 'partial' || $payment_status == 'paid') {
if ($this->input->post('paid_by') == 'deposit') {
if ( ! $this->site->check_customer_deposit($customer_id, $this->input->post('amount-paid'))) {
$this->session->set_flashdata('error', lang("amount_greater_than_deposit"));
redirect($_SERVER["HTTP_REFERER"]);
}
}
if ($this->input->post('paid_by') == 'gift_card') {
$gc = $this->site->getGiftCardByNO($this->input->post('gift_card_no'));
$amount_paying = $grand_total >= $gc->balance ? $gc->balance : $grand_total;
$gc_balance = $gc->balance - $amount_paying;
$payment = array(
'date' => $date,
'reference_no' => $this->input->post('payment_reference_no'),
'amount' => $this->sma->formatDecimal($amount_paying),
'paid_by' => $this->input->post('paid_by'),
'cheque_no' => $this->input->post('cheque_no'),
'cc_no' => $this->input->post('gift_card_no'),
'cc_holder' => $this->input->post('pcc_holder'),
'cc_month' => $this->input->post('pcc_month'),
'cc_year' => $this->input->post('pcc_year'),
'cc_type' => $this->input->post('pcc_type'),
'created_by' => $this->session->userdata('user_id'),
'note' => $this->input->post('payment_note'),
'type' => 'received',
'gc_balance' => $gc_balance,
);
} else {
$payment = array(
'date' => $date,
'reference_no' => $this->input->post('payment_reference_no'),
'amount' => $this->sma->formatDecimal($this->input->post('amount-paid')),
'paid_by' => $this->input->post('paid_by'),
'cheque_no' => $this->input->post('cheque_no'),
'cc_no' => $this->input->post('pcc_no'),
'cc_holder' => $this->input->post('pcc_holder'),
'cc_month' => $this->input->post('pcc_month'),
'cc_year' => $this->input->post('pcc_year'),
'cc_type' => $this->input->post('pcc_type'),
'created_by' => $this->session->userdata('user_id'),
'note' => $this->input->post('payment_note'),
'type' => 'received',
);
}
} else {
$payment = array();
}
if ($_FILES['document']['size'] > 0) {
$this->load->library('upload');
$config['upload_path'] = $this->digital_upload_path;
$config['allowed_types'] = $this->digital_file_types;
$config['max_size'] = $this->allowed_file_size;
$config['overwrite'] = false;
$config['encrypt_name'] = true;
$this->upload->initialize($config);
if (!$this->upload->do_upload('document')) {
$error = $this->upload->display_errors();
$this->session->set_flashdata('error', $error);
redirect($_SERVER["HTTP_REFERER"]);
}
$photo = $this->upload->file_name;
$data['attachment'] = $photo;
}
// $this->sma->print_arrays($data, $products, $payment);
}
if ($this->form_validation->run() == true && $this->sales_model->addSale($data, $products, $payment)) {
$this->session->set_userdata('remove_slls', 1);
if ($quote_id) {
$this->db->update('quotes', array('status' => 'completed'), array('id' => $quote_id));
}
$this->session->set_flashdata('message', lang("sale_added"));
redirect("sales");
} else {
if ($quote_id || $sale_id) {
if ($quote_id) {
$this->data['quote'] = $this->sales_model->getQuoteByID($quote_id);
$items = $this->sales_model->getAllQuoteItems($quote_id);
} elseif ($sale_id) {
$this->data['quote'] = $this->sales_model->getInvoiceByID($sale_id);
$items = $this->sales_model->getAllInvoiceItems($sale_id);
}
krsort($items);
$c = rand(100000, 9999999);
foreach ($items as $item) {
$row = $this->site->getProductByID($item->product_id);
if (!$row) {
$row = json_decode('{}');
$row->tax_method = 0;
} else {
unset($row->cost, $row->details, $row->product_details, $row->image, $row->barcode_symbology, $row->cf1, $row->cf2, $row->cf3, $row->cf4, $row->cf5, $row->cf6, $row->supplier1price, $row->supplier2price, $row->cfsupplier3price, $row->supplier4price, $row->supplier5price, $row->supplier1, $row->supplier2, $row->supplier3, $row->supplier4, $row->supplier5, $row->supplier1_part_no, $row->supplier2_part_no, $row->supplier3_part_no, $row->supplier4_part_no, $row->supplier5_part_no);
}
$row->quantity = 0;
$pis = $this->site->getPurchasedItems($item->product_id, $item->warehouse_id, $item->option_id);
if ($pis) {
foreach ($pis as $pi) {
$row->quantity += $pi->quantity_balance;
}
}
$row->id = $item->product_id;
$row->code = $item->product_code;
$row->name = $item->product_name;
$row->type = $item->product_type;
$row->qty = $item->quantity;
$row->base_quantity = $item->quantity;
$row->base_unit = $row->unit ? $row->unit : $item->product_unit_id;
$row->base_unit_price = $row->price ? $row->price : $item->unit_price;
$row->unit = $item->product_unit_id;
$row->qty = $item->unit_quantity;
$row->discount = $item->discount ? $item->discount : '0';
$row->price = $this->sma->formatDecimal($item->net_unit_price + $this->sma->formatDecimal($item->item_discount / $item->quantity));
$row->unit_price = $row->tax_method ? $item->unit_price + $this->sma->formatDecimal($item->item_discount / $item->quantity) + $this->sma->formatDecimal($item->item_tax / $item->quantity) : $item->unit_price + ($item->item_discount / $item->quantity);
$row->real_unit_price = $item->real_unit_price;
$row->tax_rate = $item->tax_rate_id;
$row->serial = '';
$row->option = $item->option_id;
$options = $this->sales_model->getProductOptions($row->id, $item->warehouse_id);
if ($options) {
$option_quantity = 0;
foreach ($options as $option) {
$pis = $this->site->getPurchasedItems($row->id, $item->warehouse_id, $item->option_id);
if ($pis) {
foreach ($pis as $pi) {
$option_quantity += $pi->quantity_balance;
}
}
if ($option->quantity > $option_quantity) {
$option->quantity = $option_quantity;
}
}
}
$combo_items = false;
if ($row->type == 'combo') {
$combo_items = $this->sales_model->getProductComboItems($row->id, $item->warehouse_id);
}
$units = $this->site->getUnitsByBUID($row->base_unit);
$tax_rate = $this->site->getTaxRateByID($row->tax_rate);
$ri = $this->Settings->item_addition ? $row->id : $c;
$pr[$ri] = array('id' => $c, 'item_id' => $row->id, 'label' => $row->name . " (" . $row->code . ")",
'row' => $row, 'combo_items' => $combo_items, 'tax_rate' => $tax_rate, 'units' => $units, 'options' => $options);
$c++;
}
$this->data['quote_items'] = json_encode($pr);
}
$this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
$this->data['quote_id'] = $quote_id ? $quote_id : $sale_id;
$this->data['billers'] = $this->site->getAllCompanies('biller');
$this->data['warehouses'] = $this->site->getAllWarehouses();
$this->data['tax_rates'] = $this->site->getAllTaxRates();
//$this->data['currencies'] = $this->sales_model->getAllCurrencies();
$this->data['slnumber'] = ''; //$this->site->getReference('so');
$this->data['payment_ref'] = ''; //$this->site->getReference('pay');
$bc = array(array('link' => base_url(), 'page' => lang('home')), array('link' => site_url('sales'), 'page' => lang('sales')), array('link' => '#', 'page' => lang('add_sale')));
$meta = array('page_title' => lang('add_sale'), 'bc' => $bc);
$this->page_construct('sales/add', $meta, $this->data);
}
}
public function calculateAVCost($product_id, $warehouse_id, $net_unit_price, $unit_price, $quantity, $product_name, $option_id, $item_quantity) {
$product = $this->getProductByID($product_id);
$real_item_qty = $quantity;
$wp_details = $this->getWarehouseProduct($warehouse_id, $product_id);
$avg_net_unit_cost = $wp_details ? $wp_details->avg_cost : $product->cost;
$avg_unit_cost = $wp_details ? $wp_details->avg_cost : $product->cost;
if ($pis = $this->getPurchasedItems($product_id, $warehouse_id, $option_id)) {
$cost_row = array();
$quantity = $item_quantity;
$balance_qty = $quantity;
foreach ($pis as $pi) {
if (!empty($pi) && $pi->quantity > 0 && $balance_qty <= $quantity && $quantity > 0) {
if ($pi->quantity_balance >= $quantity && $quantity > 0) {
$balance_qty = $pi->quantity_balance - $quantity;
$cost_row = array('date' => date('Y-m-d'), 'product_id' => $product_id, 'sale_item_id' => 'sale_items.id', 'purchase_item_id' => $pi->id, 'quantity' => $real_item_qty, 'purchase_net_unit_cost' => $avg_net_unit_cost, 'purchase_unit_cost' => $avg_unit_cost, 'sale_net_unit_price' => $net_unit_price, 'sale_unit_price' => $unit_price, 'quantity_balance' => $balance_qty, 'inventory' => 1, 'option_id' => $option_id);
$quantity = 0;
} elseif ($quantity > 0) {
$quantity = $quantity - $pi->quantity_balance;
$balance_qty = $quantity;
$cost_row = array('date' => date('Y-m-d'), 'product_id' => $product_id, 'sale_item_id' => 'sale_items.id', 'purchase_item_id' => $pi->id, 'quantity' => $pi->quantity_balance, 'purchase_net_unit_cost' => $avg_net_unit_cost, 'purchase_unit_cost' => $avg_unit_cost, 'sale_net_unit_price' => $net_unit_price, 'sale_unit_price' => $unit_price, 'quantity_balance' => 0, 'inventory' => 1, 'option_id' => $option_id);
}
}
if (empty($cost_row)) {
break;
}
$cost[] = $cost_row;
if ($quantity == 0) {
break;
}
}
}
if ($quantity > 0 && !$this->Settings->overselling) {
$this->session->set_flashdata('error', sprintf(lang("quantity_out_of_stock_for_%s"), ($pi->product_name ? $pi->product_name : $product_name)));
redirect($_SERVER["HTTP_REFERER"]);
} elseif ($quantity > 0) {
$cost[] = array('date' => date('Y-m-d'), 'product_id' => $product_id, 'sale_item_id' => 'sale_items.id', 'purchase_item_id' => NULL, 'quantity' => $real_item_qty, 'purchase_net_unit_cost' => $avg_net_unit_cost, 'purchase_unit_cost' => $avg_unit_cost, 'sale_net_unit_price' => $net_unit_price, 'sale_unit_price' => $unit_price, 'quantity_balance' => NULL, 'overselling' => 1, 'inventory' => 1);
$cost[] = array('pi_overselling' => 1, 'product_id' => $product_id, 'quantity_balance' => (0 - $quantity), 'warehouse_id' => $warehouse_id, 'option_id' => $option_id);
}
return $cost;
}
warehouse id 2
I am trying to sell the item from warehouse_id 2 where i have 43 products in stock where it shows of stock when i am selling 1 or 2 quantity from this warehouse i dont know which piece of code causing the issue.
Quantity issue is quite likely in this code as i have asked the tecdiary about the issue but they themselves dont know which piece of code is causing the issue
error when selling
How to increase the performance of following function in phalcon framework. There are thousands of records in the table. I tried different ways, but I am stuck the point. How can I increase the efficiency and reduce the execution time. Following are two methods:
public function currentmonthAction()
{
$payload = $this->request->getJsonRawBody();
$this->setDB();
$ticketsmodel = new Tickets();
$fromcitycondition = "";
if( isset($payload->city->id) )
{
$fromcitycondition = "and fromcity='{$payload->city->id}'";
}
try{
$date = new \Datetime($payload->date);
$year = $date->format('Y');
$month = $date->format('m');
$month = '08';
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
/* result for all cities passenger */
$result = array();
// get all cities permutations
$tmpcitiesdata = array();
$rawresultset = Tickets::find (
array(
'columns' => 'fromcity,tocity',
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (1) ". $fromcitycondition,
'group' => 'fromcity,tocity'
));
foreach ($rawresultset as $rawresult) {
$tmpcitiesdata[$rawresult->fromcity.'-'.$rawresult->tocity]['fromcity'] = $rawresult->fromcity;
$tmpcitiesdata[$rawresult->fromcity.'-'.$rawresult->tocity]['tocity'] = $rawresult->tocity;
}
//var_dump($rawresultset);
// get tickets sold based on cities combinations
$total = 0;
foreach ($tmpcitiesdata as $tmpcities) {
$rawresultset = Tickets::find (
array(
'columns' => 'customer',
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (1) and fromcity=". $tmpcities['fromcity']." and tocity=".$tmpcities['tocity'],
'group' => 'customer'
));
$totalsoldRaw = count($rawresultset);
// get ticket cancellations
$rawresultset = Tickets::find (
array(
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (3) and fromcity=". $tmpcities['fromcity']." and tocity=".$tmpcities['tocity']
));
//make sure cancellations are tickets cancellations not booking cancellations
foreach($rawresultset as $rawresult)
{
$resultNumber = Tickets::find("departure='$rawresult->departure' and seatno={$rawresult->seatno} and id < {$rawresult->id} and tickettype = 1" );
if( count($resultNumber) > 0 ){
$totalsoldRaw = $totalsoldRaw-1;
}
}
$total += $totalsoldRaw;
array_push($result, array('total' => $totalsoldRaw, 'fromcity' => Cities::findFirstById($tmpcities['fromcity'])->name, 'tocity' => Cities::findFirstById($tmpcities['tocity'])->name));
}
//sort result based on counts
arsort($result);
//cut result to max 6 cities
$result = array_slice($result, 0, 6);
$this->response->setContentType('application/json')
->setJsonContent(
array( 'totaltickets' => $total, "allcities" => $result )
);
$this->response->send();
return;
}
catch(\PDOException $e)
{
$this->response->setStatusCode('422','Invalid Payload');
$this->response->setContentType('application/json')
->setJsonContent(array(
'flash' => array(
'class' => 'danger',
'message' => $e->getMessage()
)
));
$this->response->send();
return;
}
}
Use count instead of count(result of find). Also are you sure in // get ticket cancellations you don't need group ? Then you can select all tickets for customers in 1,3 tickettype and then filter resultset.
Also can't your first $rawresulset can't be:
$rawresultset = Tickets::find (
array(
'columns' => 'customer,fromcity,tocity,tickettype ',
'conditions' => "departure between '{$year}-{$month}-01' and '{$year}-{$month}-$daysInMonth' and tickettype in (1,3)".$fromcitycondition
'group' => 'customer,fromcity,tocity'
));
?
$ticketCanccelations = $rawresultset->filter(function($row){
if($row->tickettype == 3) {
return $row;
}
});
$resultNumber = Tickets::count("departure='$rawresult->departure' and seatno={$rawresult->seatno} and id < {$rawresult->id} and tickettype = 1" );
In my lottery project I have 5 tickets, in which you select numbers and buy. The thing is, you can only buy the tickets if you buy them in order... For example:
Ticket 1 Ticket 2 Ticket 3 Ticket 4 Ticket 5
If you add numbers to the ticket 1 and then the others it works... If you skip the ticket 1 and add numbers to the other ones, when you try to buy you get this error:
ContextErrorException: Notice: Undefined offset: 0 in C:\wamp\www\Digidis\front\src\MediaparkLt\UserBundle\Service\MoneyManager.php line 313
The full stack:
array('cartProduct' => array('title' => 'EUROMILLONES', 'price' => '2.35', 'product' => '2', 'ticket_id' => '1433921783_19792', 'numbers' => '8,13,14,17,37', 'stars' => '4,7', 'betslip' => '{"duration":"1","subscription":"false","jsPrice":"235","type":"simple","numbers1":"0,0,0,0,0","numbers2":"8,13,14,17,37","numbers3":"0,0,0,0,0","numbers4":"0,0,0,0,0","numbers5":"0,0,0,0,0","stars1":"0,0","stars2":"4,7","stars3":"0,0","stars4":"0,0","stars5":"0,0","dayOfWeek":"3"}', 'is_syndicate' => false, 'draw' => object(DateTime)), 'product' => object(Product), 'user' => object(User), 'reference' => null, 'paymentResult' => 'Authorised', 'bets' => object(stdClass), 'individualBets' => array(), 'tickets' => array(array('numbers' => '8,13,14,17,37', 'stars' => '4,7')), 'k' => '0', 't' => array('numbers' => '0,0,0,0,0', 'stars' => '0,0'), 'is_ticket_filled' => false, 'week_id' => array(array('ticketId' => '7005')), 'g' => '0', 'lastId' => '7005', 'purchase' => object(Purchase), 'price' => '2.35', 'bet' => object(Bet), 'euromillonesBet' => object(EuromillonesBet), 'drawDate' => array(object(DrawDate)), 'j' => '0')) in C:\wamp\www\Digidis\front\src\MediaparkLt\UserBundle\Service\MoneyManager.php line 313
As you can see first it gets the ticket 1, which is empty(or 0) and thats why it causes the error... How can I make it so that it skips the empty tickets?
Here is the controller where the error occurs:
$bets = json_decode($cartProduct['betslip']);
$individualBets = array();
$tickets = array(
array('numbers' => $bets->numbers1, 'stars' => $bets->stars1),
array('numbers' => $bets->numbers2, 'stars' => $bets->stars2),
array('numbers' => $bets->numbers3, 'stars' => $bets->stars3),
array('numbers' => $bets->numbers4, 'stars' => $bets->stars4),
array('numbers' => $bets->numbers5, 'stars' => $bets->stars5)
);
if ($bets->type === 'simple') {
foreach ($tickets as $k => $t) {
$is_ticket_filled = ((int) str_replace(',', '', $t['numbers'])) > 0;
if (!$is_ticket_filled) {
unset($tickets[$k]);
}
}
} else if ($bets->type === 'multiple') {
$tickets = array(array('numbers' => $bets->numbers1, 'stars' => $bets->stars1));
}
$week_id = null;
for ($k = 0; $k < (count($tickets)); $k++) {
for ($g = 0; $g < $bets->duration; $g++) {
if (!isset($week_id[$g])) {
$week_id[$g] = $this->entityManager->getRepository('MediaparkLtLotteryBundle:Bet')->getLastTicketId();
if ($week_id[$g]) {
$week_id[$g]['ticketId'] ++;
} else {
$week_id[$g]['ticketId'] = 0;
}
}
$lastId = $week_id[$g]['ticketId'];
$purchase = new Purchase();
$purchase->setUser($user);
$purchase->setDrawDate($cartProduct['draw']);
$purchase->setProduct($product);
$purchase->setReference($reference);
$price = $cartProduct['price'];
$bet = new Bet();
if ('eurojackpot' == $product->getAlias()) {
$euromillonesBet = new EurojackpotBet();
} else {
$euromillonesBet = new EuromillonesBet();
}
$drawDate = $this->entityManager->getRepository('MediaparkLtLotteryBundle:DrawDate')->findByDrawDate($cartProduct['draw']);
if (!$drawDate)
die('no draw date found ' . $cartProduct['draw']->format('Y-m-d H:i:s'));
$bet->setDrawDate($drawDate[0]);
$bet->setTicketId($lastId);
if (strtoupper($paymentResult) === 'AUTHORISED') {
$bet->setStatus(BetStatus::AUTHORISED);
} else {
$bet->setStatus(BetStatus::FAILED);
}
$bet->setWinnings(0);
$euromillonesBet->setBet($bet);
/// LINE 313 ABOVE!!!!!!!
$numbers = $this->getNumbersArray($tickets[$k]['numbers']);
$j = 0;
foreach ($numbers as $number) {
$j++;
$name = 'setN' . $j;
$euromillonesBet->$name($number);
}
$numbers = $this->getNumbersArray($tickets[$k]['stars']);
$euromillonesBet->setS1($numbers[0]);
$euromillonesBet->setS2($numbers[1]);
$euromillonesBet->setAmountOfStars(Bet::NUMBER_OF_STARS);
$purchase->addBet($bet);
$purchase->setPricePaid($price);
if (strtoupper($paymentResult) === 'AUTHORISED') {
$purchase->setStatus(PaymentStatus::AUTHORISED);
} else {
$purchase->setStatus(PaymentStatus::FAILED);
}
if ($bets->subscription === "true") {
$contract = new PurchaseContract();
$contract->setAccumulatedWinnings(0);
$contract->setCancellationDate(null);
$contract->setFirstDrawDate($purchase->getDrawDate());
$contract->setLastRenewedDate($purchase->getDrawDate());
$contract->setNextRenewalFirstDrawDate($purchase->getDrawDate());
// $contract->setPurchase($purchase);
$contract->setStatusPurchaseContract(1);
$contract->setWeeks(1);
$purchase->setPurchaseContract($contract);
$this->entityManager->persist($contract);
}
if ($g == 0)
$individualBets[] = $euromillonesBet;
$this->entityManager->persist($bet);
$this->entityManager->persist($euromillonesBet);
$this->entityManager->persist($purchase);
$this->entityManager->flush();
}
}
return $individualBets;
}
From what I see the bet type in your object is set to "type":"simple" and numbers1":"0,0,0,0,0"
$is_ticket_filled = ((int) str_replace(',', '', $t['numbers'])) > 0;
//(int) 00000 = 0
if (!$is_ticket_filled) {
unset($tickets[$k]);
}
Is causing the issue since unset does not reset the array indexes.
http://ideone.com/5q74Wv
Then later you iterate using for($k=0; $k < count($tickets); $k++)
You should instead rebase the array after using unset($tickets[$k])
if ($bets->type === 'simple') {
//...
$tickets = array_values($tickets);
}
or check the existence of the ticket when iterating over indexes
$ticketCount = count($tickets);
for ($k=0; $k < $ticketCount; $k++) {
if (false === isset($tickets[$k]) {
continue;
}
//...
}
or easier still, iterate over the existing tickets array using foreach instead of for.
foreach ($tickets as $k => $ticket) {
//...
}
Then change $tickets[$k] with just $ticket since $k is not used anywhere else.