Displaying success message after form is submitted - php

My form was working perfectly fine and displays the success message when the form is submitted. However, I just added a small piece of code and though the form submits, it doesn't display the success message anymore.
This is my code:
public function entrymarks()
{
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('exam_group_class_batch_exam_subject_id', 'Subject', 'required|trim|xss_clean');
if ($this->form_validation->run() == false) {
$data = array(
'exam_group_class_batch_exam_subject_id' => form_error('exam_group_class_batch_exam_subject_id'),
);
$array = array('status' => 0, 'error' => $data);
echo json_encode($array);
} else {
$exam_group_student_id = $this->input->post('exam_group_student_id');
$insert_array = array();
$update_array = array();
if (!empty($exam_group_student_id)) {
foreach ($exam_group_student_id as $exam_group_student_key => $exam_group_student_value) {
$attendance_post = $this->input->post('exam_group_student_attendance_' . $exam_group_student_value);
if (isset($attendance_post)) {
$attendance = $this->input->post('exam_group_student_attendance_' . $exam_group_student_value);
} else {
$attendance = "present";
}
$cal1 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value);
$cal2 = $this->input->post('exam_group_student_ca2_' . $exam_group_student_value);
$cal3 = $this->input->post('exam_group_student_ca3_' . $exam_group_student_value);
$cal4 = $this->input->post('exam_group_student_ca4_' . $exam_group_student_value);
$exam = $this->input->post('exam_group_student_exam_' . $exam_group_student_value);
$total = $cal1 + $cal2 + $cal3 + $cal4 + $exam;
if ($total > 0) { // This line may be the problem
$array = array(
'exam_group_class_batch_exam_subject_id' => $this->input->post('exam_group_class_batch_exam_subject_id'),
'exam_group_class_batch_exam_student_id' => $exam_group_student_value,
'attendence' => $attendance,
'get_ca1' => $cal1,
'get_ca2' => $cal2,
'get_ca3' => $cal3,
'get_ca4' => $cal4,
'get_exam' => $exam,
'get_tot_score' => $total,
'note' => $this->input->post('exam_group_student_note_' . $exam_group_student_value),
);
$insert_array[] = $array;
}
}
}
$this->examgroupstudent_model->add_result($insert_array);
$array = array('status' => '1', 'error' => '', 'message' => $this->lang->line('success_message'));
echo json_encode($array);
}
}
How do I get the success message to display again?

Related

Prevent inserting to database If total value is equal to 0,

When adding scores for students, I would like those with a total score of 0 not to be inserted into the database at all.
Controller:
public function entrymarks()
{
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('exam_group_class_batch_exam_subject_id', 'Subject', 'required|trim|xss_clean');
if ($this->form_validation->run() == false) {
$data = array(
'exam_group_class_batch_exam_subject_id' => form_error('exam_group_class_batch_exam_subject_id'),
);
$array = array('status' => 0, 'error' => $data);
echo json_encode($array);
} else {
$exam_group_student_id = $this->input->post('exam_group_student_id');
$insert_array = array();
$update_array = array();
if (!empty($exam_group_student_id)) {
foreach ($exam_group_student_id as $exam_group_student_key => $exam_group_student_value) {
$attendance_post = $this->input->post('exam_group_student_attendance_' . $exam_group_student_value);
if (isset($attendance_post)) {
$attendance = $this->input->post('exam_group_student_attendance_' . $exam_group_student_value);
} else {
$attendance = "present";
}
$array = array(
'exam_group_class_batch_exam_subject_id' => $this->input->post('exam_group_class_batch_exam_subject_id'),
'exam_group_class_batch_exam_student_id' => $exam_group_student_value,
'attendence' => $attendance,
'get_ca1' => $this->input->post('exam_group_student_ca1_' . $exam_group_student_value),
'get_ca2' => $this->input->post('exam_group_student_ca2_' . $exam_group_student_value),
'get_ca3' => $this->input->post('exam_group_student_ca3_' . $exam_group_student_value),
'get_ca4' => $this->input->post('exam_group_student_ca4_' . $exam_group_student_value),
'get_exam' => $this->input->post('exam_group_student_exam_' . $exam_group_student_value),
'note' => $this->input->post('exam_group_student_note_' . $exam_group_student_value),
);
$insert_array[] = $array;
}
}
if ( intval($array['get_ca1'] +$array['get_ca2']+$array['get_ca3']+$array['get_ca4']+$array['get_exam'] ) > 0 ) {
$this->examgroupstudent_model->add_result($insert_array);
}
}
$array = array('status' => '1', 'error' => '', 'message' => $this->lang->line('success_message'));
echo json_encode($array);
}
}
I will like to first get the sum total of get_ca1+get_ca2+get_ca3+get_ca4+get_exam then if it is 0, don't insert.
Please how do I do this?
I don't think you can access the array value on the fly without any workaround, and you've placed the insert outside the foreach.
It would be best if you spent more time on these.
Code Indexing
Use proper IDE. Not like notepad.
Debug all and every line for errors.
Do like this.
Since you're not using batch insert, you can do it one by one.
$cal1 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value);
$cal2 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value);
$cal3 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value);
$cal4 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value);
$exam = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value);
$total = $cal1 + $cal2 + $cal3 + $cal4 + $exam;
$array = array(
'exam_group_class_batch_exam_subject_id' => $this->input->post('exam_group_class_batch_exam_subject_id'),
'exam_group_class_batch_exam_student_id' => $exam_group_student_value,
'attendence' => $attendance,
'get_ca1' => $cal1,
'get_ca2' => $cal2,
'get_ca3' => $cal3,
'get_ca4' => $cal4,
'get_exam' => $exam,
'note' => $this->input->post('exam_group_student_note_' . $exam_group_student_value)
);
if ($total > 0) {
$this->examgroupstudent_model->add_result($array);
}
So final code will be
public function entrymarks()
{
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('exam_group_class_batch_exam_subject_id', 'Subject', 'required|trim|xss_clean');
if ($this->form_validation->run() == false) {
$data = array(
'exam_group_class_batch_exam_subject_id' => form_error('exam_group_class_batch_exam_subject_id'),
);
$array = array('status' => 0, 'error' => $data);
echo json_encode($array);
} else {
$exam_group_student_id = $this->input->post('exam_group_student_id');
$insert_array = array();
$update_array = array();
if (!empty($exam_group_student_id)) {
foreach ($exam_group_student_id as $exam_group_student_key => $exam_group_student_value) {
$attendance_post = $this->input->post('exam_group_student_attendance_' . $exam_group_student_value);
if (isset($attendance_post)) {
$attendance = $this->input->post('exam_group_student_attendance_' . $exam_group_student_value);
} else {
$attendance = "present";
}
$cal1 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value);
$cal2 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value);
$cal3 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value);
$cal4 = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value);
$exam = $this->input->post('exam_group_student_ca1_' . $exam_group_student_value);
$total = $cal1 + $cal2 + $cal3 + $cal4 + $exam;
$array = array(
'exam_group_class_batch_exam_subject_id' => $this->input->post('exam_group_class_batch_exam_subject_id'),
'exam_group_class_batch_exam_student_id' => $exam_group_student_value,
'attendence' => $attendance,
'get_ca1' => $cal1,
'get_ca2' => $cal2,
'get_ca3' => $cal3,
'get_ca4' => $cal4,
'get_exam' => $exam,
'note' => $this->input->post('exam_group_student_note_' . $exam_group_student_value)
);
if ($total > 0) {
$this->examgroupstudent_model->add_result($array);
}
}
}
}
$array = array('status' => '1', 'error' => '', 'message' => $this->lang->line('success_message'));
echo json_encode($array);
}

