ICS modules
This commit is contained in:
@@ -77,4 +77,15 @@
|
||||
/* Ensure the link itself is styled correctly when not active */
|
||||
.page-item-secondary .page-link {
|
||||
color: var(--bs-secondary);
|
||||
}
|
||||
|
||||
.card-loader-overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: rgba(255, 255, 255, 0.85);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 2;
|
||||
border-radius: inherit;
|
||||
}
|
||||
+127
-1
@@ -115,6 +115,111 @@ $(function () {
|
||||
|
||||
});
|
||||
|
||||
|
||||
$('input.contact_search').each(function (i, el) {
|
||||
|
||||
var $el = $(el);
|
||||
$el.autocomplete({
|
||||
|
||||
// Fetch data from server
|
||||
source: function (request, response) {
|
||||
|
||||
// Abort previous request (prevent multiple firing)
|
||||
if ($el.data('xhr')) {
|
||||
$el.data('xhr').abort();
|
||||
}
|
||||
|
||||
// Prepare payload
|
||||
let q = prepare_form_data(0, true);
|
||||
q['keyword'] = request.term;
|
||||
let json = JSON.stringify(q);
|
||||
|
||||
// Send AJAX request
|
||||
var xhr = $.ajax({
|
||||
url: server_url + 'ics/api/engine/contact_search.php',
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: { json: json },
|
||||
// for CSRF validation
|
||||
headers: {
|
||||
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
|
||||
},
|
||||
|
||||
success: function (res) {
|
||||
|
||||
var aca = [];
|
||||
|
||||
// Map result to autocomplete format
|
||||
$.each(res.result, function (i, item) {
|
||||
|
||||
var temp = "";
|
||||
temp += "<div class='contact-result-item' style='font-family:\"Poppins\",sans-serif;padding:4px 0;'>";
|
||||
temp += "<div style='font-size:10px;text-transform:uppercase;color:#E66239;font-weight:600;line-height:1.2;'>";
|
||||
temp += "Tax ID: " + (item.tax_id || 'N/A');
|
||||
temp += "</div>";
|
||||
temp += "<div style='font-size:13px;font-weight:500;color:#171717;margin-top:2px;'>";
|
||||
temp += item.contact_name;
|
||||
temp += "</div>";
|
||||
temp += "</div>";
|
||||
|
||||
aca.push({
|
||||
label: temp, // HTML dropdown
|
||||
value: item.contact_name, // Default value
|
||||
data: item // Full object
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
response(aca);
|
||||
}
|
||||
});
|
||||
|
||||
// Save request reference
|
||||
$el.data('xhr', xhr);
|
||||
},
|
||||
|
||||
minLength: 0,
|
||||
delay: 300,
|
||||
|
||||
// When selecting item
|
||||
select: function (e, ui) {
|
||||
|
||||
if (ui.item && ui.item.data) {
|
||||
|
||||
var contact = ui.item.data;
|
||||
|
||||
// Replace input value with SKU
|
||||
$(this)
|
||||
.val(contact.contact_name)
|
||||
.attr("data-id", contact.id)
|
||||
.attr("secondary", contact.contact_name);
|
||||
|
||||
console.log("Input updated with contact name:", contact.contact_name);
|
||||
|
||||
return false; // Prevent overwrite by default value
|
||||
}
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
// Allow HTML rendering in dropdown
|
||||
.data("ui-autocomplete")._renderItem = function (ul, item) {
|
||||
return $("<li>")
|
||||
.append($("<div>").html(item.label))
|
||||
.appendTo(ul);
|
||||
};
|
||||
|
||||
// Add this ↓
|
||||
$el.on('blur', function () {
|
||||
var secondary = $(this).attr('secondary');
|
||||
console.log($(this).attr('data-id'))
|
||||
if (secondary) {
|
||||
$('input#contact').val($('input#contact').attr('secondary'));
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
@@ -198,7 +303,7 @@ function ajax_request(options) {
|
||||
isAjaxProcessing = false;
|
||||
return Promise.reject("validation_failed");
|
||||
}
|
||||
|
||||
|
||||
if(options.data){
|
||||
Object.entries(options.data).forEach(([key, value]) => {
|
||||
payloadJson[key] = value;
|
||||
@@ -400,3 +505,24 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Helper function to format date strings (assuming input is in ISO format)
|
||||
*/
|
||||
function format_date(iso_string) {
|
||||
var split = iso_string.split(" ");
|
||||
if (split.length === 2) {
|
||||
var datePart = split[0].split("-");
|
||||
}
|
||||
return (datePart) ? `${datePart[2]}/${datePart[1]}/${datePart[0]} ${split[1]}` : iso_string;
|
||||
}
|
||||
|
||||
function format_number(value, decimal) {
|
||||
var n = Number(value);
|
||||
if (isNaN(n)) return '--';
|
||||
if (decimal !== undefined) n = n.toFixed(decimal);
|
||||
var parts = n.toString().split('.');
|
||||
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
|
||||
return parts.join('.');
|
||||
}
|
||||
@@ -57,7 +57,11 @@ function db_check($sth, &$answer, $options = []) {
|
||||
$log_message = $options['log'] ?? "DB Error";
|
||||
error_log($log_message . " in " . $trace['file'] . " line " . $trace['line'] . ": " . $sth->errorInfo()[2]);
|
||||
|
||||
// production version
|
||||
$answer["message"] = $options['message'] ?? "A server error occurred. Please try again.";
|
||||
|
||||
// development version
|
||||
$answer["message"] = $sth->errorInfo()[2];
|
||||
|
||||
http_response_code($options['code'] ?? 500);
|
||||
|
||||
@@ -148,6 +152,7 @@ if(!empty($_SESSION["login_company_id"])){
|
||||
|
||||
$company_id = (int)$_SESSION["login_company_id"];
|
||||
$user_id = (int)$_SESSION["login_user_id"];
|
||||
$uuid = bin2hex(random_bytes(16));
|
||||
|
||||
// create json for table logging
|
||||
$logging = array(
|
||||
@@ -158,4 +163,271 @@ if(!empty($_SESSION["login_company_id"])){
|
||||
);
|
||||
|
||||
}
|
||||
?>
|
||||
|
||||
/**
|
||||
* HELPER CLASSES AND FUNCTIONS
|
||||
* These are designed to be reusable across different API endpoints for consistent data handling and error management.
|
||||
* They are not specific to any single operation and can be used wherever similar patterns arise.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Helper class to manage data consistency
|
||||
*/
|
||||
class WarehouseManager {
|
||||
|
||||
private $pdo;
|
||||
private $company_id;
|
||||
|
||||
public function __construct($pdo, $company_id) {
|
||||
$this->pdo = $pdo;
|
||||
$this->company_id = $company_id;
|
||||
}
|
||||
|
||||
public function getWarehouseName($warehouse_id) {
|
||||
$sql = "SELECT warehouse_name FROM md_warehouse
|
||||
WHERE company_id = :company_id AND id = :warehouse_id";
|
||||
|
||||
$sth = $this->pdo->prepare($sql);
|
||||
$sth->execute([
|
||||
":company_id" => $this->company_id,
|
||||
":warehouse_id" => $warehouse_id
|
||||
]);
|
||||
return $sth->fetchColumn();
|
||||
}
|
||||
|
||||
public function getStockContext($warehouse_id, $id) {
|
||||
$name = $this->getWarehouseName($warehouse_id);
|
||||
$table = "td_stock_" . $name;
|
||||
|
||||
$sql = "SELECT * FROM `$table`
|
||||
WHERE company_id = :company_id AND id = :id";
|
||||
|
||||
$sth = $this->pdo->prepare($sql);
|
||||
$sth->execute([
|
||||
":company_id" => $this->company_id,
|
||||
":id" => $id
|
||||
]);
|
||||
|
||||
return [
|
||||
'table' => $table,
|
||||
'name' => $name,
|
||||
'row' => $sth->fetch(PDO::FETCH_ASSOC) ?: []
|
||||
];
|
||||
}
|
||||
|
||||
public function adjustBalance($type, $warehouse_id, $product_sku, $old_qty, $new_qty) {
|
||||
|
||||
// Lock the row — other transactions wait here
|
||||
$sql = "SELECT id FROM warehouse_balance
|
||||
WHERE company_id = :company_id
|
||||
AND warehouse_id = :warehouse_id
|
||||
AND product_sku = :product_sku
|
||||
FOR UPDATE";
|
||||
|
||||
$sth = $this->pdo->prepare($sql);
|
||||
$sth->execute([
|
||||
":company_id" => $this->company_id,
|
||||
":warehouse_id" => $warehouse_id,
|
||||
":product_sku" => $product_sku
|
||||
]);
|
||||
|
||||
if (!$sth->fetchColumn()) {
|
||||
$sql = "INSERT INTO warehouse_balance
|
||||
(company_id, warehouse_id, product_sku)
|
||||
VALUES (:company_id, :warehouse_id, :product_sku)";
|
||||
|
||||
$sth = $this->pdo->prepare($sql);
|
||||
$sth->execute([
|
||||
":company_id" => $this->company_id,
|
||||
":warehouse_id" => $warehouse_id,
|
||||
":product_sku" => $product_sku
|
||||
]);
|
||||
}
|
||||
|
||||
$column = $type === 'in' ? 'total_in' : 'total_out';
|
||||
|
||||
// This is already atomic since it uses relative update
|
||||
$sql = "UPDATE warehouse_balance
|
||||
SET `$column` = `$column` - :old_qty + :new_qty
|
||||
WHERE company_id = :company_id
|
||||
AND warehouse_id = :warehouse_id
|
||||
AND product_sku = :product_sku";
|
||||
|
||||
$sth = $this->pdo->prepare($sql);
|
||||
$sth->execute([
|
||||
":company_id" => $this->company_id,
|
||||
":warehouse_id" => $warehouse_id,
|
||||
":product_sku" => $product_sku,
|
||||
":old_qty" => $old_qty,
|
||||
":new_qty" => $new_qty
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class FileUploader {
|
||||
|
||||
private $target_dir;
|
||||
private $allowed_mimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'application/pdf'];
|
||||
private $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'pdf'];
|
||||
private $max_size = 5 * 1024 * 1024; // 5MB
|
||||
private $uploaded_files = []; // newly uploaded filenames
|
||||
private $deleted_files = []; // files we deleted from disk
|
||||
|
||||
public function __construct($target_dir) {
|
||||
$this->target_dir = rtrim($target_dir, '/') . '/';
|
||||
$this->ensureDirectory();
|
||||
}
|
||||
|
||||
private function ensureDirectory() {
|
||||
if (!is_dir($this->target_dir)) {
|
||||
mkdir($this->target_dir, 0755, true);
|
||||
}
|
||||
if (!is_writable($this->target_dir)) {
|
||||
throw new Exception("Target directory is not writable.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove files that user deleted in the UI
|
||||
*/
|
||||
public function cleanup($existing_csv, $keep_csv) {
|
||||
if (empty($existing_csv)) return;
|
||||
|
||||
$existing = array_filter(array_map('trim', explode(',', $existing_csv)));
|
||||
$keep = !empty($keep_csv) ? array_filter(array_map('trim', explode(',', $keep_csv))) : [];
|
||||
|
||||
foreach ($existing as $file) {
|
||||
if (!in_array($file, $keep)) {
|
||||
$path = $this->target_dir . $file;
|
||||
if (file_exists($path)) {
|
||||
unlink($path);
|
||||
$this->deleted_files[] = $file;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload new files from $_FILES
|
||||
* Returns array of errors (empty = success)
|
||||
*/
|
||||
public function upload($field_name) {
|
||||
if (!isset($_FILES[$field_name])) return [];
|
||||
|
||||
$errors = [];
|
||||
|
||||
foreach ($_FILES[$field_name]['name'] as $key => $name) {
|
||||
$error_code = $_FILES[$field_name]['error'][$key];
|
||||
|
||||
if ($error_code !== UPLOAD_ERR_OK) {
|
||||
$errors[] = "{$name}: " . $this->getUploadError($error_code);
|
||||
continue;
|
||||
}
|
||||
|
||||
$tmp_name = $_FILES[$field_name]['tmp_name'][$key];
|
||||
$file_size = $_FILES[$field_name]['size'][$key];
|
||||
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
|
||||
|
||||
if ($file_size > $this->max_size) {
|
||||
$errors[] = "{$name}: exceeds " . ($this->max_size / 1024 / 1024) . "MB limit";
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!in_array($extension, $this->allowed_extensions)) {
|
||||
$errors[] = "{$name}: .{$extension} is not allowed";
|
||||
continue;
|
||||
}
|
||||
|
||||
$finfo = finfo_open(FILEINFO_MIME_TYPE);
|
||||
$mime = finfo_file($finfo, $tmp_name);
|
||||
finfo_close($finfo);
|
||||
|
||||
if (!in_array($mime, $this->allowed_mimes)) {
|
||||
$errors[] = "{$name}: content type ({$mime}) is not allowed";
|
||||
continue;
|
||||
}
|
||||
|
||||
$file_id = uniqid() . "_" . time() . "." . $extension;
|
||||
$destination = $this->target_dir . $file_id;
|
||||
|
||||
if (move_uploaded_file($tmp_name, $destination)) {
|
||||
$this->uploaded_files[] = $file_id;
|
||||
chmod($destination, 0644);
|
||||
} else {
|
||||
$errors[] = "{$name}: failed to save";
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build final CSV string for DB
|
||||
*/
|
||||
public function buildFileString($keep_csv) {
|
||||
$keep = !empty($keep_csv) ? array_filter(array_map('trim', explode(',', $keep_csv))) : [];
|
||||
$final = array_merge($keep, $this->uploaded_files);
|
||||
return implode(",", array_filter($final));
|
||||
}
|
||||
|
||||
/**
|
||||
* Rollback uploaded files if DB fails
|
||||
*/
|
||||
public function rollbackUploads() {
|
||||
foreach ($this->uploaded_files as $file) {
|
||||
$path = $this->target_dir . $file;
|
||||
if (file_exists($path)) {
|
||||
unlink($path);
|
||||
}
|
||||
}
|
||||
$this->uploaded_files = [];
|
||||
}
|
||||
|
||||
private function getUploadError($code) {
|
||||
$messages = [
|
||||
UPLOAD_ERR_INI_SIZE => "exceeds server max upload size (" . ini_get('upload_max_filesize') . ")",
|
||||
UPLOAD_ERR_FORM_SIZE => "exceeds form max size",
|
||||
UPLOAD_ERR_PARTIAL => "was only partially uploaded",
|
||||
UPLOAD_ERR_NO_FILE => "no file was sent",
|
||||
UPLOAD_ERR_NO_TMP_DIR => "server missing temp folder",
|
||||
UPLOAD_ERR_CANT_WRITE => "server failed to write to disk",
|
||||
UPLOAD_ERR_EXTENSION => "blocked by server extension",
|
||||
];
|
||||
return $messages[$code] ?? "unknown error (code {$code})";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Helper function
|
||||
*/
|
||||
|
||||
// transaction wrapper with retry logic for deadlocks
|
||||
function dbTransaction($pdo, $callback, $maxRetries = 3) {
|
||||
for ($attempt = 0; $attempt < $maxRetries; $attempt++) {
|
||||
try {
|
||||
$pdo->beginTransaction();
|
||||
$result = $callback($pdo);
|
||||
$pdo->commit();
|
||||
return $result;
|
||||
|
||||
} catch (PDOException $e) {
|
||||
$pdo->rollBack();
|
||||
|
||||
if ($e->getCode() == '40001' && $attempt < $maxRetries - 1) {
|
||||
usleep(600000 * ($attempt + 1));
|
||||
continue;
|
||||
}
|
||||
|
||||
error_log("[DB ERROR] " . $e->getMessage() . " | " . $e->getFile() . ":" . $e->getLine());
|
||||
throw $e;
|
||||
|
||||
} catch (Exception $e) {
|
||||
$pdo->rollBack();
|
||||
error_log("[ERROR] " . $e->getMessage() . " | " . $e->getFile() . ":" . $e->getLine());
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
}
|
||||
?>
|
||||
Reference in New Issue
Block a user