0
1
Fork 0

DB result rows now handled as objects

This commit is contained in:
Juan Ferrer 2022-05-28 17:49:46 +02:00
parent fc22db73f2
commit 0141eea534
39 changed files with 679 additions and 695 deletions

View File

@ -6,7 +6,7 @@ Hedera.Conf = new Class({
this.$.userModel.setInfo('c', 'myClient', 'hedera'); this.$.userModel.setInfo('c', 'myClient', 'hedera');
this.$.userModel.setInfo('u', 'myUser', 'account'); this.$.userModel.setInfo('u', 'myUser', 'account');
if (this.hash.get('verificationToken')) if (this.hash.$.verificationToken)
this.onPassChangeClick(); this.onPassChangeClick();
} }
@ -15,7 +15,7 @@ Hedera.Conf = new Class({
this.$.newPassword.value = ''; this.$.newPassword.value = '';
this.$.repeatPassword.value = ''; this.$.repeatPassword.value = '';
var verificationToken = this.hash.get('verificationToken'); var verificationToken = this.hash.$.verificationToken;
this.$.oldPassword.style.display = verificationToken ? 'none' : 'block'; this.$.oldPassword.style.display = verificationToken ? 'none' : 'block';
this.$.changePassword.show(); this.$.changePassword.show();
@ -36,7 +36,7 @@ Hedera.Conf = new Class({
if (newPassword !== repeatedPassword) if (newPassword !== repeatedPassword)
throw new Error(_('Passwords doesn\'t match')); throw new Error(_('Passwords doesn\'t match'));
var verificationToken = this.hash.get('verificationToken'); var verificationToken = this.hash.$.verificationToken;
var params = {newPassword: newPassword}; var params = {newPassword: newPassword};
if (verificationToken) { if (verificationToken) {
@ -65,7 +65,7 @@ Hedera.Conf = new Class({
} else { } else {
Htk.Toast.showError(error.message); Htk.Toast.showError(error.message);
if (this.hash.get('verificationToken')) if (this.hash.$.verificationToken)
this.$.newPassword.select(); this.$.newPassword.select();
else else
this.$.oldPassword.select(); this.$.oldPassword.select();

View File

@ -11,7 +11,10 @@
param="user-name"/> param="user-name"/>
</div> </div>
<div id="form" class="users"> <div id="form" class="users">
<htk-repeater form-id="iter" renderer="rendererFunc" class="htk-list box vn-w-xs"> <htk-repeater
form-id="iter"
renderer="rendererFunc"
class="htk-list box vn-w-xs">
<db-model property="model"> <db-model property="model">
<custom> <custom>
SELECT u.id, u.name, u.nickname, u.active SELECT u.id, u.name, u.nickname, u.active

View File

@ -3,7 +3,7 @@ Hedera.Users = new Class({
Extends: Hedera.Form Extends: Hedera.Form
,rendererFunc: function(scope, form) { ,rendererFunc: function(scope, form) {
var isEnabled = form.get('active') var isEnabled = form.$.active
scope.$.disabled.style.display = isEnabled ? scope.$.disabled.style.display = isEnabled ?
'none' : 'block'; 'none' : 'block';
scope.$.impersonate.node.style.display = isEnabled ? scope.$.impersonate.node.style.display = isEnabled ?

View File

@ -24,7 +24,7 @@ Hedera.Location = new Class({
} }
,onLocationsDone: function(resultSet) { ,onLocationsDone: function(resultSet) {
this.locations = resultSet.fetchResult(); this.locations = resultSet.fetchData();
this.allLoaded(); this.allLoaded();
} }
@ -47,9 +47,8 @@ Hedera.Location = new Class({
var div = this.$.form; var div = this.$.form;
var gmap = new google.maps.Map(div, options); var gmap = new google.maps.Map(div, options);
if (this.locations) for (const location of this.locations)
while (this.locations.next()) this.createMarker(location, gmap);
this.createMarker(this.locations, gmap);
} }
,createMarker: function(location, gmap) { ,createMarker: function(location, gmap) {
@ -57,28 +56,28 @@ Hedera.Location = new Class({
div.className = 'marker'; div.className = 'marker';
var h = document.createElement('h3'); var h = document.createElement('h3');
h.appendChild(document.createTextNode(location.get('title'))); h.appendChild(document.createTextNode(location.title));
div.appendChild(h); div.appendChild(h);
var p = document.createElement('p'); var p = document.createElement('p');
p.appendChild(document.createTextNode(location.get('address'))); p.appendChild(document.createTextNode(location.address));
div.appendChild(p); div.appendChild(p);
var p = document.createElement('p'); var p = document.createElement('p');
p.appendChild(document.createTextNode(location.get('postcode') +' '+ location.get('city'))); p.appendChild(document.createTextNode(location.postcode +' '+ location.city));
div.appendChild(p); div.appendChild(p);
var p = document.createElement('p'); var p = document.createElement('p');
p.appendChild(document.createTextNode(location.get('province'))); p.appendChild(document.createTextNode(location.province));
div.appendChild(p); div.appendChild(p);
var p = document.createElement('p'); var p = document.createElement('p');
p.appendChild(document.createTextNode(location.get('phone'))); p.appendChild(document.createTextNode(location.phone));
div.appendChild(p); div.appendChild(p);
var lat = new google.maps.LatLng( var lat = new google.maps.LatLng(
location.get('lat'), location.lat,
location.get('lng') location.lng
); );
var marker = new google.maps.Marker({ var marker = new google.maps.Marker({
@ -95,7 +94,7 @@ Hedera.Location = new Class({
this.openInfoWindow.bind(this, infoWindow, gmap, marker)); this.openInfoWindow.bind(this, infoWindow, gmap, marker));
if (Vn.Locale.language if (Vn.Locale.language
&& Vn.Locale.language == location.get('language')) && Vn.Locale.language == location.language)
this.openInfoWindow(infoWindow, gmap, marker); this.openInfoWindow(infoWindow, gmap, marker);
} }

View File

@ -30,7 +30,7 @@ Hedera.Basket = new Class({
} }
,subtotal: function(form) { ,subtotal: function(form) {
return form.get('amount') * form.get('price'); return form.$.amount * form.$.price;
} }
}); });

View File

@ -67,7 +67,7 @@ Hedera.Catalog = new Class({
} }
,onBasketReady: function(form) { ,onBasketReady: function(form) {
if (form.get('method') != 'PICKUP') if (form.$.method != 'PICKUP')
Vn.Node.setText(this.$.method, _('Agency')); Vn.Node.setText(this.$.method, _('Agency'));
else else
Vn.Node.setText(this.$.method, _('Warehouse')); Vn.Node.setText(this.$.method, _('Warehouse'));
@ -100,8 +100,8 @@ Hedera.Catalog = new Class({
,realmRenderer: function(builder, form) { ,realmRenderer: function(builder, form) {
var link = builder.$.link; var link = builder.$.link;
link.href = this.hash.make({ link.href = this.hash.make({
form: this.hash.get('form'), form: this.hash.$.form,
realm: form.get('id') realm: form.$.id
}); });
} }
@ -209,7 +209,7 @@ Hedera.Catalog = new Class({
this.onEraseClick(); this.onEraseClick();
this.$.card.row = form.row; this.$.card.row = form.row;
this.$.cardItem.value = form.get('id'); this.$.cardItem.value = form.$.id;
this.$.cardPopup.show(event.currentTarget); this.$.cardPopup.show(event.currentTarget);
} }
@ -425,23 +425,23 @@ Vn.Filter = new Class({
let row = -1; let row = -1;
const model = this._model; const model = this._model;
let showValue = '';
this._emptyLabel = true;
if (model) { if (model) {
if (this._model.ready) if (model.ready) {
row = model.searchByIndex(this._valueColumnIndex, this._value); row = model.searchByIndex(this._valueColumnIndex, this._value);
if (row != -1) { if (row != -1) {
var label = model.getByIndex(row, this._showColumnIndex); var label = model.getByIndex(row, this._showColumnIndex);
this._label.nodeValue = label; showValue = label;
this._emptyLabel = false; this._emptyLabel = false;
} else { }
this._emptyLabel = true; } else
this._label.nodeValue = _('Loading...'); showValue = _('Loading...');
}
} else {
this._emptyLabel = true;
this._label.nodeValue = '';
} }
this._label.nodeValue = showValue;
} }
}); });

View File

@ -233,8 +233,8 @@
background-color: white; background-color: white;
flex-direction: column; flex-direction: column;
width: 210px; width: 240px;
height: 375px; height: 405px;
overflow: hidden; overflow: hidden;
} }
.grid-view .item-box:hover { .grid-view .item-box:hover {
@ -244,8 +244,8 @@
margin: 10px; margin: 10px;
} }
.grid-view .item-box > .htk-image { .grid-view .item-box > .htk-image {
width: 210px; width: 240px;
height: 210px; height: 240px;
} }
.grid-view .item-box > .item-info { .grid-view .item-box > .item-info {
flex: auto; flex: auto;

View File

@ -18,12 +18,7 @@ Hedera.Checkout = new Class({
return; return;
var date; var date;
const row = orderForm.$ || defaultsForm.$;
if (orderForm.numRows > 0) {
var i = orderForm;
date = i.get('sent');
} else
var i = defaultsForm;
if (!date || date.getTime() < (new Date()).getTime()) { if (!date || date.getTime() < (new Date()).getTime()) {
date = new Date(); date = new Date();
@ -40,16 +35,16 @@ Hedera.Checkout = new Class({
break; break;
} }
if (i.get('deliveryMethod') != 'PICKUP') if (row.deliveryMethod != 'PICKUP')
addDays++; addDays++;
date.setDate(date.getDate() + addDays); date.setDate(date.getDate() + addDays);
} }
this.$.date.value = date; this.$.date.value = date;
this.$.method.value = i.get('deliveryMethod'); this.$.method.value = row.deliveryMethod;
this.$.agency.value = i.get('agencyModeFk'); this.$.agency.value = row.agencyModeFk;
this.$.address.value = i.get('addressFk'); this.$.address.value = row.addressFk;
this.autoStepLocked = false; this.autoStepLocked = false;
}, },
@ -164,7 +159,7 @@ Hedera.Checkout = new Class({
addressRenderer: function(builder, form) { addressRenderer: function(builder, form) {
builder.$.address.addEventListener('click', builder.$.address.addEventListener('click',
this.onAddressClick.bind(this, form.get('id'))); this.onAddressClick.bind(this, form.$.id));
}, },
onAddressClick: function(addressId) { onAddressClick: function(addressId) {
@ -194,9 +189,9 @@ Hedera.Checkout = new Class({
if (model.numRows > 0) { if (model.numRows > 0) {
var agency; var agency;
var defaults = [ var defaults = [
this.$.orderForm.get('agencyModeFk'), this.$.orderForm.$.agencyModeFk,
this.$.defaults.get('agencyModeFk'), this.$.defaults.$.agencyModeFk,
this.$.defaults.get('defaultAgencyFk') this.$.defaults.$.defaultAgencyFk
]; ];
for (var i = 0; i < defaults.length; i++) { for (var i = 0; i < defaults.length; i++) {

View File

@ -19,7 +19,7 @@ Hedera.Confirm = new Class({
if (form.row < 0) if (form.row < 0)
return; return;
if (form.get('method') != 'PICKUP') { if (form.$.method != 'PICKUP') {
Vn.Node.show(this.$.address); Vn.Node.show(this.$.address);
Vn.Node.setText(this.$.method, _('Agency')); Vn.Node.setText(this.$.method, _('Agency'));
} else { } else {
@ -27,13 +27,13 @@ Hedera.Confirm = new Class({
Vn.Node.setText(this.$.method, _('Warehouse')); Vn.Node.setText(this.$.method, _('Warehouse'));
} }
var total = form.get('taxableBase') + form.get('tax'); var total = form.$.taxableBase + form.$.tax;
if (total === null) if (total === null)
total = 0; total = 0;
var credit = form.get('credit'); var credit = form.$.credit;
var debt = form.get('debt'); var debt = form.$.debt;
var totalDebt = debt + total; var totalDebt = debt + total;
var exceededCredit = totalDebt - credit; var exceededCredit = totalDebt - credit;
@ -77,7 +77,7 @@ Hedera.Confirm = new Class({
} }
for (var i = 0; i < methods.length; i++) for (var i = 0; i < methods.length; i++)
this.$(methods[i] +'-method').style.display = 'block'; this.$[`${methods[i]}Method`].style.display = 'block';
this.$.payMethod.value = selectedMethod; this.$.payMethod.value = selectedMethod;
}, },
@ -86,20 +86,20 @@ Hedera.Confirm = new Class({
var id = this.displayedInfo; var id = this.displayedInfo;
if (id) if (id)
Vn.Node.removeClass(this.$(id), 'selected'); Vn.Node.removeClass(this.$[id], 'selected');
switch (payMethod.value) { switch (payMethod.value) {
case 'BALANCE': case 'BALANCE':
id = 'balance-method'; id = 'balanceMethod';
break; break;
case 'CREDIT': case 'CREDIT':
id = 'credit-method'; id = 'creditMethod';
break; break;
case 'CARD': case 'CARD':
id = 'card-method'; id = 'cardMethod';
break; break;
case 'TRANSFER': case 'TRANSFER':
id = 'transfer-method'; id = 'transferMethod';
break; break;
default: default:
id = null; id = null;
@ -108,7 +108,7 @@ Hedera.Confirm = new Class({
this.displayedInfo = id; this.displayedInfo = id;
if (id) if (id)
Vn.Node.addClass(this.$(id), 'selected'); Vn.Node.addClass(this.$[id], 'selected');
}, },
disableButtons: function(disable) { disableButtons: function(disable) {
@ -140,7 +140,7 @@ Hedera.Confirm = new Class({
var payAmount = this.$.totalAmount.value; var payAmount = this.$.totalAmount.value;
var tpv = new Hedera.Tpv({conn: this.conn}); var tpv = new Hedera.Tpv({conn: this.conn});
tpv.pay(payAmount, this.$.orderForm.get('companyFk')); tpv.pay(payAmount, this.$.orderForm.$.companyFk);
} else } else
this.hash.set({'form': 'ecomerce/orders'}); this.hash.set({'form': 'ecomerce/orders'});
} }

View File

@ -3,9 +3,9 @@ Hedera.Invoices = new Class({
Extends: Hedera.Form, Extends: Hedera.Form,
donwloadRenderer: function(column, invoice) { donwloadRenderer: function(column, invoice) {
var invoiceId = invoice.get('id'); var invoiceId = invoice.$.id;
if (invoice.get('hasPdf') && invoiceId) { if (invoice.$.hasPdf && invoiceId) {
var params = { var params = {
srv: 'rest:dms/invoice', srv: 'rest:dms/invoice',
invoice: invoiceId, invoice: invoiceId,

View File

@ -19,7 +19,7 @@ Hedera.Orders = new Class({
repeaterFunc: function(res, form) { repeaterFunc: function(res, form) {
res.$.link.href = this.hash.make({ res.$.link.href = this.hash.make({
form: 'ecomerce/ticket', form: 'ecomerce/ticket',
ticket: form.get('id') ticket: form.$.id
}); });
}, },

View File

@ -12,7 +12,7 @@ Hedera.Ticket = new Class({
}, },
onTicketReady: function(form) { onTicketReady: function(form) {
if (form.get('method') != 'PICKUP') if (form.$.method != 'PICKUP')
Vn.Node.setText(this.$.method, _('Agency')); Vn.Node.setText(this.$.method, _('Agency'));
else else
Vn.Node.setText(this.$.method, _('Warehouse')); Vn.Node.setText(this.$.method, _('Warehouse'));
@ -30,22 +30,22 @@ Hedera.Ticket = new Class({
repeaterFunc: function(res, form) { repeaterFunc: function(res, form) {
var discount = res.$.discount; var discount = res.$.discount;
discount.style.display = form.get('discount') ? 'inline' : 'none'; discount.style.display = form.$.discount ? 'inline' : 'none';
res.$.discountSubtotal.value = this.discountSubtotal(form); res.$.discountSubtotal.value = this.discountSubtotal(form);
res.$.subtotal.value = this.subtotal(form); res.$.subtotal.value = this.subtotal(form);
}, },
discountSubtotal: function(form) { discountSubtotal: function(form) {
return form.get('quantity') * form.get('price'); return form.$.quantity * form.$.price;
}, },
subtotal: function(form) { subtotal: function(form) {
var discount = form.get('discount'); var discount = form.$.discount;
return this.discountSubtotal(form) * ((100 - discount) / 100); return this.discountSubtotal(form) * ((100 - discount) / 100);
}, },
servicesFunc: function(res, form) { servicesFunc: function(res, form) {
res.$.subtotal.value = form.get('quantity') * form.get('price'); res.$.subtotal.value = form.$.quantity * form.$.price;
}, },
onServicesChanged: function(model) { onServicesChanged: function(model) {

View File

@ -46,7 +46,7 @@ Hedera.New = new Class({
if (!this.editor) if (!this.editor)
return; return;
var newHtml = this.$.iter.get('text'); var newHtml = this.$.iter.$.text;
if (!newHtml) if (!newHtml)
newHtml = ''; newHtml = '';
@ -74,7 +74,7 @@ Hedera.New = new Class({
}, },
onReturnClick: function() { onReturnClick: function() {
this.hash.set({'form': 'news/news'}); this.hash.set({form: 'news/news'});
} }
}); });
}); });

View File

@ -1,13 +1,6 @@
.new .box { .new .box {
position: relative; position: relative;
} }
.new .image-label {
position: absolute;
text-align: center;
width: 100%;
top: 30px;
opacity: .5;
}
.new .htk-image { .new .htk-image {
height: 100px; height: 100px;
overflow: hidden; overflow: hidden;

View File

@ -36,7 +36,6 @@
</div> </div>
<div id="form" class="new"> <div id="form" class="new">
<div class="box form vn-w-sm"> <div class="box form vn-w-sm">
<h4 class="image-label"><t>Image</t></h4>
<htk-image <htk-image
form="iter" form="iter"
column="image" column="image"

View File

@ -8,7 +8,7 @@ Hedera.Shelves = new Class({
} }
,onConfigChange: function() { ,onConfigChange: function() {
var fields = [ const fields = [
'realm' 'realm'
,'family' ,'family'
,'warehouse' ,'warehouse'
@ -19,9 +19,11 @@ Hedera.Shelves = new Class({
,'showPacking' ,'showPacking'
,'stack' ,'stack'
]; ];
const config = this.$.config.$;
for (var i = 0; i < fields.length; i++) if (config)
this.$(fields[i]).value = this.$.config.get(fields[i]); for (const field of fields)
this.$[field].value = config[field];
} }
,onPreviewClick: function() { ,onPreviewClick: function() {
@ -40,8 +42,8 @@ Hedera.Shelves = new Class({
var batch = new Sql.Batch(); var batch = new Sql.Batch();
for (var i = 0; i < fields.length; i++) for (const field of fields)
batch.addValue(fields[i], this.$(fields[i]).value); batch.addValue(field, this.$[field].value);
this.gui.openReport('shelves-report', batch); this.gui.openReport('shelves-report', batch);
} }

View File

@ -81,18 +81,34 @@ Connection.implement({
* Called when a query is executed. * Called when a query is executed.
*/ */
,_onExec: function(callback, json, error) { ,_onExec: function(callback, json, error) {
const results = [];
if (json) if (json)
try { try {
if (json && json instanceof Array) if (json && json instanceof Array)
for (var i = 0; i < json.length; i++) for (let i = 0; i < json.length; i++)
if (json[i] !== true) { if (json[i] !== true) {
var data = json[i].data; const rows = json[i].data;
var columns = json[i].columns; const columns = json[i].columns;
for (var j = 0; j < columns.length; j++) { const data = new Array(rows.length);
var castFunc = null; results.push({
data,
columns,
tables: json[i].tables
});
switch (columns[j].type) { for (let j = 0; j < rows.length; j++) {
const row = data[j] = {};
for (let k = 0; k < columns.length; k++)
row[columns[k].name] = rows[j][k];
}
for (let j = 0; j < columns.length; j++) {
let castFunc = null;
const col = columns[j];
switch (col.type) {
case Type.DATE: case Type.DATE:
case Type.DATE_TIME: case Type.DATE_TIME:
case Type.TIMESTAMP: case Type.TIMESTAMP:
@ -101,21 +117,22 @@ Connection.implement({
} }
if (castFunc !== null) { if (castFunc !== null) {
if (columns[j].def != null) if (col.def != null)
columns[j].def = castFunc(columns[j].def); col.def = castFunc(col.def);
for (var k = 0; k < data.length; k++) for (let k = 0; k < data.length; k++)
if (data[k][j] != null) if (data[k][col.name] != null)
data[k][j] = castFunc(data[k][j]); data[k][col.name] = castFunc(data[k][col.name]);
} }
} }
} } else
results.push(json[i]);
} catch (e) { } catch (e) {
error = e; error = e;
} }
if (callback) if (callback)
callback(new Db.ResultSet(json, error)); callback(new Db.ResultSet(results, error));
} }
}); });

View File

@ -1,62 +1,51 @@
var Iterator = require ('./iterator'); var Iterator = require('./iterator');
var Model = require ('./model'); var Model = require('./model');
module.exports = new Class module.exports = new Class({
({
Extends: Vn.Object Extends: Vn.Object
,Implements: Iterator ,Implements: Iterator
,Tag: 'db-form' ,Tag: 'db-form'
,Properties: ,Properties: {
{
/** /**
* The model associated to this form. * The model associated to this form.
*/ */
model: model: {
{
type: Model type: Model
,set: function (x) ,set: function(x) {
{ this.link({_model: x}, {
this.link ({_model: x},
{
'status-changed': this.onModelChange 'status-changed': this.onModelChange
,'row-updated': this.onRowUpdate ,'row-updated': this.onRowUpdate
}); });
} }
,get: function () ,get: function() {
{
return this._model; return this._model;
} }
}, },
/** /**
* The row where the form positioned, has -1 if the row is unselected. * The row where the form positioned, has -1 if the row is unselected.
*/ */
row: row: {
{
type: Number type: Number
,set: function (x) ,set: function(x) {
{
if (!this._model || this._model.numRows <= x || x < -1) if (!this._model || this._model.numRows <= x || x < -1)
x = -1; x = -1;
if (x == this._row) if (x == this._row)
return; return;
this._row = x; this._row = x;
this.iterChanged (); this.iterChanged();
} }
,get: function () ,get: function() {
{
return this._row; return this._row;
} }
}, },
/** /**
* The number of rows in the form. * The number of rows in the form.
*/ */
numRows: numRows: {
{
type: Number type: Number
,get: function () ,get: function() {
{
if (this._model) if (this._model)
return this._model.numRows; return this._model.numRows;
@ -66,13 +55,20 @@ module.exports = new Class
/** /**
* Checks if the form data is ready. * Checks if the form data is ready.
*/ */
ready: ready: {
{
type: Boolean type: Boolean
,get: function () ,get: function() {
{
return this._ready; return this._ready;
} }
},
/**
* The row object.
*/
$: {
type: Object
,get: function() {
return this._model.getObject(this._row);
}
} }
} }
@ -81,32 +77,29 @@ module.exports = new Class
,_row: -1 ,_row: -1
,_ready: false ,_ready: false
,onModelChange: function () ,onModelChange: function() {
{
var ready = this._model && this._model.ready; var ready = this._model && this._model.ready;
if (ready != this._ready) if (ready != this._ready) {
{
if (this._row != -1) if (this._row != -1)
this.lastRow = this._row; this.lastRow = this._row;
this._ready = ready; this._ready = ready;
this.signalEmit ('status-changed'); this.signalEmit('status-changed');
if (this._row == -1) if (this._row == -1)
this.row = this.lastRow; this.row = this.lastRow;
if (ready) if (ready)
this.signalEmit ('ready'); this.signalEmit('ready');
this.iterChanged (); this.iterChanged();
} }
} }
,onRowUpdate: function (model, row, column) ,onRowUpdate: function(model, row) {
{
if (row == this._row) if (row == this._row)
this.iterChanged (); this.iterChanged();
} }
}); });

View File

@ -26,6 +26,12 @@ module.exports = new Class({
*/ */
ready: { ready: {
type: Boolean type: Boolean
},
/**
* The row object.
*/
$: {
type: Object
} }
} }
@ -84,16 +90,6 @@ module.exports = new Class({
return this._model.getObject(this._row); return this._model.getObject(this._row);
} }
/**
* Gets a value from the form.
*
* @param {String} columnName The column name
* @return {Object} The value
*/
,get: function(columnName) {
return this._model.get(this._row, columnName);
}
/** /**
* Sets a value on the form. * Sets a value on the form.
* *

View File

@ -50,8 +50,7 @@ Model.implement({
/** /**
* The connection used to execute the statement. * The connection used to execute the statement.
*/ */
conn: conn: {
{
type: Connection type: Connection
,set: function(x) { ,set: function(x) {
this._conn = x; this._conn = x;
@ -64,8 +63,7 @@ Model.implement({
/** /**
* The result index. * The result index.
*/ */
resultIndex: resultIndex: {
{
type: Number type: Number
,set: function(x) { ,set: function(x) {
this._resultIndex = x; this._resultIndex = x;
@ -77,8 +75,7 @@ Model.implement({
/** /**
* The batch used to execute the statement. * The batch used to execute the statement.
*/ */
batch: batch: {
{
type: Sql.Batch type: Sql.Batch
,set: function(x) { ,set: function(x) {
this.link({_batch: x}, {'changed': this._autoLoad}); this.link({_batch: x}, {'changed': this._autoLoad});
@ -91,8 +88,7 @@ Model.implement({
/** /**
* The model select statement. * The model select statement.
*/ */
stmt: stmt: {
{
type: Sql.Stmt type: Sql.Stmt
,set: function(x) { ,set: function(x) {
this._stmt = x; this._stmt = x;
@ -105,8 +101,7 @@ Model.implement({
/** /**
* The model query. * The model query.
*/ */
query: query: {
{
type: String type: String
,set: function(x) { ,set: function(x) {
this.stmt = new Sql.String({query: x}); this.stmt = new Sql.String({query: x});
@ -121,8 +116,7 @@ Model.implement({
/** /**
* The main table. * The main table.
*/ */
mainTable: mainTable: {
{
type: String type: String
,set: function(x) { ,set: function(x) {
this._mainTable = null; this._mainTable = null;
@ -136,8 +130,7 @@ Model.implement({
/** /**
* Determines if the model is updatable. * Determines if the model is updatable.
*/ */
updatable: updatable: {
{
type: Boolean type: Boolean
,set: function(x) { ,set: function(x) {
this._updatable = false; this._updatable = false;
@ -151,8 +144,7 @@ Model.implement({
/** /**
* The number of rows in the model. * The number of rows in the model.
*/ */
numRows: numRows: {
{
type: Number type: Number
,get: function() { ,get: function() {
if (this.data) if (this.data)
@ -164,8 +156,7 @@ Model.implement({
/** /**
* The current status of the model. * The current status of the model.
*/ */
status: status: {
{
type: Number type: Number
,get: function() { ,get: function() {
return this._status; return this._status;
@ -174,8 +165,7 @@ Model.implement({
/** /**
* Checks if the model data is ready. * Checks if the model data is ready.
*/ */
ready: ready: {
{
type: Boolean type: Boolean
,get: function() { ,get: function() {
return this._status == Status.READY; return this._status == Status.READY;
@ -184,16 +174,14 @@ Model.implement({
/** /**
* Update mode. * Update mode.
*/ */
mode: mode: {
{
enumType: Mode enumType: Mode
,value: Mode.ON_CHANGE ,value: Mode.ON_CHANGE
}, },
/** /**
* Wether to execute the model query automatically. * Wether to execute the model query automatically.
*/ */
autoLoad: autoLoad: {
{
type: Boolean type: Boolean
,value: true ,value: true
} }
@ -384,11 +372,7 @@ Model.implement({
* @param {Sql.Expr} srcColumn The default value expression * @param {Sql.Expr} srcColumn The default value expression
*/ */
,setDefault: function(field, table, expr) { ,setDefault: function(field, table, expr) {
this._defaults.push({ this._defaults.push({field, table, expr});
field: field
,table: table
,expr: expr
});
} }
/** /**
@ -399,11 +383,7 @@ Model.implement({
* @param {Object} value The default value * @param {Object} value The default value
*/ */
,setDefaultFromValue: function(field, table, value) { ,setDefaultFromValue: function(field, table, value) {
this._defaults.push({ this._defaults.push({field, table, value});
field: field
,table: table
,value: value
});
} }
/** /**
@ -415,15 +395,11 @@ Model.implement({
* @param {String} srcColumn The source column * @param {String} srcColumn The source column
*/ */
,setDefaultFromColumn: function(field, table, srcColumn) { ,setDefaultFromColumn: function(field, table, srcColumn) {
this._defaults.push({ this._defaults.push({field, table, srcColumn});
field: field
,table: table
,srcColumn: srcColumn
});
} }
/** /**
* Checks if the column exists. * Checks if column index exists.
* *
* @param {integer} column The column index * @param {integer} column The column index
* @return {Boolean} %true if column exists, %false otherwise * @return {Boolean} %true if column exists, %false otherwise
@ -434,6 +410,17 @@ Model.implement({
&& column < this.columns.length; && column < this.columns.length;
} }
/**
* Checks if column name exists.
*
* @param {string} columnName The column name
* @return {Boolean} %true if column exists, %false otherwise
*/
,checkColName: function(columnName) {
return this.columnMap
&& this.columnMap[columnName] != null;
}
/** /**
* Checks if the row exists. * Checks if the row exists.
* *
@ -464,15 +451,25 @@ Model.implement({
* @return {number} The column index or -1 if column not exists * @return {number} The column index or -1 if column not exists
*/ */
,getColumnIndex: function(columnName) { ,getColumnIndex: function(columnName) {
var index; if (this.checkColName(columnName))
return this.columnMap[columnName].index;
if (this.columnMap
&& (index = this.columnMap[columnName]) !== undefined)
return index;
return -1; return -1;
} }
/**
* Get the index of the column from its name.
*
* @param {number} columnIndex The column name
* @return {string} The column index or -1 if column not exists
*/
,getColumnName: function(columnIndex) {
if (this.checkColExists(columnIndex))
return this.columns[columnIndex].name;
return null;
}
/** /**
* Gets the row as object. * Gets the row as object.
* *
@ -483,11 +480,7 @@ Model.implement({
if (!this.checkRowExists(rowIndex)) if (!this.checkRowExists(rowIndex))
return undefined; return undefined;
const row = this.data[rowIndex]; return this.data[rowIndex];
const object = {};
for(let i = 0; i < row.length; i++)
object[this.columns[i].name] = row[i];
return object;
} }
/** /**
@ -498,12 +491,8 @@ Model.implement({
* @return {mixed} The value * @return {mixed} The value
*/ */
,get: function(rowIndex, columnName) { ,get: function(rowIndex, columnName) {
var index = this.getColumnIndex(columnName); if (this.checkRowExists(rowIndex))
return this.data[rowIndex][columnName];
if (index != -1)
return this.getByIndex(rowIndex, index);
return undefined;
} }
/** /**
@ -514,41 +503,11 @@ Model.implement({
* @param {mixed} value The new value * @param {mixed} value The new value
*/ */
,set: function(rowIndex, columnName, value) { ,set: function(rowIndex, columnName, value) {
var index = this.getColumnIndex(columnName);
if (index != -1)
this.setByIndex(rowIndex, index, value);
else
console.warn('Db.Model: Column %s doesn\'t exist', columnName);
}
/**
* Gets a value from the model using the column index.
*
* @param {number} rowIndex The row index
* @param {number} column The column index
* @return {mixed} The value
*/
,getByIndex: function(rowIndex, column) {
if (this.checkRowExists(rowIndex) && this.checkColExists(column))
return this.data[rowIndex][column];
return undefined;
}
/**
* Updates a value on the model using the column index.
*
* @param {number} rowIndex The row index
* @param {number} col The column index
* @param {mixed} value The new value
*/
,setByIndex: function(rowIndex, col, value) {
if (!this.checkRowExists(rowIndex) if (!this.checkRowExists(rowIndex)
&& !this.checkColExists(col)) && !this.checkColName(columnName))
return; return;
var tableIndex = this.columns[col].table; var tableIndex = this.columnMap[columnName].table;
if (!this._checkTableUpdatable(tableIndex)) if (!this._checkTableUpdatable(tableIndex))
return; return;
@ -569,8 +528,8 @@ Model.implement({
tableOp = Operation.UPDATE; tableOp = Operation.UPDATE;
var pks = this.tables[tableIndex].pks; var pks = this.tables[tableIndex].pks;
for (var i = 0; i < pks.length; i++) for (const pk of pks)
if (!row[pks[i]] && !op.oldValues[pks[i]]) { if (!row[pk] && !op.oldValues[pk]) {
tableOp = Operation.INSERT; tableOp = Operation.INSERT;
break; break;
} }
@ -579,18 +538,50 @@ Model.implement({
} }
if (tableOp & Operation.UPDATE if (tableOp & Operation.UPDATE
&& op.oldValues[col] === undefined) && op.oldValues[columnName] === undefined)
op.oldValues[col] = row[col]; op.oldValues[columnName] = row[columnName];
this.signalEmit('row-updated-before', rowIndex); this.signalEmit('row-updated-before', rowIndex);
row[col] = value; row[columnName] = value;
this.signalEmit('row-updated', rowIndex, [col]); this.signalEmit('row-updated', rowIndex, [columnName]);
if (this.mode == Mode.ON_CHANGE if (this.mode == Mode.ON_CHANGE
&& !(op.type & Operation.INSERT)) && !(op.type & Operation.INSERT))
this.performOperations(); this.performOperations();
} }
/**
* Gets a value from the model using the column index.
*
* @param {number} rowIndex The row index
* @param {number} columnIndex The column index
* @return {mixed} The value
*/
,getByIndex: function(rowIndex, columnIndex) {
var columnName = this.getColumnName(columnIndex);
if (columnName)
return this.get(rowIndex, columnName);
return undefined;
}
/**
* Updates a value on the model using the column index.
*
* @param {number} rowIndex The row index
* @param {number} columnIndex The column index
* @param {mixed} value The new value
*/
,setByIndex: function(rowIndex, columnIndex, value) {
var columnName = this.getColumnName(columnIndex);
if (columnName)
this.set(rowIndex, columnName, value);
else
console.warn('Db.Model: Column %d doesn\'t exist', columnIndex);
}
/** /**
* Deletes a row from the model. * Deletes a row from the model.
* *
@ -619,10 +610,12 @@ Model.implement({
for (var i = 0; i < this.columns.length; i++) for (var i = 0; i < this.columns.length; i++)
if (this.columns[i].table == this._mainTable) { if (this.columns[i].table == this._mainTable) {
if (op.oldValues[i] === undefined) const colName = this.columns[i].name;
op.oldValues[i] = op.row[i];
op.row[i] = null; if (op.oldValues[colName] === undefined)
op.oldValues[colName] = op.row[colName];
op.row[colName] = null;
updatedCols.push(i); updatedCols.push(i);
} }
@ -643,13 +636,13 @@ Model.implement({
return -1; return -1;
var cols = this.columns; var cols = this.columns;
var newRow = new Array(cols.length); var newRow = {};
for (var i = 0; i < cols.length; i++) for (var i = 0; i < cols.length; i++)
if (cols[i].table === this._mainTable) if (cols[i].table === this._mainTable)
newRow[i] = cols[i].def; newRow[cols[i].name] = cols[i].def;
else else
newRow[i] = null; newRow[cols[i].name] = null;
var rowIndex = this.data.push(newRow) - 1; var rowIndex = this.data.push(newRow) - 1;
newRow.index = rowIndex; newRow.index = rowIndex;
@ -689,7 +682,7 @@ Model.implement({
var where = this._createWhere(this._mainTable, op, true); var where = this._createWhere(this._mainTable, op, true);
if (where) { if (where) {
query = new Sql.Delete({where: where}); query = new Sql.Delete({where});
query.addTarget(this._createTarget(this._mainTable)); query.addTarget(this._createTarget(this._mainTable));
} }
} else if (op.type & (Operation.INSERT | Operation.UPDATE)) { } else if (op.type & (Operation.INSERT | Operation.UPDATE)) {
@ -727,7 +720,7 @@ Model.implement({
var multiStmt = new Sql.MultiStmt(); var multiStmt = new Sql.MultiStmt();
var target = this._createTarget(tableIndex); var target = this._createTarget(tableIndex);
var select = new Sql.Select({where: where}); var select = new Sql.Select({where});
select.addTarget(target); select.addTarget(target);
var row = op.row; var row = op.row;
@ -737,27 +730,21 @@ Model.implement({
var dmlQuery = new Sql.Insert(); var dmlQuery = new Sql.Insert();
var table = this.tables[tableIndex]; var table = this.tables[tableIndex];
for (var i = 0; i < this._defaults.length; i++) { for (const def of defaults)
var def = this._defaults[i]; if (def.table === table.name) {
if (def.value)
if (def.table === table.name) { dmlQuery.addSet(def.field, def.value);
if (def.value) else if (def.expr)
dmlQuery.addSet(def.field, def.value); dmlQuery.addExpr(def.field, def.expr);
else if (def.expr) else if (def.srcColumn)
dmlQuery.addExpr(def.field, def.expr); dmlQuery.addSet(def.field, row[def.srcColumn]);
else if (def.srcColumn) {
var columnIndex = this.getColumnIndex(def.srcColumn);
dmlQuery.addSet(def.field, row[columnIndex]);
}
}
} }
for (var i = 0; i < cols.length; i++) for (const col of cols)
if (cols[i].table === tableIndex) { if (col.table === tableIndex) {
if (row[i] !== null) if (row[col.name] !== null)
dmlQuery.addSet(cols[i].orgname, row[i]); dmlQuery.addSet(col.orgname, row[col.name]);
select.addField(col.orgname);
select.addField(cols[i].orgname);
} }
} else { } else {
var updateWhere = this._createWhere(tableIndex, op, true); var updateWhere = this._createWhere(tableIndex, op, true);
@ -767,10 +754,10 @@ Model.implement({
var dmlQuery = new Sql.Update({where: updateWhere}); var dmlQuery = new Sql.Update({where: updateWhere});
for (var i = 0; i < cols.length; i++) for (const col of cols)
if (cols[i].table === tableIndex && op.oldValues[i] !== undefined) { if (col.table === tableIndex && op.oldValues[col.name] !== undefined) {
var fieldName = cols[i].orgname; var fieldName = col.orgname;
dmlQuery.addSet(fieldName, row[i]); dmlQuery.addSet(fieldName, row[col.name]);
select.addField(fieldName); select.addField(fieldName);
} }
} }
@ -823,14 +810,14 @@ Model.implement({
if (op.tables[tableIndex] & Operation.INSERT) { if (op.tables[tableIndex] & Operation.INSERT) {
for (var i = 0; i < cols.length; i++) for (var i = 0; i < cols.length; i++)
if (cols[i].table === tableIndex) { if (cols[i].table === tableIndex) {
row[i] = newValues[j++]; row[cols[i].name] = newValues[j++];
updatedCols.push(i); updatedCols.push(i);
} }
} else { } else {
for (var i = 0; i < cols.length; i++) for (var i = 0; i < cols.length; i++)
if (cols[i].table === tableIndex if (cols[i].table === tableIndex
&& op.oldValues[i] !== undefined) { && op.oldValues[i] !== undefined) {
row[i] = newValues[j++]; row[cols[i].name] = newValues[j++];
updatedCols.push(i); updatedCols.push(i);
} }
} }
@ -866,7 +853,8 @@ Model.implement({
for (var i = 0; i < cols.length; i++) for (var i = 0; i < cols.length; i++)
if (op.oldValues[i] !== undefined) { if (op.oldValues[i] !== undefined) {
row[i] = op.oldValues[i]; const colName = cols[i].name;
row[colName] = op.oldValues[colName];
updatedCols.push(i); updatedCols.push(i);
} }
@ -910,17 +898,15 @@ Model.implement({
/** /**
* Orders the model by the specified column name. * Orders the model by the specified column name.
* *
* @param {integer} column The column name * @param {integer} columnName The column name
* @param {SortWay} way The sort way * @param {SortWay} way The sort way
*/ */
,sortByName: function(columnName, way) { ,sortByName: function(columnName, way) {
this._requestedSortIndex = -1; this._requestedSortIndex = -1;
this._requestedSortName = columnName; this._requestedSortName = columnName;
var index = this.getColumnIndex(columnName); if (this.checkColName(columnName))
this._sort(columnName, way);
if (index != -1)
this._sort(index, way);
} }
/** /**
@ -933,10 +919,10 @@ Model.implement({
this._requestedSortIndex = column; this._requestedSortIndex = column;
this._requestedSortName = null; this._requestedSortName = null;
if (!this.checkColExists(column)) const columnName = this.getColumnName(column);
return; if (columnName) return;
this._sort(column, way); this._sort(columnName, way);
} }
,_sort: function(column, way) { ,_sort: function(column, way) {
@ -978,26 +964,24 @@ Model.implement({
this._buildIndex(column); this._buildIndex(column);
} }
,_buildIndex: function(column) { ,_buildIndex: function(columnName) {
var columnIndex = this.getColumnIndex(column); if (this.checkColName(columnName)) {
if (columnIndex !== -1) {
var index = {}; var index = {};
var data = this.data; var data = this.data;
switch (this.columns[columnIndex].type) { switch (this.columns[columnName].type) {
case Connection.Type.TIMESTAMP: case Connection.Type.TIMESTAMP:
case Connection.Type.DATE_TIME: case Connection.Type.DATE_TIME:
case Connection.Type.DATE: case Connection.Type.DATE:
for (var i = 0; i < data.length; i++) for (var i = 0; i < data.length; i++)
index[data[i][columnIndex].toString()] = i; index[data[i][columnName].toString()] = i;
break; break;
default: default:
for (var i = 0; i < data.length; i++) for (var i = 0; i < data.length; i++)
index[data[i][columnIndex]] = i; index[data[i][columnName]] = i;
} }
this._indexes[columnIndex] = index; this._indexes[columnName] = index;
} }
} }
@ -1007,29 +991,16 @@ Model.implement({
* If an index have been built on that column, it will be used, for more * If an index have been built on that column, it will be used, for more
* information see the indexColumn() method. * information see the indexColumn() method.
* *
* @param {String} column The column name * @param {String} columnName The column name
* @param {Object} value The value to search * @param {Object} value The value to search
* @return {integer} The column index * @return {integer} The column index
*/ */
,search: function(column, value) { ,search: function(columnName, value) {
var index = this.getColumnIndex(column); if (!this.checkColName(columnName))
return this.searchByIndex(index, value);
}
/**
* Searchs a value on the model and returns the row index of the first
* ocurrence.
*
* @param {integer} col The column index
* @param {Object} value The value to search
* @return {integer} The column index
*/
,searchByIndex: function(col, value) {
if (!this.checkColExists(col))
return -1; return -1;
if (value) if (value)
switch (this.columns[col].type) { switch (this.columnMap[columnName].type) {
case Connection.Type.BOOLEAN: case Connection.Type.BOOLEAN:
value = !!value; value = !!value;
break; break;
@ -1043,39 +1014,52 @@ Model.implement({
value = value.toString(); value = value.toString();
} }
// Searchs the value using an internal index. let rowIndex = -1;
const index = this._indexes[columnName];
var index = this._indexes[col];
if (index) { if (index) {
// Searchs the value using an internal index
if (index[value] !== undefined) if (index[value] !== undefined)
return index[value]; rowIndex = index[value];
} else {
// Searchs the value using a loop
return -1; var data = this.data;
}
// Searchs the value using a loop. switch (this.columnMap[columnName].type) {
var data = this.data;
switch (this.columns[col].type) {
case Connection.Type.TIMESTAMP: case Connection.Type.TIMESTAMP:
case Connection.Type.DATE_TIME: case Connection.Type.DATE_TIME:
case Connection.Type.DATE: case Connection.Type.DATE:
{
for (var i = 0; i < data.length; i++) for (var i = 0; i < data.length; i++)
if (value === data[i][col].toString()) if (value === data[i][columnName].toString()) {
return i; rowIndex = i;
break;
}
break; break;
}
default: default:
for (var i = 0; i < data.length; i++) for (var i = 0; i < data.length; i++)
if (value === data[i][col]) if (value === data[i][columnName]) {
return i; rowIndex = i;
break;
}
}
} }
return -1; return rowIndex;
}
/**
* Searchs a value on the model and returns the row index of the first
* ocurrence.
*
* @param {integer} columnIndex The column index
* @param {Object} value The value to search
* @return {integer} The column index
*/
,searchByIndex: function(columnIndex, value) {
var columnName = this.getColumnName(columnIndex);
return this.search(columnName, value);
} }
,_setStatus: function(status) { ,_setStatus: function(status) {
@ -1094,27 +1078,26 @@ Model.implement({
} }
,_createWhere: function(tableIndex, op, useOldValues) { ,_createWhere: function(tableIndex, op, useOldValues) {
var where = new Sql.Operation({type: Sql.Operation.Type.AND}); const where = new Sql.Operation({type: Sql.Operation.Type.AND});
var pks = this.tables[tableIndex].pks; const pks = this.tables[tableIndex].pks;
if (pks.length === 0) if (pks.length === 0)
return null; return null;
for (var i = 0; i < pks.length; i++) { for (const pk of pks) {
var col = pks[i]; const column = this.columnMap[pk];
var column = this.columns[col];
var equalOp = new Sql.Operation({type: Sql.Operation.Type.EQUAL}); const equalOp = new Sql.Operation({type: Sql.Operation.Type.EQUAL});
equalOp.exprs.add(new Sql.Field({name: column.orgname})); equalOp.exprs.add(new Sql.Field({name: column.orgname}));
where.exprs.add(equalOp); where.exprs.add(equalOp);
var pkValue = null; let pkValue = null;
if (useOldValues && op.oldValues if (useOldValues && op.oldValues
&& op.oldValues[col] !== undefined) && op.oldValues[pk] !== undefined)
pkValue = op.oldValues[col]; pkValue = op.oldValues[pk];
else else
pkValue = op.row[col]; pkValue = op.row[pk];
if (pkValue) if (pkValue)
equalOp.exprs.add(new Sql.Value({value: pkValue})); equalOp.exprs.add(new Sql.Value({value: pkValue}));
@ -1161,12 +1144,11 @@ Model.implement({
if (!this.tableInfo) if (!this.tableInfo)
this.tableInfo = {}; this.tableInfo = {};
this.tableInfo[table] = this.tableInfo[table] = {
{ orgname,
orgname: orgname, schema,
schema: schema, pks,
pks: pks, ai
ai: ai
}; };
this._repairColumns(); this._repairColumns();
@ -1189,24 +1171,20 @@ Model.implement({
if (tableInfo.pks) { if (tableInfo.pks) {
table.pks = []; table.pks = [];
for (var j = 0; j < tableInfo.pks.length; j++) { for (const pk of tableInfo.pks) {
var colIndex = this.getColumnIndex(tableInfo.pks[j]); if (this.checkColName(pk))
table.pks.push(pk);
if (colIndex !== -1)
table.pks.push(colIndex);
else else
console.warn('Db.Model: Can\'t repair primary key: `%s`.`%s`' console.warn('Db.Model: Can\'t repair primary key: `%s`.`%s`'
,tableInfo.orgname ,tableInfo.orgname
,tableInfo.pks[j] ,pk
); );
} }
} }
if (tableInfo.ai) { if (tableInfo.ai) {
var colIndex = this.getColumnIndex(tableInfo.ai); if (this.checkColName(tableInfo.ai))
this.columnMap[tableInfo.ai].flags |= Connection.Flag.AI;
if (colIndex !== -1)
this.columns[colIndex].flags |= Connection.Flag.AI;
else else
console.warn('Db.Model: Can\'t repair autoincrement column: `%s`.`%s`' console.warn('Db.Model: Can\'t repair autoincrement column: `%s`.`%s`'
,tableInfo.orgname ,tableInfo.orgname

View File

@ -1,8 +1,7 @@
var Form = require ('./form'); var Form = require('./form');
module.exports = new Class module.exports = new Class({
({
Extends: Vn.Param Extends: Vn.Param
,Tag: 'db-param' ,Tag: 'db-param'
,Parent: 'form' ,Parent: 'form'
@ -14,13 +13,11 @@ module.exports = new Class
column: column:
{ {
type: String type: String
,set: function (x) ,set: function(x) {
{
this._columnName = x; this._columnName = x;
this.refresh (); this.refresh();
} }
,get: function () ,get: function() {
{
this._columnName; this._columnName;
} }
}, },
@ -30,18 +27,16 @@ module.exports = new Class
form: form:
{ {
type: Form type: Form
,set: function (x) ,set: function(x) {
{ this.link({_form: x},
this.link ({_form: x},
{ {
'status-changed': this.onFormChange 'status-changed': this.onFormChange
,'iter-changed': this.onIterChange ,'iter-changed': this.onIterChange
}); });
this.refresh (); this.refresh();
} }
,get: function () ,get: function() {
{
return this._form; return this._form;
} }
}, },
@ -52,12 +47,10 @@ module.exports = new Class
oneWay: oneWay:
{ {
type: Boolean type: Boolean
,set: function (x) ,set: function(x) {
{
this._oneWay = x; this._oneWay = x;
} }
,get: function () ,get: function() {
{
return this._oneWay; return this._oneWay;
} }
} }
@ -70,29 +63,24 @@ module.exports = new Class
,_oneWay: false ,_oneWay: false
,_formValue: null ,_formValue: null
,initialize: function (props) ,initialize: function(props) {
{ this.parent(props);
this.parent (props); this.on('changed', this.onChange, this);
this.on ('changed', this.onChange, this);
} }
,refresh: function () ,refresh: function() {
{ if (this._form) {
if (this._form) this.onFormChange();
{ this.onIterChange();
this.onFormChange ();
this.onIterChange ();
} }
} }
,onFormChange: function () ,onFormChange: function() {
{
if (this._columnName != null) if (this._columnName != null)
this._columnIndex = this._form.getColumnIndex (this._columnName); this._columnIndex = this._form.getColumnIndex(this._columnName);
} }
,onIterChange: function () ,onIterChange: function() {
{
if (this._oneWay && this.value != null) if (this._oneWay && this.value != null)
return; return;
@ -101,7 +89,7 @@ module.exports = new Class
var formValue; var formValue;
if (this._columnIndex !== -1) if (this._columnIndex !== -1)
formValue = this._form.getByIndex (this._columnIndex); formValue = this._form.getByIndex(this._columnIndex);
else else
formValue = undefined; formValue = undefined;
@ -109,10 +97,9 @@ module.exports = new Class
this._formLock = false; this._formLock = false;
} }
,onChange: function () ,onChange: function() {
{
if (!this._formLock && this._columnIndex != -1 && !this.oneWay) if (!this._formLock && this._columnIndex != -1 && !this.oneWay)
this._form.setByIndex (this._columnIndex, this._value); this._form.setByIndex(this._columnIndex, this._value);
} }
}); });

View File

@ -55,11 +55,11 @@ module.exports = new Class({
} }
/** /**
* Fetchs the first row from the next resultset. * Fetchs the first row object from the next resultset.
* *
* @return {Array} the row if success, %null otherwise * @return {Array} the row if success, %null otherwise
*/ */
,fetchRow: function() { ,fetchObject: function() {
var result = this.fetch(); var result = this.fetch();
if (result !== null if (result !== null
@ -71,22 +71,16 @@ module.exports = new Class({
} }
/** /**
* Fetchs the first row object from the next resultset. * Fetchs data from the next resultset.
* *
* @return {Array} the row if success, %null otherwise * @return {Array} the data
*/ */
,fetchObject: function() { ,fetchData: function() {
var result = this.fetch(); var result = this.fetch();
if (result !== null if (result !== null
&& result.data instanceof Array && result.data instanceof Array)
&& result.data.length > 0) { return result.data;
var row = result.data[0];
var object = {};
for(var i = 0; i < row.length; i++)
object[result.columns[i].name] = row[i];
return object;
}
return null; return null;
} }
@ -104,5 +98,26 @@ module.exports = new Class({
return null; return null;
} }
/**
* Fetchs the first row from the next resultset.
*
* @return {Array} the row if success, %null otherwise
*/
,fetchRow: function() {
var result = this.fetch();
if (result !== null
&& result.data instanceof Array
&& result.data.length > 0) {
var object = result.data[0];
var row = new Array(result.columns.length);
for(var i = 0; i < row.length; i++)
row[i] = object[result.columns[i].name];
return row;
}
return null;
}
}); });

View File

@ -1,26 +1,25 @@
/** /**
* This class stores a database result. * This class stores a database result.
*/ */
module.exports = new Class module.exports = new Class({
({
/** /**
* Initilizes the result object. * Initilizes the result object.
*/ */
initialize: function (result) initialize: function(result) {
{
this.data = result.data; this.data = result.data;
this.tables = result.tables; this.tables = result.tables;
this.columns = result.columns; this.columns = result.columns;
this.row = -1; this.row = -1;
if (this.columns) if (this.columns) {
{
this.columnMap = {}; this.columnMap = {};
for (var i = 0; i < this.columns.length; i++) for (var i = 0; i < this.columns.length; i++) {
this.columnMap[this.columns[i].name] = i; const col = this.columns[i];
} col.index = i;
else this.columnMap[col.name] = col;
}
} else
this.columnMap = null; this.columnMap = null;
} }
@ -30,25 +29,30 @@ module.exports = new Class
* @param {String} columnName The column name * @param {String} columnName The column name
* @return {Object} The cell value * @return {Object} The cell value
*/ */
,get: function (columnName) ,get: function(columnName) {
{ return this.data[this.row][columnName];
var columnIndex = this.columnMap[columnName]; }
return this.data[this.row][columnIndex];
/**
* Gets a row.
*
* @return {Object} The cell value
*/
,getObject: function() {
return this.data[this.row];
} }
/** /**
* Resets the result iterator. * Resets the result iterator.
*/ */
,reset: function () ,reset: function() {
{
this.row = -1; this.row = -1;
} }
/** /**
* Moves the internal iterator to the next row. * Moves the internal iterator to the next row.
*/ */
,next: function () ,next: function() {
{
this.row++; this.row++;
if (this.row >= this.data.length) if (this.row >= this.data.length)

View File

@ -56,6 +56,15 @@ module.exports = new Class({
return false; return false;
} }
},
/**
* The row object.
*/
$: {
type: Object
,get: function() {
return this._model.getObject(this._row);
}
} }
} }
}); });

View File

@ -141,10 +141,10 @@ module.exports = new Class({
// Retrieving configuration parameters // Retrieving configuration parameters
var res = resultSet.fetchResult(); var res = resultSet.fetchObject();
if (res.next() && res.get('testDomain')) { if (res && res.testDomain) {
if (location.host != res.get('productionDomain')) { if (location.host != res.productionDomain) {
var linkText = 'Old website'; var linkText = 'Old website';
var linkField = 'productionDomain'; var linkField = 'productionDomain';
} else { } else {
@ -171,17 +171,17 @@ module.exports = new Class({
,_onMenuLoad: function(resultSet) { ,_onMenuLoad: function(resultSet) {
// Retrieving menu sections // Retrieving menu sections
var res = resultSet.fetchResult(); var res = resultSet.fetchData();
var sectionMap = {}; var sectionMap = {};
let i = 0;
if (res) for (const row of res) {
for (var i = 0; res.next(); i++) { var parent = row.parentFk;
var parent = res.get('parentFk');
if (!sectionMap[parent]) if (!sectionMap[parent])
sectionMap[parent] = []; sectionMap[parent] = [];
sectionMap[parent].push(i); sectionMap[parent].push(i++);
} }
Vn.Node.removeChilds(this.$.mainMenu); Vn.Node.removeChilds(this.$.mainMenu);
@ -196,23 +196,24 @@ module.exports = new Class({
for (var i = 0; i < sections.length; i++) { for (var i = 0; i < sections.length; i++) {
res.row = sections[i]; res.row = sections[i];
const row = res[sections[i]];
var li = this.createElement('li'); var li = this.createElement('li');
ul.appendChild(li); ul.appendChild(li);
var text = this.createTextNode(_(res.get('description'))); var text = this.createTextNode(_(row.description));
var a = this.createElement('a'); var a = this.createElement('a');
if (res.get('path')) { if (row.path) {
a.href = Vn.Hash.make({'form': res.get('path')}); a.href = Vn.Hash.make({form: row.path});
this.menuOptions[res.get('path')] = a; this.menuOptions[row.path] = a;
} }
a.appendChild(text); a.appendChild(text);
li.appendChild(a); li.appendChild(a);
var formId = res.get('id'); var formId = row.id;
if (sectionMap[formId]) { if (sectionMap[formId]) {
var submenu = this.createElement('ul'); var submenu = this.createElement('ul');

View File

@ -176,7 +176,7 @@ button,
font-weight: bold; font-weight: bold;
&:disabled { &:disabled {
background-color: rgba(0, 0, 0, .5); background-color: rgba(0, 0, 0, .1);
} }
} }
.button { .button {

View File

@ -1,14 +1,13 @@
module.exports = new Class module.exports = new Class({
({
Extends: Vn.Object Extends: Vn.Object
,tpvOrder: null ,tpvOrder: null
,tpvStatus: null ,tpvStatus: null
,check: function(callback) { ,check: function(callback) {
this.tpvOrder = Vn.Hash.get('tpvOrder'); this.tpvOrder = Vn.Hash.$.tpvOrder;
this.tpvStatus = Vn.Hash.get('tpvStatus'); this.tpvStatus = Vn.Hash.$.tpvStatus;
if (this.tpvStatus) { if (this.tpvStatus) {
var batch = new Sql.Batch(); var batch = new Sql.Batch();
@ -79,10 +78,10 @@ module.exports = new Class
} }
,_onRetryPayDone: function(resultSet) { ,_onRetryPayDone: function(resultSet) {
var res = resultSet.fetchResult(); var res = resultSet.fetchObject();
if (res.next()) if (res)
this._realPay(res.get('amount'), res.get('companyFk')); this._realPay(res.amount, res.companyFk);
else else
Htk.Toast.showError(_('AmountError')); Htk.Toast.showError(_('AmountError'));
} }

View File

@ -5,44 +5,36 @@ var NodeBuilder = require('./node-builder');
* Represents a grid column. This is an abstract class and should not be * Represents a grid column. This is an abstract class and should not be
* instantiated directly. * instantiated directly.
*/ */
module.exports = new Class module.exports = new Class({
({
Extends: NodeBuilder Extends: NodeBuilder
,Tag: 'htk-column' ,Tag: 'htk-column'
,Properties: ,Properties:
{ {
value: value: {
{
type: String type: String
,value: null ,value: null
}, },
column: column: {
{
type: String type: String
,value: null ,value: null
}, },
columnIndex: columnIndex: {
{
type: Number type: Number
,value: -1 ,value: -1
}, },
title: title: {
{
type: String type: String
,value: null ,value: null
}, },
editable: editable: {
{
type: Boolean type: Boolean
,value: false ,value: false
}, },
renderer: renderer: {
{
type: Function type: Function
,value: false ,value: false
}, },
class: class: {
{
type: String type: String
,set: function(x) { ,set: function(x) {
this._userCssClass = x; this._userCssClass = x;
@ -92,9 +84,9 @@ module.exports = new Class
return td; return td;
} }
,updateColumnIndex: function(model) { ,updateColumnName: function(model) {
if (this.column) if (this.columnIndex !== -1)
this.columnIndex = model.getColumnIndex(this.column); this.column = model.getColumnName(this.columnIndex);
} }
,changed: function(tr, newValue) { ,changed: function(tr, newValue) {

View File

@ -42,7 +42,6 @@ module.exports = new Class({
,render: function() { ,render: function() {
var node = this.createRoot('button'); var node = this.createRoot('button');
node.className = 'htk-button'; node.className = 'htk-button';
node.addEventListener('click', this.onClick.bind(this));
this.iconNode = new Htk.Icon(); this.iconNode = new Htk.Icon();
node.appendChild(this.iconNode.node); node.appendChild(this.iconNode.node);
@ -59,8 +58,4 @@ module.exports = new Class({
this.node.appendChild(this._textNode); this.node.appendChild(this._textNode);
} }
} }
,onClick: function() {
this.signalEmit('click', this._form);
}
}); });

View File

@ -136,7 +136,7 @@ module.exports = new Class({
if (this._stamp) if (this._stamp)
src += '?'+ this._stamp; src += '?'+ this._stamp;
else if (this._stampColumn && this.form) else if (this._stampColumn && this.form)
src += '?'+ this.form.get(this._stampColumn); src += '?'+ this.form.$[this._stampColumn];
return src; return src;
} }

View File

@ -5,13 +5,11 @@ module.exports = new Class({
Extends: Htk.Field Extends: Htk.Field
,Implements: Db.Iterator ,Implements: Db.Iterator
,Tag: 'htk-combo' ,Tag: 'htk-combo'
,Properties: ,Properties: {
{
/** /**
* The model associated to this form. * The model associated to this form.
*/ */
model: model: {
{
type: Db.Model type: Db.Model
,set: function(x) { ,set: function(x) {
this.link({_model: x}, {'status-changed-after': this._onModelChange}); this.link({_model: x}, {'status-changed-after': this._onModelChange});
@ -24,8 +22,7 @@ module.exports = new Class({
/** /**
* The row where the form positioned, has -1 if the row is unselected. * The row where the form positioned, has -1 if the row is unselected.
*/ */
row: row: {
{
type: Number type: Number
,set: function(x) { ,set: function(x) {
if (!this._model || this._model.numRows <= x || x < -1) if (!this._model || this._model.numRows <= x || x < -1)
@ -89,6 +86,15 @@ module.exports = new Class({
,get: function() { ,get: function() {
return this._notNull; return this._notNull;
} }
},
/**
* The row object.
*/
$: {
type: Object
,get: function() {
return this._model.getObject(this._row);
}
} }
} }
@ -116,19 +122,6 @@ module.exports = new Class({
button.appendChild(dropDown.node); button.appendChild(dropDown.node);
} }
,on: function(id, callback, instance) {
switch (id) {
case 'click':
case 'mousedown':
case 'focusout':
this.node.addEventListener(id,
callback.bind(instance, this));
break;
default:
this.parent(id, callback, instance);
}
}
,_setRow: function(row) { ,_setRow: function(row) {
this._row = row; this._row = row;
this._refreshShowText(); this._refreshShowText();
@ -238,7 +231,7 @@ module.exports = new Class({
this._setRow(row); this._setRow(row);
} }
,putValue: function(value) { ,putValue: function() {
this._selectOption(); this._selectOption();
} }
}); });

View File

@ -10,8 +10,7 @@ module.exports = new Class({
/** /**
* The source data model. * The source data model.
*/ */
model: model: {
{
type: Db.Model type: Db.Model
,set: function(x) { ,set: function(x) {
this.link({_model: x}, this.link({_model: x},
@ -36,16 +35,14 @@ module.exports = new Class({
/** /**
* Message that should be displayed when source model is not ready. * Message that should be displayed when source model is not ready.
*/ */
emptyMessage: emptyMessage: {
{
type: String type: String
,value: null ,value: null
}, },
/** /**
* Wether to display the header with column titles. * Wether to display the header with column titles.
*/ */
showHeader: showHeader: {
{
type: Boolean type: Boolean
,set: function(x) { ,set: function(x) {
this._showHeader = x; this._showHeader = x;
@ -104,8 +101,8 @@ module.exports = new Class({
} }
,renderCell: function(row, column, tr) { ,renderCell: function(row, column, tr) {
if (column.columnIndex != -1) if (column.column)
column.value = this._model.data[row][column.columnIndex]; column.value = this._model.data[row][column.column];
if (column.renderer) { if (column.renderer) {
this._set.row = row; this._set.row = row;
@ -178,7 +175,7 @@ module.exports = new Class({
case Db.Model.Status.READY: case Db.Model.Status.READY:
{ {
for (var i = 0; i < this.columns.length; i++) for (var i = 0; i < this.columns.length; i++)
this.columns[i].updateColumnIndex(this._model); this.columns[i].updateColumnName(this._model);
this.buildRow(this._model.numRows); this.buildRow(this._model.numRows);
this.showNoRecordsFound(); this.showNoRecordsFound();
@ -244,26 +241,26 @@ module.exports = new Class({
} }
,sortModel: function(column) { ,sortModel: function(column) {
var columnIndex = column.columnIndex; var columnName = column.column;
if (this._model && columnIndex != -1) { if (this._model && columnName != -1) {
if (this.sortColumn === columnIndex if (this.sortColumn === columnName
&& this.sortWay === Db.Model.SortWay.ASC) && this.sortWay === Db.Model.SortWay.ASC)
this.sortWay = Db.Model.SortWay.DESC; this.sortWay = Db.Model.SortWay.DESC;
else else
this.sortWay = Db.Model.SortWay.ASC; this.sortWay = Db.Model.SortWay.ASC;
this.sortColumn = columnIndex; this.sortColumn = columnName;
this._model.sort(columnIndex, this.sortWay); this._model.sortByName(columnName, this.sortWay);
} }
} }
,columnChanged: function(column, row, newValue) { ,columnChanged: function(column, row, newValue) {
var columnIndex = column.columnIndex; var columnName = column.column;
if (columnIndex != -1) if (columnName != -1)
this._model.setByIndex(row, columnIndex, newValue); this._model.set(row, columnName, newValue);
} }
,addColumn: function(pos, column) { ,addColumn: function(pos, column) {

View File

@ -1,7 +1,7 @@
var NodeBuilder = require('./node-builder'); const NodeBuilder = require('./node-builder');
module.exports = new Class({ const Widget = new Class({
Extends: NodeBuilder Extends: NodeBuilder
,Properties: ,Properties:
{ {
@ -15,6 +15,18 @@ module.exports = new Class({
return this._node; return this._node;
} }
}, },
/**
* CSS syle.
*/
style: {
type: String
,set: function(x) {
this.node.style = x;
}
,get: function() {
return this.node.style;
}
},
/** /**
* CSS classes to be appendend to the node classes. * CSS classes to be appendend to the node classes.
*/ */
@ -28,6 +40,15 @@ module.exports = new Class({
return this._node.className; return this._node.className;
} }
}, },
/**
* CSS class list.
*/
classList: {
type: Object
,get: function() {
return this.node.classList;
}
},
/** /**
* Title of the element. * Title of the element.
*/ */
@ -70,5 +91,43 @@ module.exports = new Class({
,remove: function() { ,remove: function() {
Vn.Node.remove(this._node); Vn.Node.remove(this._node);
} }
,on: function(id, callback, instance) {
if (htmlEventMap[id]) {
this.node.addEventListener(id,
callback.bind(instance, this));
} else
this.parent(id, callback, instance);
}
}); });
htmlEventMap = {};
htmlEvents = [
'click',
'dblclick',
'keydown',
'keypress',
'keyup',
'mousedown',
'mousemove',
'mouseout',
'mouseover',
'mouseup',
'mousewheel',
'wheel',
'focus',
'focusout',
'focusin'
];
htmlEvents.forEach(x => htmlEventMap[x] = true);
htmlMethods = [
'addEventListener'
];
htmlMethods.forEach(method => {
Widget[method] = function() {
this.node.apply(this.node, arguments);
};
});
module.exports = Widget;

View File

@ -1,63 +1,49 @@
var Object = require ('./object'); var Object = require('./object');
var Param = require ('./param'); var Param = require('./param');
var Hash = require ('./hash'); var Hash = require('./hash');
module.exports = new Class module.exports = new Class({
({
Extends: Object Extends: Object
,Tag: 'vn-hash-param' ,Tag: 'vn-hash-param'
,Child: 'param' ,Child: 'param'
,Properties: ,Properties: {
{ param: {
param:
{
type: Param type: Param
,set: function (x) ,set: function(x) {
{ this.link({_param: x}, {'changed': this._onParamChange});
this.link ({_param: x}, {'changed': this._onParamChange}); this._refreshParam();
this._refreshParam ();
} }
,get: function () ,get: function() {
{
return this._param; return this._param;
} }
}, },
key: key: {
{
type: String type: String
,set: function (x) ,set: function(x) {
{
this._key = x; this._key = x;
this._onHashChange (); this._onHashChange();
} }
,get: function () ,get: function() {
{
return this._key; return this._key;
} }
}, },
value: value: {
{
type: Object type: Object
,set: function (x) ,set: function(x) {
{ this._setValue(x, true);
this._setValue (x, true);
} }
,get: function () ,get: function() {
{
return this._value; return this._value;
} }
}, },
type: type: {
{
type: Object type: Object
,set: function (x) ,set: function(x) {
{
this._type = x; this._type = x;
this._onHashChange (); this._onHashChange();
} }
,get: function () ,get: function() {
{
return this._type; return this._type;
} }
} }
@ -69,82 +55,73 @@ module.exports = new Class
,_key: null ,_key: null
,_type: null ,_type: null
,initialize: function (props) ,initialize: function(props) {
{ this.parent(props);
this.parent (props); var listener = Hash.getListener();
var listener = Hash.getListener (); this.link({_listener: listener}, {'changed': this._onHashChange});
this.link ({_listener: listener}, {'changed': this._onHashChange}); this._onHashChange();
this._onHashChange ();
} }
,_onHashChange: function () ,_onHashChange: function() {
{
if (this._hashLock || !this._key || !this._listener) if (this._hashLock || !this._key || !this._listener)
return; return;
var newValue = Hash.get (this._key); var newValue = Hash.get(this._key);
if (newValue === '') if (newValue === '')
newValue = null; newValue = null;
if (this._type && newValue !== undefined && newValue !== null) if (this._type && newValue !== undefined && newValue !== null)
switch (this._type) switch (this._type) {
{
case Boolean: case Boolean:
newValue = (/^(true|1)$/i).test (newValue); newValue = (/^(true|1)$/i).test(newValue);
break; break;
case Number: case Number:
newValue = 0 + new Number (newValue); newValue = 0 + new Number(newValue);
break; break;
} }
this._hashLock = true; this._hashLock = true;
this._setValue (newValue, true); this._setValue(newValue, true);
this._hashLock = false; this._hashLock = false;
} }
,_setValue: function (newValue, signal) ,_setValue: function(newValue, signal) {
{
if (newValue == this._value) if (newValue == this._value)
return; return;
this._value = newValue; this._value = newValue;
if (this._key && !this._hashLock) if (this._key && !this._hashLock) {
{
this._hashLock = true; this._hashLock = true;
var map = {}; var map = {};
map[this._key] = newValue; map[this._key] = newValue;
Hash.add (map); Hash.add(map);
this._hashLock = false; this._hashLock = false;
} }
this._refreshParam (); this._refreshParam();
if (signal) if (signal)
this.signalEmit ('changed', newValue); this.signalEmit('changed', newValue);
} }
,_refreshParam: function () ,_refreshParam: function() {
{ if (this._param && !this._paramLock) {
if (this._param && !this._paramLock)
{
this._paramLock = true; this._paramLock = true;
this._param.value = this._value; this._param.value = this._value;
this._paramLock = false; this._paramLock = false;
} }
} }
,_onParamChange: function () ,_onParamChange: function() {
{
if (this._paramLock) if (this._paramLock)
return; return;
this._paramLock = true; this._paramLock = true;
this._setValue (this._param.value); this._setValue(this._param.value);
this._paramLock = false; this._paramLock = false;
} }
}); });

View File

@ -4,13 +4,14 @@ var HashListener = require('./hash-listener');
/** /**
* Class to handle the URL. * Class to handle the URL.
*/ */
module.exports = module.exports = {
{ path: null
_hash: null ,_hash: null
,_hashMap: {} ,_hashMap: {}
,_listener: null ,_listener: null
,initialize: function() { ,initialize: function() {
this.$ = this._hasMap;
this._listener = new HashListener(); this._listener = new HashListener();
this._hashChangedHandler = this._hashChanged.bind(this); this._hashChangedHandler = this._hashChanged.bind(this);
@ -76,6 +77,7 @@ module.exports =
if (newHash !== this._hash) { if (newHash !== this._hash) {
this._hashMap = map; this._hashMap = map;
this.$ = map;
this._hash = newHash; this._hash = newHash;
this._blockChanged = true; this._blockChanged = true;
@ -118,7 +120,7 @@ module.exports =
return; return;
var newMap = hashMap = {}; var newMap = hashMap = {};
var kvPairs = newHash.substr(2).split('&'); var kvPairs = newHash.substring(2).split('&');
for (var i = 0; i < kvPairs.length; i++) { for (var i = 0; i < kvPairs.length; i++) {
var kvPair = kvPairs[i].split('=', 2); var kvPair = kvPairs[i].split('=', 2);
@ -128,6 +130,7 @@ module.exports =
} }
this._hashMap = newMap; this._hashMap = newMap;
this.$ = newMap;
this._hash = newHash; this._hash = newHash;
this._listener.changed(); this._listener.changed();
} }

View File

@ -4,44 +4,38 @@
* *
* @param signals Map with all connected signal handlers * @param signals Map with all connected signal handlers
*/ */
module.exports = new Class module.exports = new Class({
({
Tag: 'vn-object' Tag: 'vn-object'
,Properties: {} ,Properties: {}
,_refCount: 1 ,_refCount: 1
,_signalData: null ,_signalData: null
,initialize: function (props) ,initialize: function(props) {
{ this.setProperties(props);
this.setProperties (props);
} }
,setProperties: function (props) ,setProperties: function(props) {
{
for (var prop in props) for (var prop in props)
this[prop] = props[prop]; this[prop] = props[prop];
} }
,ref: function () ,ref: function() {
{
this._refCount++; this._refCount++;
return this; return this;
} }
,unref: function () ,unref: function() {
{
this._refCount--; this._refCount--;
if (this._refCount === 0) if (this._refCount === 0)
this._destroy (); this._destroy();
} }
,loadXml: function (builder, node) {} ,loadXml: function(builder, node) {}
,appendChild: function (child) {} ,appendChild: function(child) {}
,_signalInit: function () ,_signalInit: function() {
{
if (!this._signalData) if (!this._signalData)
this._signalData = { this._signalData = {
signals: {}, signals: {},
@ -56,22 +50,19 @@ module.exports = new Class
* @param {Function} callback The callback * @param {Function} callback The callback
* @param {Object} instance The instance * @param {Object} instance The instance
*/ */
,on: function (id, callback, instance) ,on: function(id, callback, instance) {
{ if (!(callback instanceof Function)) {
if (!(callback instanceof Function)) console.warn('Vn.Object: Invalid callback for signal \'%s\'', id);
{
console.warn ('Vn.Object: Invalid callback for signal \'%s\'', id);
return; return;
} }
this._signalInit (); this._signalInit();
var callbacks = this._signalData.signals[id]; var callbacks = this._signalData.signals[id];
if (!callbacks) if (!callbacks)
callbacks = this._signalData.signals[id] = []; callbacks = this._signalData.signals[id] = [];
callbacks.push callbacks.push({
({
blocked: false blocked: false
,callback: callback ,callback: callback
,instance: instance ,instance: instance
@ -85,8 +76,7 @@ module.exports = new Class
* @param {Function} callback The callback * @param {Function} callback The callback
* @param {Boolean} block %true for lock the signal, %false for unlock * @param {Boolean} block %true for lock the signal, %false for unlock
*/ */
,blockSignal: function (id, callback, block, instance) ,blockSignal: function(id, callback, block, instance) {
{
if (!this._signalData) if (!this._signalData)
return; return;
@ -106,8 +96,7 @@ module.exports = new Class
* *
* @param {String} id The signal identifier * @param {String} id The signal identifier
*/ */
,signalEmit: function (id) ,signalEmit: function(id) {
{
if (!this._signalData) if (!this._signalData)
return; return;
@ -117,14 +106,14 @@ module.exports = new Class
return; return;
var callbackArgs = []; var callbackArgs = [];
callbackArgs.push (this); callbackArgs.push(this);
for (var i = 1; i < arguments.length; i++) for (var i = 1; i < arguments.length; i++)
callbackArgs.push (arguments[i]); callbackArgs.push(arguments[i]);
for (var i = 0; i < callbacks.length; i++) for (var i = 0; i < callbacks.length; i++)
if (!callbacks[i].blocked) if (!callbacks[i].blocked)
callbacks[i].callback.apply (callbacks[i].instance, callbackArgs); callbacks[i].callback.apply(callbacks[i].instance, callbackArgs);
} }
/** /**
@ -134,8 +123,7 @@ module.exports = new Class
* @param {Function} callback The connected callback * @param {Function} callback The connected callback
* @param {Object} instance The instance * @param {Object} instance The instance
*/ */
,disconnect: function (id, callback, instance) ,disconnect: function(id, callback, instance) {
{
if (!this._signalData) if (!this._signalData)
return; return;
@ -147,7 +135,7 @@ module.exports = new Class
for (var i = 0; i < callbacks.length; i++) for (var i = 0; i < callbacks.length; i++)
if (callbacks[i].callback == callback if (callbacks[i].callback == callback
&& callbacks[i].instance == instance) && callbacks[i].instance == instance)
callbacks.splice (i--, 1); callbacks.splice(i--, 1);
} }
/** /**
@ -155,20 +143,18 @@ module.exports = new Class
* *
* @param {Object} instance The instance * @param {Object} instance The instance
*/ */
,disconnectByInstance: function (instance) ,disconnectByInstance: function(instance) {
{
if (!this._signalData) if (!this._signalData)
return; return;
var signals = this._signalData.signals; var signals = this._signalData.signals;
for (var signalId in signals) for (var signalId in signals) {
{
var callbacks = signals[signalId]; var callbacks = signals[signalId];
for (var i = 0; i < callbacks.length; i++) for (var i = 0; i < callbacks.length; i++)
if (callbacks[i].instance == instance) if (callbacks[i].instance == instance)
callbacks.splice (i--, 1); callbacks.splice(i--, 1);
} }
} }
@ -176,45 +162,39 @@ module.exports = new Class
* Destroys the object, this method should only be called before losing * Destroys the object, this method should only be called before losing
* the last reference to the object. * the last reference to the object.
*/ */
,_destroy: function () ,_destroy: function() {
{
if (!this._signalData) if (!this._signalData)
return; return;
var links = this._signalData.links; var links = this._signalData.links;
for (var key in links) for (var key in links)
links[key].disconnectByInstance (this); links[key].disconnectByInstance(this);
this._signalData = null; this._signalData = null;
} }
,link: function (prop, handlers) ,link: function(prop, handlers) {
{ this._signalInit();
this._signalInit ();
var links = this._signalData.links; var links = this._signalData.links;
for (var key in prop) for (var key in prop) {
{
var newObject = prop[key]; var newObject = prop[key];
var oldObject = this[key]; var oldObject = this[key];
if (oldObject) if (oldObject) {
{ oldObject.disconnectByInstance(this);
oldObject.disconnectByInstance (this); oldObject.unref();
oldObject.unref ();
} }
this[key] = newObject; this[key] = newObject;
if (newObject) if (newObject) {
{ links[key] = newObject.ref();
links[key] = newObject.ref ();
for (var signal in handlers) for (var signal in handlers)
newObject.on (signal, handlers[signal], this); newObject.on(signal, handlers[signal], this);
} } else if (oldObject)
else if (oldObject)
delete links[key]; delete links[key];
} }
} }

View File

@ -3,14 +3,14 @@ Hedera.DeliveryNote = new Class({
Extends: Hedera.Report, Extends: Hedera.Report,
onTicketReady: function(form) { onTicketReady: function(form) {
if (form.get('method') != 'PICKUP') if (form.$.method != 'PICKUP')
Vn.Node.setText(this.$.method, _('Agency')); Vn.Node.setText(this.$.method, _('Agency'));
else else
Vn.Node.setText(this.$.method, _('Warehouse')); Vn.Node.setText(this.$.method, _('Warehouse'));
}, },
discountRenderer: function(column, form) { discountRenderer: function(column, form) {
column.value = form.get('discount') ? form.get('discount') : null; column.value = form.$.discount ? form.$.discount : null;
}, },
subtotalRenderer: function(column, form) { subtotalRenderer: function(column, form) {
@ -18,13 +18,13 @@ Hedera.DeliveryNote = new Class({
}, },
subtotal: function(form) { subtotal: function(form) {
var price = form.get('price'); var price = form.$.price;
var discount = form.get('discount'); var discount = form.$.discount;
return form.get('quantity') * price *((100 - discount) / 100); return form.$.quantity * price *((100 - discount) / 100);
}, },
serviceSubtotal: function(column, form) { serviceSubtotal: function(column, form) {
column.value = form.get('quantity') * form.get('price'); column.value = form.$.quantity * form.$.price;
}, },
onServicesChanged: function(model) { onServicesChanged: function(model) {

View File

@ -26,16 +26,15 @@ Hedera.ShelvesReport = new Class({
,onQueryExec: function(resultSet) { ,onQueryExec: function(resultSet) {
// Fetch query data // Fetch query data
var res = resultSet.fetchResult(); const row = resultSet.fetchObject();
res.next();
// Calculates the scale // Calculates the scale
var maxWidth = 160; var maxWidth = 160;
var maxHeight = 160; var maxHeight = 160;
var shelfWidth = res.get('width'); var shelfWidth = row.width;
var shelfHeight = res.get('trayHeight') * (res.get('nTrays') - 1) + res.get('topTrayHeight'); var shelfHeight = row.trayHeight * (row.nTrays - 1) + row.topTrayHeight;
var scale = maxWidth / shelfWidth; var scale = maxWidth / shelfWidth;
@ -44,46 +43,46 @@ Hedera.ShelvesReport = new Class({
// Calculates the shelf dimensions // Calculates the shelf dimensions
var shelf = this.shelf = var shelf = this.shelf = {
{ nTrays: row.nTrays
nTrays: res.get('nTrays') ,trayHeight: row.trayHeight * scale
,trayHeight: res.get('trayHeight') * scale ,topTrayHeight: row.topTrayHeight * scale
,topTrayHeight: res.get('topTrayHeight') * scale ,width: row.width * scale
,width: res.get('width') * scale ,depth: row.depth * scale
,depth: res.get('depth') * scale
}; };
// Gets the items // Gets the items
var items = this.items = []; var items = this.items = [];
var remainings = this.remainings = []; var remainings = this.remainings = [];
var res = resultSet.fetchResult(); var res = resultSet.fetchData();
if (res.data.length == 0) { if (res.length == 0) {
Htk.Toast.showError(_('No items found, check that all fields are correct')); Htk.Toast.showError(_('No items found, check that all fields are correct'));
return; return;
} }
var boxScale = scale * 10; var boxScale = scale * 10;
while (res.next()) for (const row of res) {
if (!this.maxAmount || res.get('etiquetas') <= this.maxAmount) { if (!this.maxAmount || row.etiquetas <= this.maxAmount) {
items.push({ items.push({
id: res.get('Id_Article') id: row.Id_Article
,name: res.get('Article') ,name: row.Article
,packing: res.get('packing') ,packing: row.packing
,amount: res.get('etiquetas') ,amount: row.etiquetas
,boxHeight: res.get('height') * boxScale ,boxHeight: row.height * boxScale
,boxWidth: res.get('width') * boxScale ,boxWidth: row.width * boxScale
,boxDepth: res.get('depth') * boxScale ,boxDepth: row.depth * boxScale
}); });
} else { } else {
remainings.push({ remainings.push({
id: res.get('Id_Article') id: row.Id_Article
,name: res.get('Article') ,name: row.Article
,packing: res.get('packing') ,packing: row.packing
,amount: res.get('etiquetas') ,amount: row.etiquetas
}); });
}
} }
// Intializes the allocator // Intializes the allocator

View File

@ -132,12 +132,11 @@ class Query extends Vn\Web\JsonRequest {
$tableIndex = $tableMap[$column->table]; $tableIndex = $tableMap[$column->table];
if ($column->flags & MYSQLI_PRI_KEY_FLAG) if ($column->flags & MYSQLI_PRI_KEY_FLAG)
$resultMap['tables'][$tableIndex]['pks'][] = $i; $resultMap['tables'][$tableIndex]['pks'][] = $column->name;
$default = $this->castValue($column->def, $type); $default = $this->castValue($column->def, $type);
$resultMap['columns'][] = $resultMap['columns'][] = [
[
'type' => $type, 'type' => $type,
'flags' => $column->flags, 'flags' => $column->flags,
'def' => $default, 'def' => $default,