Students can start exam even when the exam date has not been reached

It turns out that students can actually start an exam even when the exam date is still to the future.
Normally, when a student clicks on the 'start exam' button when it's not time, there is usually a warning message but for some reason, it doesn't work again.
Students should be restricted from being able to start an exam when the date of the exam has not been reached
View
<button type="button" class="btn btn-info questions" data-recordid="<?php echo $exam->id; ?>" data-loading-text="<i class='fa fa-spinner fa-spin'></i> Please wait..."><i class="fa fa-bullhorn"></i> <?php echo $this->lang->line('start') . " " . $this->lang->line('exam') ?></button>
Teacher Controller
public function add() {
$this->form_validation->set_rules('exam', $this->lang->line('exam'), 'trim|required|xss_clean');
$this->form_validation->set_rules('attempt', $this->lang->line('attempt'), 'trim|required|xss_clean');
$this->form_validation->set_rules('exam_from', $this->lang->line('exam') . " " . $this->lang->line('from'), 'trim|required|xss_clean');
$this->form_validation->set_rules('exam_to', $this->lang->line('exam') . " " . $this->lang->line('to'), 'trim|required|xss_clean');
$this->form_validation->set_rules('duration', $this->lang->line('duration'), 'trim|required|xss_clean');
$this->form_validation->set_rules('description', $this->lang->line('description'), 'trim|required|xss_clean');
$this->form_validation->set_rules('passing_percentage', $this->lang->line('percentage'), 'trim|required|xss_clean');
if ($this->form_validation->run() == false) {
$msg = array(
'exam' => form_error('exam'),
'attempt' => form_error('attempt'),
'exam_from' => form_error('exam_from'),
'duration' => form_error('duration'),
'exam_to' => form_error('exam_to'),
'description' => form_error('description'),
'passing_percentage' => form_error('passing_percentage'),
);
$array = array('status' => 0, 'error' => $msg, 'message' => '');
} else {
$is_active = 0;
$publish_result = 0;
if (isset($_POST['is_active'])) {
$is_active = 1;
}
if (isset($_POST['publish_result'])) {
$publish_result = 1;
}
$idd = $this->session->userdata('admin');
$insert_data = array(
'exam' => $this->input->post('exam'),
'attempt' => $this->input->post('attempt'),
'exam_from' => date('Y-m-d', $this->customlib->datetostrtotime($this->input->post('exam_from'))),
'exam_to' => date('Y-m-d', $this->customlib->datetostrtotime($this->input->post('exam_to'))),
'duration' => $this->input->post('duration'),
'description' => $this->input->post('description'),
'session_id' => $this->setting_model->getCurrentSession(),
'is_active' => $is_active,
'publish_result' => $publish_result,
'passing_percentage' => $this->input->post('passing_percentage'),
'teacher_id' => $idd['id'],
);
$id = $this->input->post('recordid');
if ($id != 0) {
$insert_data['id'] = $id;
}
$this->onlineexam_model->add($insert_data);
$array = array('status' => 1, 'error' => '', 'message' => $this->lang->line('success_message'));
}
echo json_encode($array);
}
user controller
public function startexam____($id) {
$data = array();
$this->session->set_userdata('top_menu', 'Hostel');
$this->session->set_userdata('sub_menu', 'hostel/index');
$questionOpt = $this->customlib->getQuesOption();
$data['questionOpt'] = $questionOpt;
$onlineexam_question = $this->onlineexam_model->getExamQuestions($id);
$data['examquestion'] = $onlineexam_question;
$this->load->view('layout/student/header');
$this->load->view('user/onlineexam/startexam', $data);
$this->load->view('layout/student/footer');
}
public function getExamForm() {
$data = array();
$question_status = 0;
$recordid = $this->input->post('recordid');
$exam = $this->onlineexam_model->get($recordid);
$data['questions'] = $this->onlineexam_model->getExamQuestions($recordid);
$student_current_class = $this->customlib->getStudentCurrentClsSection();
$student_session_id = $student_current_class->student_session_id;
$onlineexam_student = $this->onlineexam_model->examstudentsID($student_session_id, $exam->id);
$data['onlineexam_student_id'] = $onlineexam_student;
$getStudentAttemts = $this->onlineexam_model->getStudentAttemts($onlineexam_student->id);
$data['question_status'] = 0;
if (strtotime(date('Y-m-d H:i:s')) >= strtotime(date($exam->exam_to . ' 23:59:59'))) {
$question_status = 1;
$data['question_status'] = 1;
} else if ($exam->attempt > $getStudentAttemts) {
$this->onlineexam_model->addStudentAttemts(array('onlineexam_student_id' => $onlineexam_student->id));
} else {
$question_status = 1;
$data['question_status'] = 1;
}
$questionOpt = $this->customlib->getQuesOption();
$data['questionOpt'] = $questionOpt;
$pag_content = $this->load->view('user/onlineexam/_searchQuestionByExamID', $data, true);
echo json_encode(array('status' => 0, 'exam' => $exam, 'page' => $pag_content, 'question_status' => $question_status));
}

