6 Commits
Author SHA1 Message Date
siaupheng 6091b59e18 Update Cache class: correct last modified date, improve file existence checks, and enhance cache creation logic for better performance and clarity. 2026-11-04 15:36:17 +07:00
siaupheng 11e17bd978 Refactor multiple JavaScript classes to use ES6 syntax, including Download, Pdf, Printer, PrinterPos, PoleDisplay, and Simulator. Update method names for consistency and improve error handling. Modify AJAX requests to enhance functionality and user experience. 2026-11-02 16:10:36 +07:00
siaupheng 929f3af79a Refactor PoleDisplay class and update Auth user_log method
- Converted PoleDisplay from a function-based structure to a class-based structure for improved readability and maintainability.
- Simplified the Open and Close methods to handle port state more clearly.
- Enhanced the Send method to support both string and array inputs for sending data.
- Updated the cd_Text method to use modern JavaScript features for padding calculations.
- Modified the user_log method in Auth class to streamline database fetch and update logic.
2026-11-01 15:55:28 +07:00
siaupheng cf100a86e2 update last modified date and refactor HTTP host retrieval in Menu class 2026-10-30 16:47:21 +07:00
siaupheng a538cc0cc5 update dependencies in composer.json for compatibility 2026-10-29 13:08:14 +07:00
siaupheng 4c8399cf64 add gen_uuidv4 and gen_uuidv7 2026-10-29 12:21:42 +07:00
12 changed files with 1637 additions and 1675 deletions
+226 -340
View File
@@ -1,40 +1,8 @@
var __extends = (undefined && undefined.__extends) || (function () { var AjaxResolver = class {
var extendStatics = function (d, b) { constructor(options) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var BaseResolver = (function () {
function BaseResolver(options) {
this._settings = $.extend(true, {}, this.getDefaults(), options); this._settings = $.extend(true, {}, this.getDefaults(), options);
} }
BaseResolver.prototype.getDefaults = function () { getDefaults() {
return {};
};
BaseResolver.prototype.getResults = function (limit, start, end) {
return this.results;
};
BaseResolver.prototype.search = function (q, cbk) {
cbk(this.getResults());
};
return BaseResolver;
}());
var AjaxResolver = (function (_super) {
__extends(AjaxResolver, _super);
function AjaxResolver(options) {
return _super.call(this, options) || this;
}
AjaxResolver.prototype.getDefaults = function () {
return { return {
url: '', url: '',
method: 'post', method: 'post',
@@ -43,42 +11,42 @@ var AjaxResolver = (function (_super) {
timeout: 0, timeout: 0,
requestThrottling: 500 requestThrottling: 500
}; };
};
AjaxResolver.prototype.search = function (q, cbk) {
var _this = this;
if (this.jqXHR != null) {
this.jqXHR.abort();
} }
search(q, cbk) {
if (this.jqXHR != null) this.jqXHR.abort();
var data = {}; var data = {};
data[this._settings.queryKey] = q; data[this._settings.queryKey] = q;
if (this._settings.param.length > 0) $.extend(data, FoniaJS.RequestParam(this._settings.param)); if (this._settings.param.length > 0) {
if (this.requestTID) { $.extend(data, FoniaJS.RequestParam(this._settings.param));
window.clearTimeout(this.requestTID);
} }
this.requestTID = window.setTimeout(function () {
_this.jqXHR = $.ajax(_this._settings.url, { if (this.requestTID) window.clearTimeout(this.requestTID);
method: _this._settings.method,
this.requestTID = window.setTimeout(() => {
this.jqXHR = $.ajax(this._settings.url, {
method: this._settings.method,
data: data, data: data,
timeout: _this._settings.timeout timeout: this._settings.timeout
}); });
_this.jqXHR.done(function (result) {
//gnips: result in object this.jqXHR.done(result => {
cbk((undefined !== result.autodata) ? result.autodata : result); cbk(result.autodata !== undefined ? result.autodata : result);
}); });
_this.jqXHR.fail(function (err) {
var _a; this.jqXHR.fail(err => {
(_a = _this._settings) === null || _a === void 0 ? void 0 : _a.fail(err); this._settings.fail?.(err);
}); });
_this.jqXHR.always(function () {
_this.jqXHR = null; this.jqXHR.always(() => {
this.jqXHR = null;
}); });
}, this._settings.requestThrottling); }, this._settings.requestThrottling);
}
}; };
return AjaxResolver;
}(BaseResolver));
var DropdownV5 = (function () { var DropdownV5 = class {
function DropdownV5(e, formatItemCbk, autoSelect, noResultsText) { constructor(e, formatItemCbk, autoSelect, noResultsText) {
this.initialized = false; this.initialized = false;
this.shown = false; this.shown = false;
this.items = []; this.items = [];
@@ -88,84 +56,67 @@ var DropdownV5 = (function () {
this.autoSelect = autoSelect; this.autoSelect = autoSelect;
this.noResultsText = noResultsText; this.noResultsText = noResultsText;
} }
DropdownV5.prototype.getElPos = function () {
var pos = $.extend({}, this._$el.position(), { getElPos() {
height: this._$el[0].offsetHeight return $.extend({}, this._$el.position(), { height: this._$el[0].offsetHeight });
}); }
return pos;
}; init() {
DropdownV5.prototype.init = function () {
var _this = this;
var pos = this.getElPos(); var pos = this.getElPos();
var fontsize = _this._$el.css('font-size'); var fontsize = this._$el.css('font-size');
this._dd = $('<div />');
this._dd.addClass('bootstrap-autocomplete dropdown-menu'); this._dd = $('<div />')
this._dd.insertAfter(this._$el); .addClass('bootstrap-autocomplete dropdown-menu')
this._dd.css({ top: pos.top + this._$el.outerHeight(), left: pos.left, width: this._$el.outerWidth(), 'font-size': fontsize }); .insertAfter(this._$el)
this._dd.on('click', '.dropdown-item', function (evt) { .css({
top: pos.top + this._$el.outerHeight(),
left: pos.left,
width: this._$el.outerWidth(),
'font-size': fontsize
});
this._dd.on('click', '.dropdown-item', evt => {
var item = $(evt.currentTarget).data('item'); var item = $(evt.currentTarget).data('item');
_this.itemSelectedLaunchEvent(item); this.itemSelectedLaunchEvent(item);
evt.preventDefault(); evt.preventDefault();
}); });
this._dd.on('keyup', function (evt) {
if (_this.shown) { this._dd.on('keyup', evt => {
switch (evt.which) { if (this.shown && evt.which === 27) {
case 27: this.hide();
_this.hide(); this._$el.focus();
_this._$el.focus();
break;
}
return false; return false;
} }
}); });
this._dd.on('mouseenter', function (evt) {
_this.ddMouseover = true; this._dd.on('mouseenter', () => { this.ddMouseover = true; });
}); this._dd.on('mouseleave', () => { this.ddMouseover = false; });
this._dd.on('mouseleave', function (evt) {
_this.ddMouseover = false; this._dd.on('mouseenter', '.dropdown-item', evt => {
}); if (this.haveResults) {
this._dd.on('mouseenter', '.dropdown-item', function (evt) {
if (_this.haveResults) {
$(evt.currentTarget).closest('div').find('.dropdown-item.active').removeClass('active'); $(evt.currentTarget).closest('div').find('.dropdown-item.active').removeClass('active');
$(evt.currentTarget).addClass('active'); $(evt.currentTarget).addClass('active');
_this.mouseover = true; this.mouseover = true;
} }
}); });
this._dd.on('mouseleave', '.dropdown-item', function (evt) {
_this.mouseover = false; this._dd.on('mouseleave', '.dropdown-item', () => { this.mouseover = false; });
});
this.initialized = true; this.initialized = true;
};
DropdownV5.prototype.checkInitialized = function () {
if (!this.initialized) {
this.init();
} }
};
Object.defineProperty(DropdownV5.prototype, "isMouseOver", { checkInitialized() {
get: function () { if (!this.initialized) this.init();
return this.mouseover; }
},
enumerable: false, get isMouseOver() { return this.mouseover; }
configurable: true get isDdMouseOver() { return this.ddMouseover; }
}); get haveResults() { return this.items.length > 0; }
Object.defineProperty(DropdownV5.prototype, "isDdMouseOver", {
get: function () { focusNextItem(reversed) {
return this.ddMouseover; if (!this.haveResults) return;
},
enumerable: false,
configurable: true
});
Object.defineProperty(DropdownV5.prototype, "haveResults", {
get: function () {
return (this.items.length > 0);
},
enumerable: false,
configurable: true
});
DropdownV5.prototype.focusNextItem = function (reversed) {
if (this.haveResults) {
var currElem = this._dd.find('.dropdown-item.active'); var currElem = this._dd.find('.dropdown-item.active');
var nextElem = reversed ? currElem.prev() : currElem.next(); var nextElem = reversed ? currElem.prev() : currElem.next();
if (nextElem.length === 0) { if (nextElem.length === 0) {
nextElem = reversed ? this._dd.find('.dropdown-item').last() : this._dd.find('.dropdown-item').first(); nextElem = reversed ? this._dd.find('.dropdown-item').last() : this._dd.find('.dropdown-item').first();
} }
@@ -173,109 +124,91 @@ var DropdownV5 = (function () {
nextElem.addClass('active'); nextElem.addClass('active');
this.scrollTo(nextElem); this.scrollTo(nextElem);
} }
};
DropdownV5.prototype.focusPreviousItem = function () { focusPreviousItem() { this.focusNextItem(true); }
this.focusNextItem(true); selectFocusItem() { this._dd.find('.dropdown-item.active').trigger('click'); }
};
DropdownV5.prototype.selectFocusItem = function () { get isItemFocused() {
this._dd.find('.dropdown-item.active').trigger('click'); return !!(this._dd && this.isShown() && this._dd.find('.dropdown-item.active').length > 0);
};
Object.defineProperty(DropdownV5.prototype, "isItemFocused", {
get: function () {
if (this._dd && this.isShown() && (this._dd.find('.dropdown-item.active').length > 0)) {
return true;
} }
return false;
}, show() {
enumerable: false,
configurable: true
});
DropdownV5.prototype.show = function () {
if (!this.shown) { if (!this.shown) {
this._dd.addClass('show'); this._dd.addClass('show');
this.shown = true; this.shown = true;
this._$el.trigger('autocomplete.dd.shown'); this._$el.trigger('autocomplete.dd.shown');
} }
}; }
DropdownV5.prototype.isShown = function () {
return this.shown; isShown() { return this.shown; }
};
DropdownV5.prototype.hide = function () { hide() {
if (this.shown) { if (this.shown) {
this._dd.removeClass('show'); this._dd.removeClass('show');
this.shown = false; this.shown = false;
this._$el.trigger('autocomplete.dd.hidden'); this._$el.trigger('autocomplete.dd.hidden');
} }
}; }
DropdownV5.prototype.updateItems = function (items, searchText) {
updateItems(items, searchText) {
this.items = items; this.items = items;
this.searchText = searchText; this.searchText = searchText;
this.refreshItemList(); this.refreshItemList();
}; }
DropdownV5.prototype.showMatchedText = function (text, qry) {
showMatchedText(text, qry) {
var startIndex = text.toLowerCase().indexOf(qry.toLowerCase()); var startIndex = text.toLowerCase().indexOf(qry.toLowerCase());
if (startIndex > -1) { if (startIndex > -1) {
var endIndex = startIndex + qry.length; var endIndex = startIndex + qry.length;
return text.slice(0, startIndex) + '<b>' return text.slice(0, startIndex) + '<b>' + text.slice(startIndex, endIndex) + '</b>' + text.slice(endIndex);
+ text.slice(startIndex, endIndex) + '</b>'
+ text.slice(endIndex);
} }
return text; return text;
}; }
DropdownV5.prototype.refreshItemList = function () {
var _this = this; refreshItemList() {
this.checkInitialized(); this.checkInitialized();
this._dd.empty(); this._dd.empty();
var liList = []; var liList = [];
if (this.items.length > 0) { if (this.items.length > 0) {
this.items.forEach(function (item) { this.items.forEach(item => {
var itemFormatted = _this.formatItem(item); var itemFormatted = this.formatItem(item);
if (typeof itemFormatted === 'string') { if (typeof itemFormatted === 'string') itemFormatted = { text: itemFormatted };
itemFormatted = { text: itemFormatted };
} var itemText = this.showMatchedText(itemFormatted.text, this.searchText);
var itemText; var itemHtml = itemFormatted.html !== undefined ? itemFormatted.html : itemText;
var itemHtml;
itemText = _this.showMatchedText(itemFormatted.text, _this.searchText); var li = $('<a />')
if (itemFormatted.html !== undefined) { .addClass('dropdown-item')
itemHtml = itemFormatted.html;
} else {
itemHtml = itemText;
}
var disabledItem = itemFormatted.disabled;
var li = $('<a >');
li.addClass('dropdown-item')
//css bisa dimasukkan ke style default + cursor select
//.css({ 'overflow': 'hidden', 'text-overflow': 'ellipsis' })
.html(itemHtml) .html(itemHtml)
.data('item', item); .data('item', item);
if (disabledItem) {
li.addClass('disabled'); if (itemFormatted.disabled) li.addClass('disabled');
}
liList.push(li); liList.push(li);
}); });
this._dd.append(liList); this._dd.append(liList);
this.show(); this.show();
} } else if (this.noResultsText !== '') {
else { var li = $('<a />').addClass('dropdown-item disabled').html(this.noResultsText);
if (this.noResultsText === '') {
this.hide();
}
else {
var li = $('<a >');
li.addClass('dropdown-item disabled')
.html(this.noResultsText);
liList.push(li); liList.push(li);
this._dd.append(liList); this._dd.append(liList);
this.show(); this.show();
} else {
this.hide();
} }
} }
};
DropdownV5.prototype.itemSelectedLaunchEvent = function (item) { itemSelectedLaunchEvent(item) {
this._$el.trigger('autocomplete.select', item); this._$el.trigger('autocomplete.select', item);
}; }
DropdownV5.prototype.scrollTo = function (el) {
var _he = this._dd.height(), _to = this._dd.scrollTop(), _ito = el.position().top, _ihe = el.outerHeight(), scrollTo(el) {
var _he = this._dd.height(),
_to = this._dd.scrollTop(),
_ito = el.position().top,
_ihe = el.outerHeight(),
_nto = _to, _wra = false; _nto = _to, _wra = false;
if (_ito < 0) { if (_ito < 0) {
_wra = el.is(':first-child'); _wra = el.is(':first-child');
_nto = _wra ? 0 : _to - _he / 2; _nto = _wra ? 0 : _to - _he / 2;
@@ -284,12 +217,11 @@ var DropdownV5 = (function () {
_nto = _wra ? (_ito + _ihe - _he) : _to + _he / 2; _nto = _wra ? (_ito + _ihe - _he) : _to + _he / 2;
} }
this._dd.scrollTop(_nto); this._dd.scrollTop(_nto);
}
}; };
return DropdownV5;
}());
var AutoComplete = (function () { var AutoComplete = class {
function AutoComplete(element, options) { constructor(element, options) {
this._selectedItem = null; this._selectedItem = null;
this._defaultValue = null; this._defaultValue = null;
this._defaultText = null; this._defaultText = null;
@@ -302,230 +234,185 @@ var AutoComplete = (function () {
autoSelect: true, autoSelect: true,
noResultsText: 'Pencarian Tidak Ketemu', noResultsText: 'Pencarian Tidak Ketemu',
preventEnter: false, preventEnter: false,
events: { events: { typed: null, searchPre: null, search: null, searchPost: null, select: null, focus: null },
typed: null, selectFunc: () => {},
searchPre: null, keyFunc: () => {},
search: null, breakFocus: false,
searchPost: null,
select: null,
focus: null,
},
//gnips: adding callback, keyfunc and breakvalue
selectFunc: function(){},
keyFunc: function(){},
breakValue: [] breakValue: []
}; };
this._el = element; this._el = element;
this._$el = $(this._el); this._$el = $(this._el);
this.manageInlineDataAttributes(); this.manageInlineDataAttributes();
if (typeof options === 'object') { if (typeof options === 'object') {
this._settings = $.extend(true, {}, this.getSettings(), options); this._settings = $.extend(true, {}, this.getSettings(), options);
} }
this.init(); this.init();
} }
AutoComplete.prototype.manageInlineDataAttributes = function () {
manageInlineDataAttributes() {
var s = this.getSettings(); var s = this.getSettings();
if (this._$el.data('url')) { if (this._$el.data('url')) s.resolverSettings.url = this._$el.data('url');
s.resolverSettings.url = this._$el.data('url'); if (this._$el.data('default-value')) this._defaultValue = this._$el.data('default-value');
if (this._$el.data('default-text')) this._defaultText = this._$el.data('default-text');
if (this._$el.data('noresults-text') !== undefined) s.noResultsText = this._$el.data('noresults-text');
} }
if (this._$el.data('default-value')) {
this._defaultValue = this._$el.data('default-value'); getSettings() { return this._settings; }
}
if (this._$el.data('default-text')) { init() {
this._defaultText = this._$el.data('default-text');
}
if (this._$el.data('noresults-text') !== undefined) {
s.noResultsText = this._$el.data('noresults-text');
}
};
AutoComplete.prototype.getSettings = function () {
return this._settings;
};
AutoComplete.prototype.init = function () {
this.bindDefaultEventListeners(); this.bindDefaultEventListeners();
if (this._settings.resolver === 'ajax') { if (this._settings.resolver === 'ajax') {
this.resolver = new AjaxResolver(this._settings.resolverSettings); this.resolver = new AjaxResolver(this._settings.resolverSettings);
} }
this._dd = new DropdownV5(this._$el, this._settings.formatResult, this._settings.autoSelect, this._settings.noResultsText); this._dd = new DropdownV5(this._$el, this._settings.formatResult, this._settings.autoSelect, this._settings.noResultsText);
}; }
AutoComplete.prototype.bindDefaultEventListeners = function () {
var _this = this; bindDefaultEventListeners() {
this._$el.on('keydown', function (evt) { this._$el.on('keydown', evt => {
//gnips: check breakValue and call keydown function var val = this._$el.val();
(('' == _this._$el.val() || ((_this._settings.breakValue.length > 0) && (_this._settings.breakValue.indexOf(_this._$el.val()) != -1))) && _this._settings.keyFunc(evt.which, _this._$el.val())); if ((val === '' || (this._settings.breakValue.length > 0 && this._settings.breakValue.indexOf(val) !== -1))) {
this._settings.keyFunc(evt.which, val);
}
switch (evt.which) { switch (evt.which) {
case 9: case 9:
if (_this._dd.isItemFocused) { if (!this._settings.breakFocus) {
_this._dd.selectFocusItem(); if (this._dd.isItemFocused) this._dd.selectFocusItem();
this._dd.hide();
} }
_this._dd.hide();
break; break;
case 13: case 13:
if (_this._dd.isItemFocused) { if (this._dd.isItemFocused) this._dd.selectFocusItem();
_this._dd.selectFocusItem(); this._dd.hide();
} if (this._settings.preventEnter) evt.preventDefault();
_this._dd.hide();
if (_this._settings.preventEnter) {
evt.preventDefault();
}
break; break;
case 40: case 40:
_this._dd.focusNextItem(); this._dd.focusNextItem();
break; break;
case 38: case 38:
_this._dd.focusPreviousItem(); this._dd.focusPreviousItem();
break; break;
} }
}); });
this._$el.on('keyup', function (evt) {
this._$el.on('keyup', evt => {
switch (evt.which) { switch (evt.which) {
case 16: case 16: case 17: case 18: case 39: case 37: case 36: case 35: case 40: case 38:
case 17:
case 18:
case 39:
case 37:
case 36:
case 35:
break; break;
case 13: case 13: case 27:
_this._dd.hide(); this._dd.hide();
break;
case 27:
_this._dd.hide();
break;
case 40:
break;
case 38:
break; break;
default: default:
_this._selectedItem = null; this._selectedItem = null;
var newValue = _this._$el.val(); this.handlerTyped(this._$el.val());
_this.handlerTyped(newValue);
} }
}); });
this._$el.on('blur', function (evt) {
if (!_this._dd.isMouseOver && _this._dd.isDdMouseOver && _this._dd.isShown()) { this._$el.on('blur', () => {
setTimeout(function () { _this._$el.focus(); }); if (this._settings.breakFocus) return;
_this._$el.focus(); if (!this._dd.isMouseOver && this._dd.isDdMouseOver && this._dd.isShown()) {
} setTimeout(() => { this._$el.focus(); });
else if (!_this._dd.isMouseOver) { this._$el.focus();
_this._dd.hide(); } else if (!this._dd.isMouseOver) {
this._dd.hide();
} }
}); });
this._$el.on('autocomplete.select', function (evt, item) {
_this._selectedItem = item; this._$el.on('autocomplete.select', (evt, item) => {
_this.itemSelectedDefaultHandler(item); this._selectedItem = item;
this.itemSelectedDefaultHandler(item);
}); });
this._$el.on('paste', function (evt) {
setTimeout(function () { this._$el.on('paste', evt => {
_this._$el.trigger('keyup', evt); setTimeout(() => { this._$el.trigger('keyup', evt); }, 0);
}, 0);
}); });
}; }
AutoComplete.prototype.handlerTyped = function (newValue) {
handlerTyped(newValue) {
if (this._settings.events.typed !== null) { if (this._settings.events.typed !== null) {
newValue = this._settings.events.typed(newValue, this._$el); newValue = this._settings.events.typed(newValue, this._$el);
if (!newValue) { if (!newValue) return;
return;
}
} }
if (newValue.length >= this._settings.minLength) { if (newValue.length >= this._settings.minLength) {
this._searchText = newValue; this._searchText = newValue;
this.handlerPreSearch(); this.handlerPreSearch();
} } else {
else {
this._dd.hide(); this._dd.hide();
} }
}; }
AutoComplete.prototype.handlerPreSearch = function () {
handlerPreSearch() {
if (this._settings.events.searchPre !== null) { if (this._settings.events.searchPre !== null) {
var newValue = this._settings.events.searchPre(this._searchText, this._$el); var newValue = this._settings.events.searchPre(this._searchText, this._$el);
if (!newValue) if (!newValue) return;
return;
this._searchText = newValue; this._searchText = newValue;
} }
this.handlerDoSearch(); this.handlerDoSearch();
};
AutoComplete.prototype.handlerDoSearch = function () {
var _this = this;
if (this._settings.events.search !== null) {
this._settings.events.search(this._searchText, function (results) {
_this.postSearchCallback(results);
}, this._$el);
} }
else {
if (this.resolver) { handlerDoSearch() {
this.resolver.search(this._searchText, function (results) { if (this._settings.events.search !== null) {
_this.postSearchCallback(results); this._settings.events.search(this._searchText, results => {
this.postSearchCallback(results);
}, this._$el);
} else if (this.resolver) {
this.resolver.search(this._searchText, results => {
this.postSearchCallback(results);
}); });
} }
} }
};
AutoComplete.prototype.postSearchCallback = function (results) { postSearchCallback(results) {
if (this._settings.events.searchPost) { if (this._settings.events.searchPost) {
results = this._settings.events.searchPost(results, this._$el); results = this._settings.events.searchPost(results, this._$el);
if ((typeof results === 'boolean') && !results) if (typeof results === 'boolean' && !results) return;
return;
} }
this.handlerStartShow(results); this.handlerStartShow(results);
}; }
AutoComplete.prototype.handlerStartShow = function (results) {
//gnips: adding auto select when barcode result of 1 item only handlerStartShow(results) {
if (1 == results.length && 1 == (void 0 !== results[0].bc ? results[0].bc : 0)) { var bcVal = results[0]?.bc ?? 0;
this._$el.trigger('autocomplete.select', results[0]), if (results.length === 1 && bcVal === 1) {
this._$el.trigger('autocomplete.select', results[0]);
this._dd.hide(); this._dd.hide();
} else this._dd.updateItems(results, this._searchText); } else {
}; this._dd.updateItems(results, this._searchText);
AutoComplete.prototype.itemSelectedDefaultHandler = function (item) { }
}
itemSelectedDefaultHandler(item) {
if (item != null) { if (item != null) {
var itemFormatted = this._settings.formatResult(item); var itemFormatted = this._settings.formatResult(item);
if (typeof itemFormatted === 'string') { if (typeof itemFormatted === 'string') itemFormatted = { text: itemFormatted };
itemFormatted = { text: itemFormatted };
}
this._$el.val(itemFormatted.text); this._$el.val(itemFormatted.text);
} } else {
else {
this._$el.val(''); this._$el.val('');
} }
this._selectedItem = item; this._selectedItem = item;
//gnips: callback with selected item
this._settings.selectFunc(item); this._settings.selectFunc(item);
this._dd.hide(); this._dd.hide();
};
AutoComplete.prototype.defaultFormatResult = function (item) {
if (typeof item === 'string') {
return { text: item };
} }
else if (item.text) {
return item; defaultFormatResult(item) {
} if (typeof item === 'string') return { text: item };
else { if (item.text) return item;
return { text: item.toString() }; return { text: item.toString() };
} }
};
AutoComplete.prototype.manageAPI = function (APICmd, params) { manageAPI(APICmd, params) {
if (APICmd === 'set') { if (APICmd === 'set') this.itemSelectedDefaultHandler(params);
this.itemSelectedDefaultHandler(params); else if (APICmd === 'clear') this.itemSelectedDefaultHandler(null);
} else if (APICmd === 'show') this._$el.trigger('keyup');
else if (APICmd === 'clear') { else if (APICmd === 'updateResolver') this.resolver = new AjaxResolver(params);
this.itemSelectedDefaultHandler(null);
}
else if (APICmd === 'show') {
this._$el.trigger('keyup');
}
else if (APICmd === 'updateResolver') {
this.resolver = new AjaxResolver(params);
} }
}; };
AutoComplete.NAME = 'autoComplete'; AutoComplete.NAME = 'autoComplete';
return AutoComplete;
}());
(function ($, window, document) { // jQuery plugin wrapper
$.fn[AutoComplete.NAME] = function (optionsOrAPI, optionalParams) { $.fn[AutoComplete.NAME] = function (optionsOrAPI, optionalParams) {
return this.each(function () { return this.each(function () {
var pluginClass; var pluginClass = $(this).data(AutoComplete.NAME);
pluginClass = $(this).data(AutoComplete.NAME);
if (!pluginClass) { if (!pluginClass) {
pluginClass = new AutoComplete(this, optionsOrAPI); pluginClass = new AutoComplete(this, optionsOrAPI);
$(this).data(AutoComplete.NAME, pluginClass); $(this).data(AutoComplete.NAME, pluginClass);
@@ -533,4 +420,3 @@ var AutoComplete = (function () {
pluginClass.manageAPI(optionsOrAPI, optionalParams); pluginClass.manageAPI(optionsOrAPI, optionalParams);
}); });
}; };
})(jQuery, window, document);
+76 -72
View File
@@ -4,82 +4,86 @@
Desc. : Fungsi-fungsi download data & laporan Desc. : Fungsi-fungsi download data & laporan
Created By : Siau Pheng ([email protected]). Created By : Siau Pheng ([email protected]).
Created Date : April 1st, 2011. Created Date : April 1st, 2011.
Last Modified : October 2nd, 2026. Last Modified : November 2nd, 2026.
(c) 3FONIA Software; WWW.3FONIA.COM. (c) 3FONIA Software; WWW.3FONIA.COM.
*******************************************************************/ *******************************************************************
*
* Class Download
*
* Download atau Share file.
*
* @license MIT, https://www.3fonia.com
* @copyright Copyright (c) 2008-2026, Siau Pheng <[email protected]>
*
* @param {object} options
* @param {string} options.url - Endpoint URL File
* @param {string} [options.filename='file.bin'] - Default file name for download is header is missing
* @param {string} [options.title] - Title for share file
* @param {string} [options.text] - Text for share file
* @param {Array} [options.params] - Request payload
*/
var Download = function(options) { class Download {
var _options = { constructor(options = {}) {
'url': '', this.url = typeof options === 'string' ? options : options.url || '';
'filename': 'file.bin', this.filename = options.filename || 'file.bin';
'title': '', this.title = options.title || '';
'text': 'share dari aplikasi' this.text = options.text || '';
}; this.params = options.params || [];
var _params = [];
this.construct = function(options){
if (typeof options == 'object') {
$.extend(_options, options);
} else _options.url = options;
};
this.set_url = function (url){
_options.url = url;
};
this.add_param = function(par_id, par_val) {
var _getvalue = (par_val) ? par_id + '=' + encodeURIComponent(par_val) : par_id;
_params.push(_getvalue);
};
this._exec = async function(is_share) {
if (!_options.url) {
console.warn('cek url !');
return false;
}
try {
const blob = await $.ajax({
type: 'POST',
url: _options.url,
data: FoniaJS.RequestParam(_params),
xhrFields: {
responseType: 'blob'
},
success: async function (data, status, xhr) {
const disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
_options.filename = matches[1].replace(/['"]/g, '');
}
}
}
});
const file = new File([blob], _options.filename, { type: blob.type });
if (is_share === true && navigator.canShare && navigator.canShare({ files: [file] })) {
await navigator.share({
files: [file],
title: _options.title ?? _options.filename,
text: _options.text
});
} else {
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = _options.filename;
link.click();
} }
} catch (error) { addParam(id, val) {
console.error('Download / sharing gagal :', error); this.params.push(val !== undefined ? `${id}=${encodeURIComponent(val)}` : id);
};
return this; return this;
}; }
this.share = async function() {
await this._exec(true); async _exec(isShare = false) {
}; if (!this.url) {
this.download = async function() { console.warn('Url File Download dibutuhkan!');
await this._exec(false); return;
}; }
this.construct(options); await $.ajax({
}; type: 'POST',
url: this.url,
data: FoniaJS.RequestParam(this.params),
xhrFields: { responseType: 'blob' }
})
.done((blob, status, xhr) => {
let filename = this.filename;
const disposition = xhr.getResponseHeader('Content-Disposition');
const match = disposition?.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
if (match?.[1]) filename = match[1].replace(/['"]/g, '');
if (!isShare) {
const url = URL.createObjectURL(blob);
const link = Object.assign(document.createElement('a'), {
href: url,
download: filename
});
link.click();
URL.revokeObjectURL(url);
} else {
const file = new File([blob], filename, { type: blob.type });
if (isShare && navigator.canShare?.({ files: [file] })) {
navigator.share({
files: [file],
title: this.title || filename,
text: this.text
});
}
file = null;
}
})
.fail((xhr, status, err) => console.error('Gagal download File karena : ', err));
}
share() {
return this._exec(true);
}
download() {
return this._exec(false);
}
}
+610 -698
View File
File diff suppressed because it is too large Load Diff
+113 -53
View File
@@ -4,63 +4,123 @@
Desc. : JS - Cetak Laporan PDF Desc. : JS - Cetak Laporan PDF
Created By : Siau Pheng ([email protected]). Created By : Siau Pheng ([email protected]).
Created Date : April 6th, 2015. Created Date : April 6th, 2015.
Last Modified : October 18th, 2020. Last Modified : November 2nd, 2026.
(c) 3FONIA Software; WWW.3FONIA.COM. (c) 3FONIA Software; WWW.3FONIA.COM.
*******************************************************************/ *******************************************************************
*
* Class Pdf
*
* Preview dan download file pdf.
*
* @license MIT, https://www.3fonia.com
* @copyright Copyright (c) 2008-2026, Siau Pheng <[email protected]>
*
* @param {object} options
* @param {string} options.url - Endpoint PDF File URL
* @param {number} [options.zoom=80] - Zoom percentage in PDF viewer
* @param {string} [options.filename='report.pdf'] - Default file name for download is header is missing
* @param {Array} [options.params] - Request payload
*/
var Pdf = function(options){ class Pdf {
var vars = { constructor(options = {}) {
'url': '', this.url = typeof options === 'string' ? options : options.url || '';
'zoom': 80, this.zoom = options.zoom || 80;
'param': [] this.filename = options.filename || 'report.pdf';
}; this.params = options.params || [];
this.construct = function(options){
if (typeof options == 'object') {
$.extend(vars, options);
} else vars.url = options;
};
this.set_url = function (url){
vars.url = url;
};
this.set_zoom = function (zoom){
if (zoom) vars.zoom = zoom;
},
this.add_param = function (par_id, par_val){
var _getvalue = (par_val) ? par_id + "=" + escape(par_val) : par_id;
vars.param.push(_getvalue);
},
this.downloadPDF = function(){
if (!vars.url) {
console.warn(vars.param + ", cek url php!");
return false;
} }
$.ajax({
type: 'POST', addParam(id, val) {
url: vars.url, this.params.push(val !== undefined ? `${id}=${encodeURIComponent(val)}` : id);
data: FoniaJS.RequestParam(vars.param),
success: (typeof vars.onSuccess === "function") ? vars.onSuccess : null,
error: (typeof vars.onFailure === "function") ? vars.onFailure : null,
}).always(FoniaJS.FormDecorated);
return this; return this;
}; }
this.showPDF = function(){
var _proto = window.location.protocol + '//'; async downloadPdf() {
var _src = _proto + FoniaJS.WEB_HOST + vars.url + '?' + $.param(FoniaJS.RequestParam(vars.param)) + '#zoom='+vars.zoom+',0,0&page=1'; if (!this.url) {
var _wtxt = console.warn('Url PDF dibutuhkan!');
'<div class="modal fade" id="winAPPPDF" tabindex="-1" role="dialog" data-bs-keyboard="false" data-bs-show="false" data-bs-backdrop="static" aria-labelledby="winAPPPDFLabel" aria-hidden="true">'+ return;
'<div class="modal-dialog modal-dialog-centered modal-fs" role="document">'+ }
'<div class="modal-content">'+ await $.ajax({
'<div class="modal-header"><h5 class="modal-title" id="winAPPPDFLabel">Preview PDF</h5><button class="btn-close" type="button" data-bs-dismiss="modal" aria-label="Close"></button></div>'+ type: 'POST',
'<div class="modal-body mb-0 p-0"><div class="ratio ratio-21x9"><object type="application/pdf" data="'+_src+'"><p>Tidak Mendukung Preview PDF</p></object></div></div>'+ url: this.url,
'</div></div></div>'; data: FoniaJS.RequestParam(this.params),
if ($('#winAPPPDF')) $('#winAPPPDF').modal('dispose').remove(); xhrFields: { responseType: 'blob' }
$(_wtxt).on('shown.bs.modal', function(e){ })
FoniaJS.FormDecorated(); .done((blob, status, xhr) => {
}).on('hidden.bs.modal', function(e){ let filename = this.filename;
const disposition = xhr.getResponseHeader('Content-Disposition');
const match = disposition?.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
if (match?.[1]) filename = match[1].replace(/['"]/g, '');
const url = URL.createObjectURL(blob);
const link = Object.assign(document.createElement('a'), {
href: url,
download: filename
});
link.click();
URL.revokeObjectURL(url);
})
.fail((xhr, status, err) => console.error('Gagal proses download PDF karena : ', err));
}
async showPdf() {
if (!this.url) {
console.warn('Url PDF dibutuhkan!');
return;
}
await $.ajax({
type: 'POST',
url: this.url,
data: FoniaJS.RequestParam(this.params),
xhrFields: { responseType: 'blob' }
})
.done((blob, status, xhr) => {
let filename = this.filename;
const disposition = xhr.getResponseHeader('Content-Disposition');
const match = disposition?.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
if (match?.[1]) filename = match[1].replace(/['"]/g, '');
const objectUrl = URL.createObjectURL(blob);
const pdfSrc = `${objectUrl}#zoom=${zoom}&page=1`;
const modalHtml = `
<div class="modal fade" id="winAPPPDF" tabindex="-1" data-bs-backdrop="static" aria-labelledby="winAPPPDFLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-xl" style="height: 90vh;">
<div class="modal-content h-100">
<div class="modal-header">
<h5 class="modal-title" id="winAPPPDFLabel">${filename}</h5>
<div class="ms-auto d-flex align-items-center gap-2">
<a href="${objectUrl}" download="${filename}" class="btn btn-sm btn-outline-primary">
<i class="bi bi-download"></i> Download
</a>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
</div>
<div class="modal-body p-0 h-100">
<object data="${pdfSrc}" type="application/pdf" class="w-100 h-100">
<iframe src="${pdfSrc}" class="w-100 h-100" style="border: none;">
<p class="p-3">Ada kendala dalam Preview PDF di browser Anda.
<a href="${objectUrl}" download="${filename}">Unduh ${filename}</a> instead.
</p>
</iframe>
</object>
</div>
</div>
</div>
</div>
`;
$('#winAPPPDF').modal('dispose').remove();
$(modalHtml)
.appendTo('body')
//.on('shown.bs.modal', () => FoniaJS.FormDecorated())
.on('hidden.bs.modal', function () {
URL.revokeObjectURL(objectUrl);
$(this).remove(); $(this).remove();
}).modal('show'); })
}; .modal('show');
this.construct(options); })
}; .fail((xhr, status, err) => console.error('Gagal proses preview PDF karena : ', err));
}
}
+57 -61
View File
@@ -4,90 +4,86 @@
Desc. : JS Class Tampil Data di Pole Display POS Desc. : JS Class Tampil Data di Pole Display POS
Created By : Siau Pheng ([email protected]). Created By : Siau Pheng ([email protected]).
Created Date : October 12th, 2025. Created Date : October 12th, 2025.
Last Modified : November 1st, 2026.
(c) 3FONIA Software; WWW.3FONIA.COM. (c) 3FONIA Software; WWW.3FONIA.COM.
*******************************************************************/ *******************************************************************/
var PoleDisplay = function(port, options){ class PoleDisplay {
var _cd_port = ''; constructor(port, options = {}) {
var _cd_pole = ''; this.port = port;
var _options = { this.pole = '';
this.options = Object.assign({
rx: { start: '\x02', end: '\x0D', width: null }, rx: { start: '\x02', end: '\x0D', width: null },
baudRate: 9600, baudRate: 9600,
dataBits: 8, dataBits: 8,
stopBits: 1, stopBits: 1,
parity: 'NONE', parity: 'NONE',
flowControl: 'NONE' flowControl: 'NONE'
}; }, options);
this.construct = function (port, options){
$.extend(_options, options);
_cd_port = port;
};
this.Open = function (){
if (_cd_pole === '') {
qz.serial.openPort(_cd_port, _options).then(() => {
_cd_pole = _cd_port;
this.cd_Error(_cd_port+' opened');
}).then(() => {
qz.serial.sendData(_cd_pole, {type:'HEX',data:'x1Bx40'}, _options).catch(this.cd_Error);
}).catch(this.cd_Error);
} }
};
this.Close = function (){ Open() {
qz.serial.closePort(_cd_port).then(() => { if (this.pole) return;
_cd_pole = '';
this.cd_Error(_cd_port+' closed');
}).catch(this.cd_Error);
};
this.Send = function (txt){ qz.serial.openPort(this.port, this.options)
if (_cd_pole === '') return false; .then(() => {
var ascii_to_hexa = function(str) { this.pole = this.port;
var arr1 = []; this._conerr(`${this.port} opened`);
for (var n = 0, l = str.length; n < l; n++) { return qz.serial.sendData(this.pole, { type: 'HEX', data: 'x1Bx40' }, this.options);
var hex = Number(str.charCodeAt(n)).toString(16); })
if (hex.length==1) hex = '0' + hex; .catch(this._conerr);
arr1.push(hex.toUpperCase());
} }
return 'x' + arr1.join('x');
}; Close() {
var _txt = txt; if (!this.pole) return;
qz.serial.closePort(this.port)
.then(() => {
this.pole = '';
this._conerr(`${this.port} closed`);
})
.catch(this._conerr);
}
Send(txt) {
if (!this.pole) return false;
// Convert string to ASCII hex format
const asciiToHex = str =>
Array.from(str, char => char.charCodeAt(0).toString(16).padStart(2, '0').toUpperCase())
.join('x');
let textToSend = txt;
if (Array.isArray(txt)) { if (Array.isArray(txt)) {
_txt = ''; textToSend = txt.map(ele => this._aligntext(ele.t, ele.a)).join('');
txt.forEach((ele) => {
_txt += this.cd_Text(ele['t'], ele['a']);
});
} }
qz.serial.sendData(_cd_pole, {type:'HEX',data:'x10C'+ascii_to_hexa(_txt)}, _options).catch(this.cd_Error);
};
this.cd_Text = function (text, align){ const hexData = `x10C${asciiToHex(textToSend)}`;
const totWidth = 20; qz.serial.sendData(this.pole, { type: 'HEX', data: hexData }, this.options)
const txtLength = text.length; .catch(this._conerr);
if (txtLength >= totWidth) {
return text.substring(0, totWidth);
} }
const padding = totWidth - txtLength;
var lPadding = 0; _aligntext(text, align = 'L') {
var rPadding = padding; const totWidth = 20;
if (align === null) align = 'L'; if (text.length >= totWidth) return text.substring(0, totWidth);
if (align == 'C'){
const padding = totWidth - text.length;
let lPadding = 0, rPadding = padding;
if (align === 'C') {
lPadding = Math.floor(padding / 2); lPadding = Math.floor(padding / 2);
rPadding = Math.ceil(padding / 2); rPadding = Math.ceil(padding / 2);
} else if (align == 'R'){ } else if (align === 'R') {
lPadding = padding; lPadding = padding;
rPadding = 0; rPadding = 0;
} }
return " ".repeat(lPadding) + text + " ".repeat(rPadding);
};
this.cd_Error = function (err){ return ' '.repeat(lPadding) + text + ' '.repeat(rPadding);
}
_conerr(err) {
console.error(err); console.error(err);
}; }
}
this.construct(port, options);
};
+201 -169
View File
@@ -4,233 +4,265 @@
Desc. : JS Class Printer & Printer POS Desc. : JS Class Printer & Printer POS
Created By : Siau Pheng ([email protected]). Created By : Siau Pheng ([email protected]).
Created Date : May 27th, 2007. Created Date : May 27th, 2007.
Last Modified : September 21st, 2026. Last Modified : November 2nd, 2026.
(c) 3FONIA Software; WWW.3FONIA.COM. (c) 3FONIA Software; WWW.3FONIA.COM.
*******************************************************************/ *******************************************************************
*
* Class Printer
*
* Standard Web Document Printing & Report Preview Class
*
* @license MIT, https://www.3fonia.com
* @copyright Copyright (c) 2008-2026, Siau Pheng <[email protected]>
*
* @param {object} options
* @param {string} options.url - Endpoint URL Print Page
* @param {number} [options.zoom=90] - Zoom percentage in viewer
* @param {Array} [options.params] - Request payload
*/
var Printer = function(options){ class Printer {
var vars = { constructor(options = {}) {
'url': '', this.url = typeof options === 'string' ? options : options.url || '';
'zoom': 90, this.zoom = options.zoom || 90;
'param': [] this.params = options.params || [];
}; }
this.construct = function(options){
if (typeof options == 'object') { addParam(id, val) {
$.extend(vars, options); this.params.push(val !== undefined ? `${id}=${encodeURIComponent(val)}` : id);
} else vars.url = options; return this;
}; }
this.set_url = function (url){
vars.url = url; doPrint() {
}; if (!this.url) {
this.set_zoom = function (zoom){ console.warn('Url Laporan dibutuhkan!');
if (zoom) vars.zoom = zoom; return;
},
this.add_param = function (par_id, par_val){
var _getvalue = (par_val) ? par_id + "=" + escape(par_val) : par_id;
vars.param.push(_getvalue);
},
this.doPrint = function(){
if (!vars.url) {
console.warn(vars.param + ", cek url php!");
return false;
} }
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: vars.url, url: this.url,
data: FoniaJS.RequestParam(vars.param), data: FoniaJS.RequestParam(this.params),
success: (txt) => { success: (txt) => {
var $printData = $('#dataPrint'); let $printData = $('#dataPrint');
if (!$printData.length) { if (!$printData.length) {
$printData = $('<div/>', {id:'dataPrint','class':'d-none d-print-block print-body'}).appendTo('body'); $printData = $('<div/>', {
id: 'dataPrint',
class: 'd-none d-print-block print-body'
}).appendTo('body');
} }
$printData.html(txt); $printData.html(txt);
window.print(); window.print();
}, },
error: (typeof vars.onFailure === "function") ? vars.onFailure : null, error: typeof this.onFailure === 'function' ? this.onFailure : null
}); });
return this; return this;
}; }
this.doPreview = function(){
if (!vars.url) console.warn(vars.param + ", cek url php!"); doPreview() {
if (!this.url) {
console.warn('Url Laporan dibutuhkan!');
return;
}
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: vars.url, url: this.url,
data: FoniaJS.RequestParam(vars.param), data: FoniaJS.RequestParam(this.params),
success: (txt) => { success: (txt) => {
if ('' == txt) { if (!txt) {
FoniaJS.showInfo('Tidak ada data untuk pembuatan laporan !'); FoniaJS.showInfo('Tidak ada data untuk pembuatan laporan !');
return false; return false;
} }
var _wtxt = const modalHtml = `
'<div class="modal fade" id="winAPPPrint" tabindex="-1" role="dialog" data-bs-keyboard="false" data-bs-show="false" data-bs-backdrop="static" aria-labelledby="winAPPPrintLabel" aria-hidden="true">'+ <div class="modal fade" id="winAPPPrint" tabindex="-1" role="dialog" data-bs-keyboard="false" data-bs-show="false" data-bs-backdrop="static" aria-labelledby="winAPPPrintLabel" aria-hidden="true">
'<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-fs" role="document">'+ <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-fs" role="document">
'<div class="modal-content">'+ <div class="modal-content">
'<div class="modal-header"><h5 class="modal-title" id="winAPPPrintLabel">Preview Laporan</h5><div class="ms-auto"><button class="btn me-2" id="tombCetak" type="button" aria-label="Cetak"><i class="bi-printer me-2"></i><span aria-hidden="true">Cetak</span></button><button class="btn" type="button" data-bs-dismiss="modal" aria-label="Tutup"><i class="bi-x-lg me-2"></i><span aria-hidden="true">Tutup</span></button></div></div>'+ <div class="modal-header">
'<div class="modal-body print-body" id="divPrintP">'+txt+'</div>'+ <h5 class="modal-title" id="winAPPPrintLabel">Preview Laporan</h5>
'</div></div></div>'; <div class="ms-auto">
if ($('#winAPPPrint')) $('#winAPPPrint').modal('dispose').remove(); <button class="btn me-2" id="tombCetak" type="button" aria-label="Cetak">
$(_wtxt).on('shown.bs.modal', (e) => { <i class="bi-printer me-2"></i><span aria-hidden="true">Cetak</span>
$('#winAPPPrint').find('#tombCetak').click(() => { </button>
var $printData = $('#dataPrint'); <button class="btn" type="button" data-bs-dismiss="modal" aria-label="Tutup">
<i class="bi-x-lg me-2"></i><span aria-hidden="true">Tutup</span>
</button>
</div>
</div>
<div class="modal-body print-body" id="divPrintP">${txt}</div>
</div>
</div>
</div>
`;
$('#winAPPPrint').modal('dispose').remove();
$(modalHtml)
.on('shown.bs.modal', () => {
$('#winAPPPrint #tombCetak').off('click').on('click', () => {
let $printData = $('#dataPrint');
if (!$printData.length) { if (!$printData.length) {
$printData = $('<div/>', {id:'dataPrint','class':'d-none d-print-block print-body'}).appendTo('body'); $printData = $('<div/>', {
id: 'dataPrint',
class: 'd-none d-print-block print-body'
}).appendTo('body');
} }
$printData.html($('#divPrintP').html()); $printData.html($('#divPrintP').html());
FoniaJS.closeWindow($('#winAPPPrint')); FoniaJS.closeWindow($('#winAPPPrint'));
window.print(); window.print();
}); });
}).on('hidden.bs.modal', (e) => { })
.on('hidden.bs.modal', function () {
$(this).remove(); $(this).remove();
}).modal('show'); })
.modal('show');
}, },
error: (typeof vars.onFailure === "function") ? vars.onFailure : null, error: typeof this.onFailure === 'function' ? this.onFailure : null
}); });
}; return this;
this.construct(options); }
}; }
var PrinterPos = function(options) { /**
var b_default = false; * Class PrinterPos
var _options = { *
'url': '', * Direct Thermal POS Printer Class (via QZ Tray API)
'param': [], *
'printer': null, * @license MIT, https://www.3fonia.com
'cut_paper': "\x1D\x56\x41", * @copyright Copyright (c) 2008-2026, Siau Pheng <[email protected]>
'open_draw': "\x1B\x70\x30\x19\x19", *
'chr_norm': "\x1B\x21\x01", * @param {object} options
'chr_bold': "\x1B\x21\x10", * @param {string} options.url - Endpoint URL Print Page
'chr_sbold': "\x1B\x21\x31", * @param {number} [options.printer=FoniaJS._def_printer] - Printer Name
'chr_uline': "\x1B\x21\x80" * @param {Array} [options.params] - Request payload
}; */
this.construct = function(options) {
if (typeof options == 'object') { class PrinterPos {
$.extend(_options, options); constructor(options = {}) {
} else _options.url = options; this.url = typeof options === 'string' ? options : options.url || '';
if (FoniaJS._def_printer) _options.printer = FoniaJS._def_printer; this.printer = options.printer || (FoniaJS._def_printer ?? null);
}; this.cut_paper = options.cut_paper || '\x1D\x56\x41';
this.detectPrinter = function() { this.open_draw = options.open_draw || '\x1B\x70\x30\x19\x19';
if (!qz.websocket.isActive()) { this.chr_norm = options.chr_norm || '\x1B\x21\x01';
this.chr_bold = options.chr_bold || '\x1B\x21\x10';
this.chr_sbold = options.chr_sbold || '\x1B\x21\x31';
this.chr_uline = options.chr_uline || '\x1B\x21\x80';
this.params = options.params || [];
}
_detectPrinter() {
if (!qz?.websocket?.isActive?.()) {
FoniaJS.showInfo('Status Printer belum Active !'); FoniaJS.showInfo('Status Printer belum Active !');
return false; return false;
} }
return true; return true;
};
this.getPrinters = function() {
return [];
};
this.setPrinter = function(nprint) {
(nprint != null) && (_options.printer = nprint);
};
this.useDefaultPrinter = function() {
b_default = true;
};
this.set_url = function(url) {
_options.url = url;
};
this.add_param = function(par_id, par_val) {
var _getvalue = (par_val) ? par_id + '=' + escape(par_val) : par_id;
_options.param.push(_getvalue);
};
this.exec = function() {
if (!this.detectPrinter()) return;
if (this.b_default) {
var parent = this;
qz.printers.getDefault().then(function(data) {
var nama_p = data;
if (data.name != undefined) {
nama_p = data.name;
} }
parent._options.param.push('Printer='+nama_p);
return parent.do_print(nama_p, parent._options.url, parent._options.param); setPrinter(nprint) {
}, function(data) { if (nprint != null) this.printer = nprint;
FoniaJS.showInfo(data); return this;
});
} else {
var _nprinter = _options.printer;
if (typeof _nprinter === 'object' && _nprinter.name == undefined) {
if (_nprinter.file != undefined) _nprinter = _nprinter.file;
if (_nprinter.host != undefined) _nprinter = _nprinter.host + ":" + _nprinter.port;
} else {
if (_nprinter.name != undefined) _nprinter = _nprinter.name;
if (_nprinter== undefined) _nprinter = 'None';
} }
_options.param.push('Printer='+_nprinter);
this.do_print(_options.printer, _options.url, _options.param); addParam(id, val) {
this.params.push(val !== undefined ? `${id}=${encodeURIComponent(val)}` : id);
return this;
} }
};
this.do_print = function(nama_p, url, params) { async exec() {
var qzcfg = qz.configs.create(nama_p); if (!this._detectPrinter()) return;
let printerName = this.printer;
if (typeof printerName === 'object' && printerName !== null) {
if (printerName.name !== undefined) {
printerName = printerName.name;
} else if (printerName.file !== undefined) {
printerName = printerName.file;
} else if (printerName.host !== undefined) {
printerName = `${printerName.host}:${printerName.port}`;
}
}
printerName = printerName ?? 'None';
this.params.push(`Printer=${printerName}`);
this.doPrint(this.printer, this.url, this.params);
}
doPrint(printerName, url, params) {
const qzcfg = qz.configs.create(printerName);
new Request({ new Request({
url: url, url,
sendParam: params, sendParam: params,
onSuccess: (ajson) => { onSuccess: (ajson) => {
if (typeof ajson === "object") { if (typeof ajson === 'object' && ajson !== null) {
var hasil_cetak = (ajson.type == "escp") ? this.gen_escp(ajson) : this.gen_epl(ajson); const printPayload = ajson.type === 'escp' ? this.genEscp(ajson) : this.genEpl(ajson);
qz.print(qzcfg, hasil_cetak); qz.print(qzcfg, printPayload);
} else { } else {
FoniaJS.showInfo('Error dalam proses Cetak.'); FoniaJS.showInfo('Error dalam proses Cetak.');
} }
} }
}).send(); }).send();
};
this.gen_escp = function(adata) {
var ohead = [];
var osheet = [], ocetak = [];
ohead.push("\x1B\x40");
ohead.push("\x1B\x61\x01");
if (adata.config.logo != null) {
//ohead.push({type:'raw',format:'image',data:adata.config.logo,options:{language:'ESCPOS',dotDensity:'double'}});
//ohead.push("\x1B\x32");
ohead.push({type:'raw',format:'image',flavor:'base64',data:adata.config.logo,options:{language:'ESCPOS',dotDensity:'double'}});
ohead.push("\x1B\x32");
} }
if (parseInt(adata.config.fontsize) == 2) {
_options.chr_norm = "\x1B\x21\x02"; genEscp(adata) {
const ohead = ['\x1B\x40', '\x1B\x61\x01'];
if (adata.config?.logo) {
ohead.push({
type: 'raw',
format: 'image',
flavor: 'base64',
data: adata.config.logo,
options: { language: 'ESCPOS', dotDensity: 'double' }
});
ohead.push('\x1B\x32');
} }
if (adata.header.length > 0) { if (parseInt(adata.config?.fontsize, 10) === 2) {
for (i = 0; i < adata.header.length; i++) { this.chr_norm = '\x1B\x21\x02';
if (i==0 && adata.config.logo==null) ohead.push(_options.chr_bold);
ohead.push(adata.header[i] + "\x0A");
if (i==0 && adata.config.logo==null) ohead.push(_options.chr_norm);
} }
if (Array.isArray(adata.header)) {
adata.header.forEach((headerLine, index) => {
if (index === 0 && !adata.config?.logo) ohead.push(this.chr_bold);
ohead.push(`${headerLine}\x0A`);
if (index === 0 && !adata.config?.logo) ohead.push(this.chr_norm);
});
} }
for (s = 0; s < adata.content.length; s++) {
if (adata.content[s].length == 0) continue; let ocetak = [];
osheet = ohead.slice(0); if (Array.isArray(adata.content)) {
for (i = 0; i < adata.content[s].length; i++) { adata.content.forEach((sheetContent) => {
var tmp_cont = adata.content[s][i]; if (!sheetContent?.length) return;
tmp_cont = tmp_cont.replace('_SBOLD_', _options.chr_sbold) const osheet = [...ohead];
.replace('_BOLD_', _options.chr_bold) sheetContent.forEach((line) => {
.replace('_NORM_', _options.chr_norm) const formattedLine = line
.replace('_ULINE_', _options.chr_uline); .replace('_SBOLD_', this.chr_sbold)
osheet.push(tmp_cont + "\x0A"); .replace('_BOLD_', this.chr_bold)
} .replace('_NORM_', this.chr_norm)
if (adata.config.cutpaper) { .replace('_ULINE_', this.chr_uline);
osheet.push(_options.cut_paper + "\x0A"); osheet.push(`${formattedLine}\x0A`);
});
if (adata.config?.cutpaper) {
osheet.push(`${this.cut_paper}\x0A`);
} }
ocetak = ocetak.concat(osheet); ocetak = ocetak.concat(osheet);
});
} }
var notaout = [];
if (adata.config.opendraw) { let notaout = [];
notaout.push(_options.open_draw); if (adata.config?.opendraw) {
notaout.push(this.open_draw);
} }
for (i = 0; i < adata.config.times; i++) { const times = adata.config?.times || 1;
for (let i = 0; i < times; i++) {
notaout = notaout.concat(ocetak); notaout = notaout.concat(ocetak);
} }
return notaout; return notaout;
};
this.gen_epl = function(adata) {
var cetak = [];
for (i = 0; i < adata.content.length; i++) {
cetak.push(adata.content[i] + "\r\n");
} }
var notaout = [];
for (i = 0; i < adata.config.times; i++) { genEpl(adata) {
const cetak = (adata.content || []).map((line) => `${line}\r\n`);
let notaout = [];
const times = adata.config?.times || 1;
for (let i = 0; i < times; i++) {
notaout = notaout.concat(cetak); notaout = notaout.concat(cetak);
} }
return notaout; return notaout;
}; }
this.construct(options); }
};
+80 -53
View File
@@ -1,60 +1,87 @@
/******************************************************************* /*******************************************************************
Module : /assets/js/simulator.js Module : /assets/js/simulator.js
Desc. : JS Class Simulator Data dalam Code Desc. : JS Class Simulator Data dalam Code
Created By : Siau Pheng ([email protected]). Created By : Siau Pheng ([email protected]).
Created Date : March 18th, 2021. Created Date : March 18th, 2021.
Last Modified : December 26th, 2025. Last Modified : November 2nd, 2026.
(c) 3FONIA Software; WWW.3FONIA.COM. (c) 3FONIA Software; WWW.3FONIA.COM.
*******************************************************************
*
* Class Simulator
*
* Simulator Data untuk sinkron data dengan JSON
*
* @license MIT, https://www.3fonia.com
* @copyright Copyright (c) 2008-2026, Siau Pheng <[email protected]>
*
* @param {object} options
* @param {string} options.url - Endpoint URL Print Page
* @param {Array} [options.params] - Request payload
*/
*******************************************************************/ class Simulator {
constructor(options = {}) {
this.url = typeof options === 'string' ? options : options.url || '';
this.params = options.params || [];
}
var Simulator = function(options){ addParam(id, val) {
var vars = { this.params.push(val !== undefined ? `${id}=${encodeURIComponent(val)}` : id);
'url': '', return this;
'param': [] }
};
this.construct = function(options){ doPreview() {
if (typeof options == 'object') { if (!this.url) {
$.extend(vars, options); console.warn('Url Simulator dibutuhkan!');
} else vars.url = options; return;
}; }
this.set_url = function (url){
vars.url = url;
};
this.add_param = function (par_id, par_val){
var _getvalue = (par_val) ? par_id + "=" + escape(par_val) : par_id;
vars.param.push(_getvalue);
},
this.doPreview = function(){
if (!vars.url) console.warn(vars.param + ", cek url php!");
$.ajax({ $.ajax({
type: 'POST', type: 'POST',
url: vars.url, url: this.url,
data: FoniaJS.RequestParam(vars.param), data: FoniaJS.RequestParam(this.params),
success: function(data){ dataType: 'json',
if (data.length == 0) { error: typeof onFailure === 'function' ? onFailure : null,
success: (data) => {
if (!data || data.length === 0) {
FoniaJS.showInfo('Tidak ada data !'); FoniaJS.showInfo('Tidak ada data !');
return false; return false;
} }
var _divd = '';
for (var no = 0; no < data.length; no++) { const divContent = data
_divd += '<div class="sim-code px-2 py-2 mb-1 border border-info">' + data[no] + '</div>'; .map(item => `<div class="sim-code px-2 py-2 mb-1 border border-info">${item}</div>`)
} .join('');
var _wtxt =
'<div class="modal fade" id="winAPPSim" tabindex="-1" role="dialog" data-bs-keyboard="false" data-bs-show="false" data-bs-backdrop="static" aria-labelledby="winAPPSimLabel" aria-hidden="true">'+ const modalHtml = `
'<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-fs" role="document">'+ <div class="modal fade" id="winAPPSim" tabindex="-1" role="dialog" data-bs-keyboard="false" data-bs-show="false" data-bs-backdrop="static" aria-labelledby="winAPPSimLabel" aria-hidden="true">
'<div class="modal-content">'+ <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-fs" role="document">
'<div class="modal-header"><h5 class="modal-title" id="winAPPSimLabel">Code Simulator</h5><div class="ms-auto"><button class="btn me-2" id="tombSalin" type="button" aria-label="Salin Semua"><i class="bi-copy me-2"></i><span aria-hidden="true">Salin Semua</span></button><button class="btn" type="button" data-bs-dismiss="modal" aria-label="Tutup"><i class="bi-x-lg me-2"></i><span aria-hidden="true">Tutup</span></button></div></div>'+ <div class="modal-content">
'<div class="modal-body">'+_divd+'</div>'+ <div class="modal-header">
'</div></div></div>'; <h5 class="modal-title" id="winAPPSimLabel">Code Simulator</h5>
if ($('#winAPPSim')) $('#winAPPSim').modal('dispose').remove(); <div class="ms-auto">
$(_wtxt).on('shown.bs.modal', function(e){ <button class="btn me-2" id="tombSalin" type="button" aria-label="Salin Semua">
$('#winAPPSim').find('#tombSalin').click(function(){ <i class="bi-copy me-2"></i><span aria-hidden="true">Salin Semua</span>
</button>
<button class="btn" type="button" data-bs-dismiss="modal" aria-label="Tutup">
<i class="bi-x-lg me-2"></i><span aria-hidden="true">Tutup</span>
</button>
</div>
</div>
<div class="modal-body">${divContent}</div>
</div>
</div>
</div>`;
$('#winAPPSim').modal('dispose').remove();
$(modalHtml)
.on('shown.bs.modal', function () {
const $modal = $(this);
// Copy all code blocks
$modal.find('#tombSalin').on('click', () => {
window.getSelection().removeAllRanges(); window.getSelection().removeAllRanges();
$('.sim-code').each(function(i, ele) { $('.sim-code').each((_, ele) => {
var range = document.createRange(); const range = document.createRange();
range.selectNode(ele); range.selectNode(ele);
window.getSelection().addRange(range); window.getSelection().addRange(range);
}); });
@@ -62,23 +89,23 @@ var Simulator = function(options){
window.getSelection().removeAllRanges(); window.getSelection().removeAllRanges();
FoniaJS.showInfo('Sukses salin semua Kode !'); FoniaJS.showInfo('Sukses salin semua Kode !');
}); });
$('#winAPPSim').find('.sim-code').click(function(){
var range = document.createRange(); // Copy individual code block and hide it
$modal.find('.sim-code').on('click', function () {
const range = document.createRange();
range.selectNode(this); range.selectNode(this);
window.getSelection().removeAllRanges(); window.getSelection().removeAllRanges();
window.getSelection().addRange(range); window.getSelection().addRange(range);
document.execCommand('copy'); document.execCommand('copy');
window.getSelection().removeAllRanges(); window.getSelection().removeAllRanges();
//$(this).addClass('bg-success');
$(this).addClass('d-none'); $(this).addClass('d-none');
}); });
}).on('hidden.bs.modal', function(e){ })
.on('hidden.bs.modal', function () {
$(this).remove(); $(this).remove();
}).modal('show'); })
}, .modal('show');
error: (typeof vars.onFailure === "function") ? vars.onFailure : null, }
dataType: 'json'
}); });
}; }
this.construct(options); }
};
+5 -5
View File
@@ -18,12 +18,12 @@
], ],
"require": { "require": {
"php": ">=8.3", "php": ">=8.3",
"flightphp/core": "^3.18", "flightphp/core": "^3.19",
"flightphp/session": "^0.3", "flightphp/session": "^0.3",
"mpdf/mpdf": ">=8.0", "mpdf/mpdf": "^8.3",
"avadim/fast-excel-writer": "^6.17", "avadim/fast-excel-writer": "^6.19",
"matthiasmullie/minify": ">=1.3", "matthiasmullie/minify": "^1.3",
"endroid/qr-code": ">=4.4" "endroid/qr-code": "^6.1"
}, },
"autoload": { "autoload": {
"classmap": ["src/"], "classmap": ["src/"],
+3 -3
View File
@@ -5,7 +5,7 @@
Module : /App/Auth.php Module : /App/Auth.php
Created By : Siau Pheng ([email protected]). Created By : Siau Pheng ([email protected]).
Created Date : March 16th, 2008. Created Date : March 16th, 2008.
Last Modified : October 21st, 2026. Last Modified : October 31st, 2026.
(c) 3FONIA Software; WWW.3FONIA.COM. (c) 3FONIA Software; WWW.3FONIA.COM.
@@ -86,8 +86,8 @@ final class Auth {
public function user_log(): void { public function user_log(): void {
$_user_id = $this->session->get('WEB_USER')['UserID'] ?? 0; $_user_id = $this->session->get('WEB_USER')['UserID'] ?? 0;
if ($_user_id === 0) return; if ($_user_id === 0) return;
$a_hasil = $this->db->fetchRow('SELECT * FROM app_logs WHERE UserID=? ORDER BY Last_Date DESC LIMIT 1', [$_user_id])->getData(); $a_hasil = $this->db->fetchRow('SELECT * FROM app_logs WHERE UserID=? ORDER BY Last_Date DESC LIMIT 1', [$_user_id]);
if (count($a_hasil) > 0) { if ($a_hasil) {
$this->db->update('app_operator', [ 'Last_IP' => $a_hasil['Last_IP'], 'Last_Date' => $a_hasil['Last_Date'] ], 'UserID=?', [$_user_id]); $this->db->update('app_operator', [ 'Last_IP' => $a_hasil['Last_IP'], 'Last_Date' => $a_hasil['Last_Date'] ], 'UserID=?', [$_user_id]);
} }
$this->db->runQuery('INSERT IGNORE INTO app_logs SELECT UserID,Token,IP,DateStamp FROM app_token WHERE Token=?', [$this->session->get('APP_TOKEN')]); $this->db->runQuery('INSERT IGNORE INTO app_logs SELECT UserID,Token,IP,DateStamp FROM app_token WHERE Token=?', [$this->session->get('APP_TOKEN')]);
+35 -28
View File
@@ -5,7 +5,7 @@
Module : /Data/Cache.php Module : /Data/Cache.php
Created By : Siau Pheng ([email protected]). Created By : Siau Pheng ([email protected]).
Created Date : March 16th, 2008. Created Date : March 16th, 2008.
Last Modified : October 12th, 2026. Last Modified : November 4th, 2026.
(c) 3FONIA Software; WWW.3FONIA.COM. (c) 3FONIA Software; WWW.3FONIA.COM.
@@ -61,7 +61,7 @@ final class Cache {
$this->web_user = $app->session()->get('WEB_USER') ?? []; $this->web_user = $app->session()->get('WEB_USER') ?? [];
$this->is_login = (count($this->web_user) > 0); $this->is_login = (count($this->web_user) > 0);
$rootdir = (defined('PROJECT_ROOT')) ? PROJECT_ROOT : $app->get('app.project_root'); $rootdir = (defined('PROJECT_ROOT')) ? constant('PROJECT_ROOT') : $app->get('app.project_root');
$this->cachedir = $rootdir . '/temp/cache/'; $this->cachedir = $rootdir . '/temp/cache/';
$this->localedir = $rootdir . '/app/Scripts/locale/'; $this->localedir = $rootdir . '/app/Scripts/locale/';
$this->jsapp = $rootdir . '/app/Scripts/'; $this->jsapp = $rootdir . '/app/Scripts/';
@@ -157,24 +157,22 @@ final class Cache {
private function create_cache(string $type = "css", array $afile = [], string $cachefile = ""): void { private function create_cache(string $type = "css", array $afile = [], string $cachefile = ""): void {
$contents = ''; $smini = null; $contents = ''; $smini = null;
$bpublic = ($this->app->request()->ip === '127.0.0.1') ? false : true; if (!$this->IS_DEV) {
if ($bpublic === true) {
if ($type === "css") { if ($type === "css") {
$smini = new Minify\CSS; $smini = new Minify\CSS;
} else { } else {
$smini = new Minify\JS; $smini = new Minify\JS;
} }
} }
foreach ($afile as $nfile) { foreach ($afile as $file) {
if (file_exists($nfile)) { if (!file_exists($file)) continue;
if ($bpublic === true) { if (!$this->IS_DEV) {
$smini->add($nfile); $smini->add($file);
} else { } else {
$contents .= "\n". file_get_contents($nfile); $contents .= "\n". file_get_contents($file);
} }
} }
} if (!$this->IS_DEV) $contents = $smini->minify();
if ($bpublic) $contents = $smini->minify();
file_put_contents($this->cachedir . $cachefile, $contents); file_put_contents($this->cachedir . $cachefile, $contents);
} }
@@ -195,38 +193,43 @@ final class Cache {
public function Cache(string $mode = "index"): array { public function Cache(string $mode = "index"): array {
if ($mode === 'index') { if ($mode === 'index') {
$this->ini['index']['app'] = (string) $this->db->fetchField("SELECT JS FROM app_operator_profile WHERE UserID=?", [$this->web_user['UserID']]) ?? ''; $this->ini['index']['app'] = (string) $this->db->fetchField("SELECT JS FROM app_operator_profile WHERE UserID=?", [$this->web_user['UserID']]) ?? '';
$_menu = $this->db->fetchField("SELECT CONVERT(DECODE(Menu,?) USING UTF8MB4) Menu FROM app_operator WHERE UserID=?", [$this->web_app['PARENT_CODE'], $this->web_user['UserID']]) ?? ''; $_menu = (string) $this->db->fetchField("SELECT CONVERT(DECODE(Menu,?) USING UTF8MB4) Menu FROM app_operator WHERE UserID=?", [$this->web_app['PARENT_CODE'], $this->web_user['UserID']]) ?? '';
$_gmenu = ''; $_gmenu = '';
if ($this->web_user['Grup_MenuID'] > 0) $_gmenu = $this->db->fetchField('SELECT CONVERT(DECODE(Menu,?) USING UTF8MB4) Menu FROM app_menu_grup WHERE Grup_MenuID=?', [$this->web_app['PARENT_CODE'], $this->web_user['Grup_MenuID']]) ?? ''; if ($this->web_user['Grup_MenuID'] > 0) $_gmenu = (string) $this->db->fetchField('SELECT CONVERT(DECODE(Menu,?) USING UTF8MB4) Menu FROM app_menu_grup WHERE Grup_MenuID=?', [$this->web_app['PARENT_CODE'], $this->web_user['Grup_MenuID']]) ?? '';
$this->my_menu = array_filter(array_unique(explode(",", $_gmenu .",". $_menu))); $this->my_menu = array_filter(array_unique(explode(",", $_gmenu .",". $_menu)));
} }
$is_modif = false; $is_modif = false;
foreach (['css','js','app'] as $type) { foreach (['css','js','app'] as $type) {
$is_index_app = ($mode === 'index' && $type === 'app'); $is_iapp = ($mode === 'index' && $type === 'app');
if (empty($this->ini[$mode][$type]) || !file_exists($this->cachedir . $this->ini[$mode][$type]) || ($this->IS_DEV)) { if (!empty($this->ini[$mode][$type]) &&
file_exists($this->cachedir . $this->ini[$mode][$type]) &&
!$is_iapp && !$this->IS_DEV) continue;
[ $afile, $lastmod ] = $this->gen_file($mode, $type); [ $afile, $lastmod ] = $this->gen_file($mode, $type);
$cachefile = md5($mode . '-' . $type . '-' . $lastmod) . ($type === 'css' ? '.css' : '.js'); $cachefile = md5($mode.'-'.$type.'-'. ($is_iapp?(string) $this->web_user['UserID'].'-':'') .$lastmod) . ($type === 'css' ? '.css' : '.js');
if ($is_index_app) $cachefile = md5('index-app-' . (string) $this->web_user['UserID'] . $lastmod) . '.js';
if (($this->ini[$mode][$type] ?? false) === $cachefile &&
file_exists($this->cachedir . $this->ini[$mode][$type]) &&
!$this->IS_DEV) continue;
$this->create_cache($type, $afile, $cachefile); $this->create_cache($type, $afile, $cachefile);
$this->ini[$mode][$type] = $cachefile; $this->ini[$mode][$type] = $cachefile;
if ($is_index_app) $this->db->runQuery("INSERT INTO app_operator_profile (UserID,JS) VALUES (?, ?) ON DUPLICATE KEY UPDATE JS=VALUES(JS)", [$this->web_user['UserID'], $cachefile]); if ($is_iapp) $this->db->runQuery("INSERT INTO app_operator_profile (UserID,JS) VALUES (?, ?) ON DUPLICATE KEY UPDATE JS=VALUES(JS)", [$this->web_user['UserID'], $cachefile]);
$is_modif = true; $is_modif = true;
} }
}
$acache = [ 'CSS' => [], 'JS' => [], 'JSX' => [] ]; $acache = [ 'CSS' => [], 'JS' => [], 'JSX' => [] ];
foreach ($this->ini[$mode] as $_type => $_file) { foreach ($this->ini[$mode] as $_type => $_file) {
if (file_exists($this->cachedir . $_file)) { if (!file_exists($this->cachedir . $_file)) continue;
if ($_type === 'css') { if ($_type === 'css') {
$acache['CSS'][] = 'cache/' . $_file; $acache['CSS'][] = 'cache/' . $_file;
} else $acache['JS'][] = 'cache/' . $_file; } else $acache['JS'][] = 'cache/' . $_file;
} }
}
if ($is_modif === true) $this->save_ini(); if ($is_modif === true) $this->save_ini();
$nonce = $this->app->get('csp_nonce'); $nonce = $this->app->get('csp_nonce');
$_secret = $this->web_app['APP_CODE'] .";". $this->web_app['APP_SID'] .";". $this->app->request()->getVar('HTTP_HOST') .";". "http://".$this->app->request()->getVar('HTTP_HOST') .";". isMobile() .";". ($this->web_app['AUTH_LEVEL']?$this->web_app['AUTH_LEVEL']:0); $_secret = $this->web_app['APP_CODE'] .";". $this->web_app['APP_SID'] .";". $this->app->request()->getVar('HTTP_HOST') .";". "http://".$this->app->request()->getVar('HTTP_HOST') .";". isMobile() .";". ($this->web_app['AUTH_LEVEL'] ?? 0);
$_suser = ($this->is_login) ? $this->web_user['Username'] .";". $this->web_user['UserID'] .";". $this->web_user['Grup_MenuID'] .";". $this->web_user['Level'] : "nobody;999;999;9"; $_suser = ($this->is_login) ? $this->web_user['Username'] .";". $this->web_user['UserID'] .";". $this->web_user['Grup_MenuID'] .";". $this->web_user['Level'] : "nobody;999;999;9";
$acache['JSX'][] = '<script nonce="'.$nonce.'" type="text/javascript">'; $acache['JSX'][] = '<script nonce="'.$nonce.'" type="text/javascript">';
@@ -240,11 +243,15 @@ final class Cache {
} }
public function Make_Cache(array $amode = ['login', 'index', 'monitor']): array { public function Make_Cache(array $amode = ['login', 'index', 'monitor']): array {
$_alog = [];
$is_modif = false; $is_modif = false;
$is_runway = (defined('RUNWAY_CMD')) ? constant('RUNWAY_CMD') : false;
foreach ($amode as $mode) { foreach ($amode as $mode) {
foreach (['css','js','app'] as $type) { foreach (['css','js','app'] as $type) {
if ($mode === 'index' && $type === 'app') continue; if ($mode === 'index' && $type === 'app') continue;
if (empty($this->ini[$mode][$type]) || !file_exists($this->cachedir . $this->ini[$mode][$type])) { if (!empty($this->ini[$mode][$type]) && file_exists($this->cachedir . $this->ini[$mode][$type]) && !$is_runway) continue;
if ($is_runway) $_alog[] = $mode.'-'.$type.' -> '.$this->ini[$mode][$type];
[ $afile, $lastmod ] = $this->gen_file($mode, $type); [ $afile, $lastmod ] = $this->gen_file($mode, $type);
$cachefile = md5($mode . '-' . $type . '-' . $lastmod) . ($type === 'css' ? '.css' : '.js'); $cachefile = md5($mode . '-' . $type . '-' . $lastmod) . ($type === 'css' ? '.css' : '.js');
$this->create_cache($type, $afile, $cachefile); $this->create_cache($type, $afile, $cachefile);
@@ -252,14 +259,14 @@ final class Cache {
$is_modif = true; $is_modif = true;
} }
} }
}
if ($is_modif === true) $this->save_ini(); if ($is_modif === true) $this->save_ini();
if (in_array('index', $amode)) { if (in_array('index', $amode)) {
$agrup = $this->db->fetchAll('SELECT Grup_MenuID,CONVERT(DECODE(Menu,?) USING UTF8MB4) Menu FROM app_menu_grup', [$this->web_app['PARENT_CODE']]); $agrup = $this->db->fetchAll('SELECT Grup_MenuID,CONVERT(DECODE(Menu,?) USING UTF8MB4) Menu FROM app_menu_grup', [$this->web_app['PARENT_CODE']]);
$auser = $this->db->fetchAll("SELECT A.*,IFNULL(B.JS,'') JS FROM (SELECT UserID,Grup_MenuID,CONVERT(DECODE(Menu,?) USING UTF8MB4) Menu FROM app_operator) A LEFT JOIN app_operator_profile B ON (A.UserID=B.UserID)", [$this->web_app['PARENT_CODE']]); $auser = $this->db->fetchAll("SELECT A.*,IFNULL(B.JS,'') JS FROM (SELECT UserID,Username,Grup_MenuID,CONVERT(DECODE(Menu,?) USING UTF8MB4) Menu FROM app_operator) A LEFT JOIN app_operator_profile B ON (A.UserID=B.UserID)", [$this->web_app['PARENT_CODE']]);
foreach ($auser as $user) { foreach ($auser as $user) {
if (empty($user['JS']) || !file_exists($this->cachedir . $user['JS'])) { if (!empty($user['JS']) && file_exists($this->cachedir . $user['JS']) && !$is_runway) continue;
if ($is_runway) $_alog[] = 'index-app: '.$user['Username'].' -> '.$user['JS'];
$this->my_menu = array_filter(array_unique(explode(",", $user['Menu'] .",". ($agrup[$user['Grup_MenuID']]['Menu'] ?? '')))); $this->my_menu = array_filter(array_unique(explode(",", $user['Menu'] .",". ($agrup[$user['Grup_MenuID']]['Menu'] ?? ''))));
[ $afile, $lastmod ] = $this->gen_file('index', 'app'); [ $afile, $lastmod ] = $this->gen_file('index', 'app');
@@ -268,8 +275,8 @@ final class Cache {
$this->db->runQuery("INSERT INTO app_operator_profile (UserID,JS) VALUES (?, ?) ON DUPLICATE KEY UPDATE JS=VALUES(JS)", [$user['UserID'], $cachefile]); $this->db->runQuery("INSERT INTO app_operator_profile (UserID,JS) VALUES (?, ?) ON DUPLICATE KEY UPDATE JS=VALUES(JS)", [$user['UserID'], $cachefile]);
} }
} }
} $_alog[] = 'Processed of '.(string) count($auser).' users.';
return [ 'status' => 1, 'user_count' => count($auser) ]; return [ 'status' => 1, 'log' => $_alog ];
} }
} }
+39 -1
View File
@@ -6,7 +6,7 @@
Desc. : Fungsi Custom Lain Lain Desc. : Fungsi Custom Lain Lain
Created By : Siau Pheng (siaupheng@3fonia.com). Created By : Siau Pheng (siaupheng@3fonia.com).
Created Date : January 27th, 2008. Created Date : January 27th, 2008.
Last Modified : August 21st, 2026. Last Modified : October 27th, 2026.
(c) 3FONIA Software; WWW.3FONIA.COM. (c) 3FONIA Software; WWW.3FONIA.COM.
@@ -362,3 +362,41 @@ if (!function_exists('random_color')) {
return "rgba(".$col_r.",".$col_g.",".$col_b.",".$trans.")"; return "rgba(".$col_r.",".$col_g.",".$col_b.",".$trans.")";
} }
} }
if (!function_exists('gen_uuidv4')) {
function gen_uuidv4(): string {
$data = random_bytes(16);
// Set version to 0100 (UUID v4)
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
// Set bits 6-7 to 10
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
}
if (!function_exists('gen_uuidv7')) {
function gen_uuidv7(int $time=0): string {
// Get timestamp in milliseconds (48 bits)
if (empty($time)) $time = (int) floor(microtime(true) * 1000);
// Generate 16 bytes of random data
$randomBytes = random_bytes(16);
// Pack the 48-bit timestamp into the first 6 bytes
$timeHex = str_pad(dechex($time), 12, '0', STR_PAD_LEFT);
$bytes = hex2bin($timeHex);
// Append 10 bytes of randomness (we need 16 total bytes)
$bytes .= substr($randomBytes, 0, 10);
// Apply the version bits (Version 7 -> 0b0111) onto byte 6
$bytes[6] = chr((ord($bytes[6]) & 0x0f) | 0x70);
// Apply the variant bits (Variant 1 -> 0b10xx) onto byte 8
$bytes[8] = chr((ord($bytes[8]) & 0x3f) | 0x80);
// Unpack to hex string and format with hyphens
$hex = bin2hex($bytes);
return sprintf('%08s-%04s-%04s-%04s-%012s',
substr($hex, 0, 8),
substr($hex, 8, 4),
substr($hex, 12, 4),
substr($hex, 16, 4),
substr($hex, 20, 12)
);
}
}
+2 -2
View File
@@ -5,7 +5,7 @@
Module : /Web/Menu.php Module : /Web/Menu.php
Created By : Siau Pheng (siaupheng@3fonia.com). Created By : Siau Pheng (siaupheng@3fonia.com).
Created Date : January 16th, 2008. Created Date : January 16th, 2008.
Last Modified : October 21st, 2026. Last Modified : October 30th, 2026.
(c) 3FONIA Software; WWW.3FONIA.COM. (c) 3FONIA Software; WWW.3FONIA.COM.
@@ -141,7 +141,7 @@ final class Menu {
$href1 = '//127.0.0.1/'; $href1 = '//127.0.0.1/';
$href2 = ""; $href2 = "";
} else { } else {
$_host = $this->app->request()->getVar('HTTP_ORIGIN') ?? $this->app->request()->getVar('HTTP_HOST') ?? $this->web_app['PARENT_SITE']; $_host = $_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_HOST'] ?? $this->web_app['PARENT_SITE'];
$_host = str_replace(['http://','https://'], "", $_host); $_host = str_replace(['http://','https://'], "", $_host);
if ($this->web_app['PARENT_SUB'] === true) { if ($this->web_app['PARENT_SUB'] === true) {
$_subs = explode('.', $_host); $_subs = explode('.', $_host);