When i try to sell the item from warehouse 1 where i have 43 quantity in stock it shows out of stock

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

Codeigniter Uploading excel and Saving to database (Network Error (tcp_error))

Really need your support on this one.
This works on intranet not until we decided to upload it on public.
Im using Codeigniter + SQL Server + Apache
This how it should work:
upload the excel file, read the content, save to database and send an email & sms.
But:
Everytime I upload the excel file after 3 Mins it stops and got this error written on Developer Opt->Network Tab:
"Network Error (tcp_error)
A communication error occurred: ""
The Web Server may be down, too busy, or experiencing other problems preventing it from responding to requests. You may wish to try again at a later time."
Here's my code:
public function do_upload()
{
set_time_limit(0);
ignore_user_abort(1);
$accID = $this->input->get('acc');
$rmi = $this->input->get('rmi');
$spInst = $this->input->get('spInst');
$dateReq = '';
$dateReqq = $this->input->get('dateReq');
if($dateReqq==null or $dateReqq==''){
$dateReq = date('Y-m-d');
}else{
$dateReq = $this->input->get('dateReq');
}
$dateNow = date("F_d_Y__h_i_s__A");
$status = "";
$msg = "";
$file_element_name = 'file';
$file_name = '';
if ($status != "error")
{
$config['upload_path'] = 'c:/xampp/htdocs/eDR/assets/uploads/';
$config['allowed_types'] = 'xlsx';
$config['max_size'] = 60000;
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$config['file_name'] = uniqid('file')."_". $dateNow;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$status = FALSE;
$msg = $this->upload->display_errors('', '');
}
else
{
$data = $this->upload->data();
//$file_id = $this->files_model->insert_file($data['file_name'], $_POST['title']);
//if($file_id)
//{
$file_name = $data['file_name'];
$file = "c:/xampp/htdocs/eDR/assets/uploads/" . $file_name;
$this->do_read($file,$accID,$rmi,$spInst,$dateReq);
$status = TRUE;
$msg = "File successfully uploaded";
//}
//else
// {
// unlink($data['full_path']);
// $status = "error";
// $msg = "Something went wrong when saving the file, please try again.";
// }
}
#unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg, 'name' => $file_name));
}
public function do_read($file,$accID,$rmi,$spInst,$dateReq){
//load the excel library
$this->load->library('excel');
//read file from path
$objPHPExcel = PHPExcel_IOFactory::load($file);
//get only the Cell Collection
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
//extract to a PHP readable array format
foreach ($cell_collection as $cell) {
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
//header will/should be in row 1 only. of course this can be modified to suit your need.
//if ($row == 1) {
// $header[$row][$column] = $data_value;
//} else {
$arr_data[$row][$column] = $data_value;
//}
}
//send the data in an array format
//$data['header'] = $header;
$drCount = ($this->up->get_DRcount($accID));
$date = date("F d, Y h:i: s A");
$data['values'] = $arr_data;
$last = count($arr_data) - 1;
$totalQty = 0;
$abbr = $this->up->get_Abbr($accID);
$TATnAGING = '';
$dAdd ='';
$posReq='';
$reqD;
foreach ($arr_data as $i => $row)
{
if( empty($row['B']) or
empty($row['C']) or
empty($row['D']) or
empty($row['E']) or
empty($row['F']) or
empty($row['G']) or
empty($row['H']) or
empty($row['I']) or
empty($row['J']) or
empty($row['K'])
){
$msg = 'B = ' . $row['B'] . ' C = ' . $row['C'] . ' D = ' . $row['D'] . ' E = ' . $row['E'] . ' F = ' . $row['F'] . ' G = ' . $row['G'] . ' H = ' . $row['H'] . ' I = ' . $row['I']
. ' J = ' . $row['J'] . ' K = ' . $row['K'] ;
$status = FALSE;
echo json_encode(array('status' => $status, 'msg'=>$msg));
exit();
}
}
foreach ($arr_data as $i => $row)
{
try {
$reqDatee = date('F d, Y', strtotime($dateReq));
$start = new DateTime( $reqDatee );
$end = new DateTime(date("F d, Y"));
$oneday = new DateInterval("P1D");
$days = array();
$data1 = "7.5";
foreach(new DatePeriod($start, $oneday, $end->add($oneday)) as $day) {
$day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
if($day_num < 6) { /* weekday */
$days[$day->format("Y-m-d")] = $data1;
}
}
$TATnAGING = count($days). ' day/s';
$dAdd = trim(strtoupper($row['D']));
$posReq = trim(strtoupper($row['B']));
$reqD = $dateReq;
$isFirst = ($i == 0);
$isLast = ($i == $last);
$id = $this->session->userdata('username');
$totalQty += $row['G'];
} catch (Exception $e) {
$msg = 'Caught exception: '. $e->getMessage(). "\n";
$status = FALSE;
echo json_encode(array('status' => $status, 'error'=>$msg));
exit();
}
if($i>1){
$data1 = array();
try {
if(trim(strtoupper($row['B']))=='YES' or trim(strtoupper($row['B']))=='Y'){
$data1 = array(
"drRef" => $abbr . '2017' . sprintf("%07d", ($drCount + 1)),
"postReq" => trim(strtoupper($row['B'])),
"reqDate" => $dateReq,
"reqBy" => trim(strtoupper($row['C'])),
"deliveryAcc" => trim(strtoupper($row['D'])),
"matCode" => trim(strtoupper($row['E'])),
"matDescription" => trim(strtoupper($row['F'])),
"qty" => $row['G'],
"UOM" => trim(strtoupper($row['H'])),
"location" => trim(strtoupper($row['I'])),
"postRef" => '',
// "postDate" => date("F d, Y h:i:s A"),
// "postBy" => $this->session->userdata['name'],
"status" => 'PENDING FOR POSTING',
// "TAT" => trim(strtoupper($row['O'])),
// "AGING" => trim(strtoupper($row['P'])),
"userID" => $id,
'addedBy' => $this->session->userdata('name'),
'addedUsing' => gethostbyaddr($_SERVER['REMOTE_ADDR']),
'dateAdded' => $date,
'seqNo' => uniqid(),
'accID' => $accID,
'fromIMEI' => trim(strtoupper($row['J'])),
'toIMEI' => trim(strtoupper($row['K'])),
);
}else{
$data1 = array(
"drRef" => $abbr .'2017' . sprintf("%07d", ($drCount + 1)),
"postReq" => trim(strtoupper($row['B'])),
"reqDate" => $dateReq,
"reqBy" => trim(strtoupper($row['C'])),
"deliveryAcc" => trim(strtoupper($row['D'])),
"matCode" => trim(strtoupper($row['E'])),
"matDescription" => trim(strtoupper($row['F'])),
"qty" => $row['G'],
"UOM" => trim(strtoupper($row['H'])),
"location" => trim(strtoupper($row['I'])),
"postRef" => '',
"postDate" => date("F d, Y h:i:s A"),
"postBy" => $this->session->userdata['name'],
"status" => 'POSTED',
"TAT" => $TATnAGING,
"userID" => $id,
'addedBy' => $this->session->userdata('name'),
'addedUsing' => gethostbyaddr($_SERVER['REMOTE_ADDR']),
'dateAdded' => $date,
'seqNo' => uniqid(),
'accID' => $accID,
'fromIMEI' => trim(strtoupper($row['J'])),
'toIMEI' => trim(strtoupper($row['K'])),
);
}
} catch (Exception $e) {
$msg = 'Caught exception: '. $e->getMessage(). "\n";
$status = FALSE;
echo json_encode(array('status' => $status, 'error'=>$msg));
exit;
}
$insert = $this->up->save($data1);
$data1 = array();
}
}
if($posReq=='YES' or $posReq=='Y'){
$data1 = array(
'drRef' => $abbr . '2017' . sprintf("%07d", ($drCount + 1)),
'accID' => $accID,
'userID' => $this->session->userdata['id'],
// 'postRef' => trim(strtoupper($row['K'])),
// 'postBy' => $this->session->userdata['name'],
// 'postDate' => $date,
'totQty' => $totalQty,
'status' => 'PENDING FOR POSTING',
'isPosted' => 'No',
'isApproved' => 'Pending',
'approverID' => $this->session->userdata('head'),
'postReq' => $posReq,
'reqDate' => $reqD,
'deliveryAdd' => $dAdd,
'reason' => urldecode($rmi),
'spInst' => urldecode($spInst),
);
}else{
$data1 = array(
'drRef' => $abbr . '2017' . sprintf("%07d", ($drCount + 1)),
'accID' => $accID,
'userID' => $this->session->userdata['id'],
//'postRef' => $this->session->userdata('username'),
'postBy' => $this->session->userdata['name'],
'postDate' => $date,
'totQty' => $totalQty,
'status' => 'POSTED',
'isPosted' => 'Yes',
'isApproved' => 'Pending',
'approverID' => $this->session->userdata('head'),
'postReq' => $posReq,
'tat' => $TATnAGING ,
'reqDate' => $reqD,
'deliveryAdd' => $dAdd,
'reason' => urldecode($rmi),
'spInst' => urldecode($spInst),
);
}
$insert = $this->up->saveOrder($data1);
$drRef = $abbr . '2017' . sprintf("%07d", ($drCount + 1));
$id = $this->up->get_Data('head','tblUser','userID',$this->session->userdata('id'));
$recepient = $this->up->get_Data('email','tblUser','userID',$id);
$name = $this->up->get_Data('name','tblUser','userID',$id);
$config = Array(
'protocol' => 'smtp',
'smtp_host' => '182.50.151.61',
'smtp_port' => 587,
'smtp_user' => 'user',
'smtp_pass' => 'pass',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
// Set to, from, message, etc.
$this->email->from('eDR#domain.com', 'e - Delivery Receipt');
$this->email->to($recepient);
//$this->email->subject('eDR Notifications');
$this->email->subject('eDR Notification < DR Request >');
$message = 'Message';
$this->email->message($message);
$result = $this->email->send();
// if (!$result) {
// $this->email->print_debugger();
// }
$receiver = $this->up->get_Data('phoneNum','tblUser','userID',$this->session->userdata('head'));
$sms = array(
'receiver' => $receiver,
'msg' => 'message',
'status' => 'Send',
);
$this->up->sendSMS($sms);
}
Thanks.
I solved this problem via CRON job or calling cmd command on my PHP script so that it will execute the query on server itself really fast. :)

Undefined index: sub

I have problem with upload field. Error page image
Actualy when I add upload field to form script gives an error.
The server gives an error for this line: $filenamefields[$group]['sub']
foreach ($fields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active']) {
$min_req = true;
if (isset($fieldlist['sub'])) {
$this->customrule_addrec(
$fieldlist['sub'],
$required, $title,
$type,
$gprefix.'[' . $group . '][sub]',
$filenamefields[$group]['sub'],
$filetypefields[$group]['sub'],
$filetmpnamefields[$group]['sub'],
$fileerrorfields[$group]['sub'],
$filesizefields[$group]['sub']);
and this line: $this->files['size']['fields']);
$min_req = $this->customrule_addrec($fields, $required, $title, $type, '',
$this->files['name']['fields'],
$this->files['type']['fields'],
$this->files['tmp_name']['fields'],
$this->files['error']['fields'],
$this->files['size']['fields']);
if (!$min_req)
$this->addError($attribute, 'Select a group');
file codes :
<?php
class Orders extends CActiveRecord
{
public $fields;
public $files;
public $file;
public $remove;
public function tableName()
{
return 'orders';
}
public function rules()
{
return array(
array(
'name, start_date, ordertype, user',
'required'
),
array(
'status, ordertype, user',
'numerical',
'integerOnly' => true
),
array(
'name',
'length',
'max' => 200
),
array(
'finish_date, desc',
'safe'
),
array(
'id, name, start_date, finish_date, status, ordertype, user, desc',
'safe',
'on' => 'search'
),
array(
'fields,files',
'safe'
),
array(
'fields',
'customrule_add',
'on' => 'add'
),
array(
'fields',
'customrule_edit',
'on' => 'edit'
),
array(
'file, remove',
'safe',
'on' => 'answer'
)
);
}
public function customrule_add($attribute, $params)
{
$fieldtypes = Orderfield::model()->findAll('ordergroup in (select id from ' . Ordergroup::model()->tableName() . ' where orderform = \'' . $this->ordertype . '\')');
$required = CHtml::listData($fieldtypes, 'id', 'required');
$title = CHtml::listData($fieldtypes, 'id', 'name');
$type = CHtml::listData($fieldtypes, 'id', 'type');
$fields = $this->$attribute;
$min_req = $this->customrule_addrec($fields, $required, $title, $type, '',
$this->files['name']['fields'],
$this->files['type']['fields'],
$this->files['tmp_name']['fields'],
$this->files['error']['fields'],
$this->files['size']['fields']);
if (!$min_req)
$this->addError($attribute, 'Select a group');
}
private function customrule_addrec($fields, $required, $title, $type, $gprefix, $filenamefields, $filetypefields, $filetmpnamefields, $fileerrorfields, $filesizefields)
{
$min_req = false;
foreach ($fields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active']) {
$min_req = true;
if (isset($fieldlist['sub'])) {
$this->customrule_addrec(
$fieldlist['sub'],
$required, $title,
$type,
$gprefix.'[' . $group . '][sub]',
$filenamefields[$group]['sub'],
$filetypefields[$group]['sub'],
$filetmpnamefields[$group]['sub'],
$fileerrorfields[$group]['sub'],
$filesizefields[$group]['sub']);
foreach ($fieldlist['sub'] as $sgroup => $sfieldlist) {
if (isset($sfieldlist['active']) && $sfieldlist['active']) {
foreach ($sfieldlist as $key => $value) {
if (($key != 'active') && ($key != 'sub') && $required[$key]) {
if ($type[$key] != 2) {
if (!$value)
$this->addError('fields[' . $group . '][sub][' . $sgroup . '][' . $key . ']', 'Value ' . $title[$key] . ' Can not be empty');
} else if (!isset($this->files['name']['fields'][$group]['sub'][$sgroup][$key]) || !$this->files['name']['fields'][$group]['sub'][$sgroup][$key]) {
$this->addError('fields[' . $group . '][sub][' . $sgroup . '][' . $key . ']', 'File ' . $title[$key] . ' Must send');
}
}
}
}
}
}
foreach ($fieldlist as $key => $value) {
if (($key != 'active') && ($key != 'sub') && $required[$key]) {
if ($type[$key] != 2) {
if (!$value)
$this->addError('fields' . $gprefix . '[' . $group . '][' . $key . ']', 'Value ' . $title[$key] . ' Can not be empty');
} else if (!isset($filenamefields[$group][$key]) || !$filenamefields[$group][$key]) {
$this->addError('fields' . $gprefix . '[' . $group . '][' . $key . ']', 'File ' . $title[$key] . ' Must send');
}
}
}
}
}
return $min_req;
}
public function customrule_edit($attribute, $params)
{
$fieldtypes = Orderfield::model()->findAll('ordergroup in (select id from ' . Ordergroup::model()->tableName() . ' where orderform = \'' . $this->ordertype . '\')');
$required = CHtml::listData($fieldtypes, 'id', 'required');
$title = CHtml::listData($fieldtypes, 'id', 'name');
$type = CHtml::listData($fieldtypes, 'id', 'type');
$groups = CHtml::listData(Ordergroup::model()->findAll(array(
'select' => 'id,name,orderform',
'condition' => 'orderform = \'' . $this->ordertype . '\''
)), 'id', 'name');
$fields = $this->$attribute;
$min_req = false;
foreach ($fields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active']) {
$min_req = true;
if (isset($fieldlist['sub'])) {
foreach ($fieldlist['sub'] as $sgroup => $sfieldlist) {
if (isset($sfieldlist['active']) && $sfieldlist['active']) {
foreach ($sfieldlist as $key => $value) {
if (($key != 'active') && ($key != 'sub') && $required[$key]) {
if ($type[$key] != 2) {
if (!$value)
$this->addError('fields[' . $group . '][sub][' . $sgroup . '][' . $key . ']', 'value ' . $title[$key] . ' Can not be empty');
}
}
}
}
}
}
foreach ($fieldlist as $key => $value) {
if (($key != 'active') && $required[$key]) {
if ($type[$key] != 2) {
if (!$value)
$this->addError('fields[' . $group . '][' . $key . ']', 'value ' . $title[$key] . 'Can not be empty');
}
}
}
}
}
if (!$min_req)
$this->addError($attribute, 'Choose a group');
}
public function add()
{
$name = $this->name;
$exists = Orders::model()->exists('`name` = \'' . $name . '\'');
if ($exists) {
$count = Orders::model()->count('`name` regexp \'^' . $name . ' - [0-9]+$\'');
$this->name = $name . ' - ' . ($count + 2);
}
$status = $this->save();
$status = $this->addsub(
$this->fields,
$status,
$this->files['name']['fields'],
$this->files['type']['fields'],
$this->files['tmp_name']['fields'],
$this->files['error']['fields'],
$this->files['size']['fields']
);
if (!$status) {
Ordervalues::model()->deleteAllByAttributes(array(
'order' => $this->id
));
GroupOfOrder::model()->deleteAllByAttributes(array(
'order' => $this->id
));
$this->delete();
return false;
}
return true;
}
private function addsub($thisfields, $status, $filenamefields, $filetypefields, $filetmpnamefields, $fileerrorfields, $filesizefields)
{
foreach ($thisfields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active'] && $status) {
$gofo = new GroupOfOrder('insert');
$gofo->group = $group;
$gofo->order = $this->id;
$gofo->save();
if (isset($fieldlist['sub'])) {
$status = $this->addsub(
$fieldlist['sub'],
$status,
$filenamefields[$group]['sub'],
$filetypefields[$group]['sub'],
$filetmpnamefields[$group]['sub'],
$fileerrorfields[$group]['sub'],
$filesizefields[$group]['sub']
);
if(!$status)
return false;
}
foreach ($fieldlist as $key => $value) {
if ($key != 'active' && $key != 'sub' && $status) {
$ftype = Orderfield::model()->findByPk($key);
if (!$ftype) {
$this->addError('fields', 'Field type error');
Ordervalues::model()->deleteAllByAttributes(array(
'order' => $this->id
));
GroupOfOrder::model()->deleteAllByAttributes(array(
'order' => $this->id
));
$this->delete();
return false;
}
if (!empty($value)) {
$field = new Ordervalues('insert');
$field->field = $key;
$field->order = $this->id;
$field->value = $value;
$status = ($status && $field->save());
} elseif (isset($filenamefields[$group][$key]) && !empty($filenamefields[$group][$key])) {
$file = new CUploadedFile($filenamefields[$group][$key], $filetmpnamefields[$group][$key], $filetypefields[$group][$key], $filesizefields[$group][$key], $fileerrorfields[$group][$key]);
if ($ftype->file_type) {
$all = explode("|", $ftype->file_type); // check every allowed extensions with uploaded file
$allowed = false;
foreach ($all as $ex) {
if ($ex == $file->extensionName) {
$allowed = true;
break;
}
}
if (!$allowed) {
$this->addError('files', 'This format' . $file->extensionName . 'is not true');
Ordervalues::model()->deleteAllByAttributes(array(
'order' => $this->id
));
GroupOfOrder::model()->deleteAllByAttributes(array(
'order' => $this->id
));
$this->delete();
return false;
}
}
$ffield = new Ordervalues('insert');
$ffield->field = $key;
$ffield->order = $this->id;
$ffield->value = $file->name;
$ffield->file_size = $file->size;
$status = ($status && $ffield->save());
$status = ($status && $file->saveAs('files/' . $ffield->id));
}
}
}
}
}
return true;
}
public function edit()
{
$status = true;
foreach ($this->fields as $group => $fieldlist) {
if (isset($fieldlist['active']) && $fieldlist['active']) {
$gofo = GroupOfOrder::model()->findByAttributes(array(
'order' => $this->id,
'group' => $group
));
if (!$gofo) {
$gofo = new GroupOfOrder('insert');
$gofo->group = $group;
$gofo->order = $this->id;
$gofo->save();
}
if (isset($fieldlist['sub'])) {
foreach ($fieldlist['sub'] as $sgroup => $sfieldlist) {
if (isset($sfieldlist['active']) && $sfieldlist['active']) {
$sgofo = GroupOfOrder::model()->findByAttributes(array(
'order' => $this->id,
'group' => $sgroup
));
if (!$sgofo) {
$sgofo = new GroupOfOrder('insert');
$sgofo->group = $sgroup;
$sgofo->order = $this->id;
$sgofo->save();
}
foreach ($sfieldlist as $key => $value) {
if ($key != 'active' && $key != 'sub' && $status) {
$ftype = Orderfield::model()->findByPk($key);
if (!$ftype) {
$this->addError('fields', 'Field type error');
return false;
}
if (!empty($value)) {
$field = Ordervalues::model()->findByAttributes(array(
'order' => $this->id,
'field' => $key
));
if (!$field) {
$field = new Ordervalues('insert');
$field->field = $key;
$field->order = $this->id;
}
$field->value = $value;
$status = ($status && $field->save());
} elseif (isset($this->files['name']['fields'][$group]['sub'][$sgroup][$key]) && !empty($this->files['name']['fields'][$group]['sub'][$sgroup][$key])) {
$file = new CUploadedFile($this->files['name']['fields'][$group]['sub'][$sgroup][$key], $this->files['tmp_name']['fields'][$group]['sub'][$sgroup][$key], $this->files['type']['fields'][$group]['sub'][$sgroup][$key], $this->files['size']['fields'][$group]['sub'][$sgroup][$key], $this->files['error']['fields'][$group]['sub'][$sgroup][$key]);
if ($ftype->file_type) {
$all = explode("|", $ftype->file_type); // check every allowed extensions with uploaded file
$allowed = false;
foreach ($all as $ex) {
if ($ex == $file->extensionName) {
$allowed = true;
break;
}
}
if (!$allowed) {
$this->addError('files', 'This format ' . $file->extensionName . ' is not true');
return false;
}
}
$ffield = Ordervalues::model()->findByAttributes(array(
'order' => $this->id,
'field' => $key
));
if (!$ffield) {
$ffield = new Ordervalues('insert');
$ffield->field = $key;
$ffield->order = $this->id;
}
$ffield->value = $file->name;
$ffield->file_size = $file->size;
$status = ($status && $ffield->save());
$status = ($status && $file->saveAs('files/' . $ffield->id));
}
}
}
}
}
}
foreach ($fieldlist as $key => $value) {
if ($key != 'active' && $key != 'sub' && $status) {
$ftype = Orderfield::model()->findByPk($key);
if (!$ftype) {
$this->addError('fields', 'Field error');
return false;
}
if (!empty($value)) {
$field = Ordervalues::model()->findByAttributes(array(
'order' => $this->id,
'field' => $key
));
if (!$field) {
$field = new Ordervalues('insert');
$field->field = $key;
$field->order = $this->id;
}
$field->value = $value;
$status = ($status && $field->save());
} elseif (isset($this->files['name']['fields'][$group][$key]) && !empty($this->files['name']['fields'][$group][$key])) {
$file = new CUploadedFile($this->files['name']['fields'][$group][$key], $this->files['tmp_name']['fields'][$group][$key], $this->files['type']['fields'][$group][$key], $this->files['size']['fields'][$group][$key], $this->files['error']['fields'][$group][$key]);
if ($ftype->file_type) {
$all = explode("|", $ftype->file_type); // check every allowed extensions with uploaded file
$allowed = false;
foreach ($all as $ex) {
if ($ex == $file->extensionName) {
$allowed = true;
break;
}
}
if (!$allowed) {
$this->addError('files', 'This format ' . $file->extensionName . ' is not true');
return false;
}
}
$ffield = Ordervalues::model()->findByAttributes(array(
'order' => $this->id,
'field' => $key
));
if (!$ffield) {
$ffield = new Ordervalues('insert');
$ffield->field = $key;
$ffield->order = $this->id;
}
$ffield->value = $file->name;
$ffield->file_size = $file->size;
$status = ($status && $ffield->save());
$status = ($status && $file->saveAs('files/' . $ffield->id));
}
}
}
} else {
$gofo = GroupOfOrder::model()->findByAttributes(array(
'order' => $this->id,
'group' => $group
));
if ($gofo) {
$gofo->delete();
$ovs = Ordervalues::model()->findAll('order = ' . $this->id . ' AND field in (select id from ' . Orderfield::model()->tableName() . ' where ordergroup=' . $group . ')');
foreach ($ovs as $ov) {
if ($ov->field0->type == 2)
unlink(Yii::app()->getBasePath() . '/../files/' . $ov->id);
$ov->delete();
}
}
}
}
$status = ($status && $this->save());
return $status;
}
public function answer()
{
if ($this->remove) {
foreach ($this->remove as $id => $f) {
if ($f) {
$filemodel = Orderfiles::model()->findByAttributes(array(
'id' => $id,
'order_id' => $this->id
));
if ($filemodel) {
$filemodel->delete();
$path = Yii::app()->basePath . '/../files/answers/' . $id;
if (file_exists($path))
unlink($path);
}
}
}
}
$file = CUploadedFile::getInstance($this, 'file');
if ($file) {
$fm = new Orderfiles('insert');
$fm->name = $file->name;
$fm->size = $file->size;
$fm->order_id = $this->id;
if ($fm->save() && $this->save())
return $file->saveAs('files/answers/' . $fm->id);
return false;
}
return $this->save();
}
public function fill_in_fields()
{
$this->fields = array();
foreach ($this->ordervalues as $field) {
$f = $field->field0;
if (!isset($this->fields[$f->ordergroup]['active']))
$this->fields[$f->ordergroup]['active'] = true;
$this->fields[$f->ordergroup][$f->id] = $field->value;
}
}
public function getPrice()
{
return Yii::app()->db->createCommand('select sum(price) from ' . Ordergroup::model()->tableName() . ' where id in (select `group` from ' . GroupOfOrder::model()->tableName() . ' where `order` = ' . $this->id . ')')->queryScalar();
}
public function deleteTree()
{
$ovsff = Ordervalues::model()->findAll('`order` = ' . $this->id . ' AND field in (select id from ' . Orderfield::model()->tableName() . ' where type = 2)');
if ($ovsff) {
foreach ($ovsff as $value) {
$path = Yii::app()->getBasePath() . '/../files/' . $value->id;
if (file_exists($path))
unlink($path);
}
}
Ordervalues::model()->deleteAll('`order` = ' . $this->id);
GroupOfOrder::model()->deleteAll('`order` = ' . $this->id);
$status = true;
$ovsff = Orderfiles::model()->findAll('`order_id` = ' . $this->id); // files of answered orders
if ($ovsff) {
foreach ($ovsff as $value) {
$path = Yii::app()->getBasePath() . '/../files/answers/' . $value->id;
if (file_exists($path))
unlink($path);
$status = $status && $value->delete();
}
}
$trans = $this->trackCode;
$status = $this->delete();
$trans->delete();
return $status;
}
public function relations()
{
return array(
'orderfiles' => array(
self::HAS_MANY,
'Orderfiles',
'order_id'
),
'ordertype0' => array(
self::BELONGS_TO,
'Orderform',
'ordertype'
),
'trackCode' => array(
self::BELONGS_TO,
'Transaction',
'track_code'
),
'user0' => array(
self::BELONGS_TO,
'Users',
'user'
),
'ordervalues' => array(
self::HAS_MANY,
'Ordervalues',
'order'
),
'tickets' => array(
self::HAS_MANY,
'Ticket',
'order_id'
)
);
}
public function attributeLabels()
{
return array(
'id' => 'Code',
'name' => 'Name',
'start_date' => 'Date',
'finish_date' => 'End Date',
'status' => 'status',
'ordertype' => 'Type',
'user' => 'User',
'track_code' => 'Pay code',
'desc' => 'Description',
'file' => 'File'
);
}
public function getStatus()
{
$status = array(
0 => 'Waiting for pay',
1 => 'In progress',
2 => 'Completed',
3 => 'Draft'
);
return $status[$this->status];
}
public function getButton()
{
$status = array(
0 => 'Waiting for pay',
1 => 'In progress',
2 => 'Completed',
4 => 'Draft'
);
if ($this->status == 0) {
return CHtml::button('Pay', array(
'onclick' => 'window.location.href=\'' . Yii::app()->createUrl('financial/invoice', array(
'id' => $this->track_code
)) . '\''
));
}
return CHtml::button('Details', array(
'onclick' => 'window.location.href=\'' . Yii::app()->createUrl('service/order', array(
'id' => $this->id
)) . '\''
));
}
public function search()
{
$criteria = new CDbCriteria();
$criteria->compare('id', $this->id);
$criteria->compare('name', $this->name, true);
$criteria->compare('start_date', $this->start_date, true);
$criteria->compare('finish_date', $this->finish_date, true);
$criteria->compare('status', $this->status);
$criteria->compare('ordertype', $this->ordertype);
$criteria->compare('user', $this->user);
$criteria->compare('track_code', $this->track_code);
$criteria->compare('desc', $this->desc, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria
));
}
public static function model($className = __CLASS__)
{
return parent::model($className);
}
}

Categories