{content}',
''
)
});
theThis.tab_StockBySuppliers = new Ext.CTBStockBySuppliers({
region : 'center',
Global_StockBrowser_Parent : theThis,
Global_StockBrowser_PageSize : theThis.pageSize,
HideColumn_StockCode : true,
HideColumn_SupplierStockCode : true,
HideColumn_ParLevel : true,
HideColumn_GST : true,
HideColumn_Nutrition : true,
HideColumn_Report : true,
HideColumn_Wastage : true,
readOnly : true
});
theThis.items = [theThis.tab_StockBySuppliers, theThis.pnl_Title];
this.buttons = myButtons;
this.initTools();
Ext.CTBDuplicatedStockDetector.superclass.initComponent.call(this);
},
clearSelections : function(){
var theThis = this;
if (theThis.tab_StockBySuppliers.rendered)
theThis.tab_StockBySuppliers.clearSelections();
},
initButtons : function(){
var theThis = this;
var buttons = [
theThis.btn_Merge = new Ext.Button({
text: 'Merge Selected Stock',
tooltip : 'Merge all selected stock into one single stock item.',
iconCls : 'icon-fix', scale : 'large',
handler : function(){
var selectedRecords = theThis.tab_StockBySuppliers.getGrid_StockBySuppliers().getSelectionModel().getSelections();
if (selectedRecords.length == 0){
showErrorNotification('Notice', 'You haven\'t choose any stock to merge.');
return;
}
else {
theThis.listOfMergeStockSupplierIds = new Array();
for (var i = 0; i < selectedRecords.length; i++){
theThis.listOfMergeStockSupplierIds[i] = selectedRecords[i].data.stockSupplierId;
}
}
//theThis.setTitle('
Select the stock you want all of them to be.
');
theThis.pnl_Title.tpl.overwrite(theThis.pnl_Title.body, {content : 'Select the stock you want all of them to be.'});
theThis.btn_Confirm.setVisible(true);
theThis.btn_Merge.setVisible(false);
theThis.tab_StockBySuppliers.clearSelections();
}
}),
theThis.btn_Confirm = new Ext.Button({
text: 'Confirm Merging',
tooltip : 'Merge all selected stock into one single stock item.',
iconCls : 'icon-ok-large', scale : 'large',
hidden : true,
handler : function(){
var selectedRecords = theThis.tab_StockBySuppliers.getGrid_StockBySuppliers().getSelectionModel().getSelections();
if (selectedRecords.length == 1){
showConfirmMessage('Are you sure ?',
function(){
theThis.mainStockSupplierId = selectedRecords[0].data.stockSupplierId;
var wrapperObject = {listOfNumbers : theThis.listOfMergeStockSupplierIds};
theThis.tab_StockBySuppliers.loadMask.show();
Ext.Ajax.request({
method: 'POST',
url: '/Stock/MergeDuplicatedStock',
params:
{
mergeIntoStockSupplierId : theThis.mainStockSupplierId,
listOfStockSupplierIds : Ext.util.JSON.encode(wrapperObject)
},
success : function(result, request) {
theThis.tab_StockBySuppliers.loadMask.hide();
theThis.resetState();
//theThis.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.tab_StockBySuppliers.loadMask.hide();
}
});
}
);
}
else {
if (selectedRecords.length == 0) showErrorNotification('Notice', 'Please select ONE merging stock.');
else showErrorNotification('Notice', 'You CAN NOT choose more than one merging stock.');
}
}
}),
theThis.btn_Cancel = new Ext.Button({
text: 'Cancel',
iconCls : 'icon-cancel-large', scale : 'large',
handler : function(){
theThis.hide();
}
})
];
return buttons;
}
});
Ext.reg('CTBDuplicatedStockDetector', Ext.CTBDuplicatedStockDetector);
Ext.CTBStockBrowser = Ext.extend(Ext.Window, {
title: 'Stock Browser',
layout: 'border',
closeAction: 'hide',
iconCls : 'icon-v3-ctb-logo',
cls : 'ctbwindow-detail-general',
expandOnShow : true,
closable: true,
resizable: true,
modal: true,
plain: true,
minimizable : true,
maximizable : true,
monitorResize : true,
width:800,
height:500,
defaults: {
split: true,
animFloat: false,
autoHide: false,
useSplitTips: true
},
Global_StockBrowser_CallbackFunction : null,
callback_Cancel : null,
Global_StockBrowser_AssignedSupplierId : -1,
Global_StockBrowser_SelectedRecords : null,
Global_StockBrowser_PageSize : CTB.init.itemPerPage || 100,
Global_StockBrowser_SelectedStockId : -1, // This is use for all stock tab
Global_StockBrowser_Callback_AfterShow : null,
IsForRequisitionIn : false,
HideSupplierBy : true,
HideColumn_StockCode : false,
HideColumn_SupplierStockCode : false,
HideColumn_ParLevel : false,
HideColumn_GST : false,
HideColumn_Nutrition : false,
HideColumn_Report : false,
HideColumn_Wastage : false,
HideColumn_UnitAvailable : true,
HideColumn_UnitPoints : true,
HideColumn_InvoiceUnit : false,
HideColumn_InvoiceUOM : false,
HideTab_Recipe : true,
HideTab_StockBySupplier : false,
onlyReturnStockRecord : false,
returnRecipeRecords : false, // This flag = true will tell the browser to return the selected recipe records instead of convert the recipe to a stock item and return the stockSupplierId
activeTab : 0,
readOnly : false,
searchAllStocksValue : '',
isRecipeTotalCostIncludingLabour : false,
forcedOutletId : -1,
listeners : {
scope : this,
'beforehide' : function(theThis){
theThis.Global_StockBrowser_AssignedSupplierId = -1;
theThis.IsForRequisitionIn = false;
theThis.callback_Cancel = null; // Reset
theThis.forcedOutletId = -1; // Reset forced outlet ID everytime it's hidden
},
'beforeshow' : function(theThis){
// Fit this window to the client browser screen with 90%
fitWindowSize(theThis, 90);
theThis.clearSelections();
},
'show' : function(theThis){
if (theThis.Global_StockBrowser_AssignedSupplierId != -1){
theThis.tab_StockBySuppliers.cmbSupplier.callback_AfterLoad = function(){
theThis.tab_StockBySuppliers.cmbSupplier.setValue(theThis.Global_StockBrowser_AssignedSupplierId);
theThis.tab_StockBySuppliers.cmbSupplier.disable();
theThis.tab_StockBySuppliers.getGrid_StockBySuppliers().getStore().baseParams = {supplierId : theThis.Global_StockBrowser_AssignedSupplierId, start : 0, limit : theThis.Global_StockBrowser_PageSize};
theThis.tab_StockBySuppliers.getGrid_StockBySuppliers().getStore().load();
}
// Hide list of all stocks
theThis.allTabs.hideTabStripItem(theThis.tab_ListOfDistinctStock);
}
else {
theThis.tab_StockBySuppliers.cmbSupplier.callback_AfterLoad = function(){
theThis.tab_StockBySuppliers.cmbSupplier.enable();
theThis.tab_StockBySuppliers.cmbSupplier.setValue(theThis.tab_StockBySuppliers.cmbSupplier.getStore().getAt(0).get('supId'));
theThis.tab_StockBySuppliers.getGrid_StockBySuppliers().getStore().baseParams = {supplierId : theThis.tab_StockBySuppliers.cmbSupplier.getValue(), start: 0, limit : theThis.Global_StockBrowser_PageSize};
theThis.tab_StockBySuppliers.getGrid_StockBySuppliers().getStore().load();
}
// Show list of all stocks
theThis.allTabs.unhideTabStripItem(theThis.tab_ListOfDistinctStock);
}
if (theThis.IsForRequisitionIn) {
theThis.tab_StockBySuppliers.cmbSupplier.getStore().baseParams.IsForRequisitionIn = true;
theThis.allTabs.setActiveTab(theThis.tab_StockBySuppliers);
// Hide list of all stocks
theThis.allTabs.hideTabStripItem(theThis.tab_ListOfDistinctStock);
// Reload the supplier list
theThis.tab_StockBySuppliers.cmbSupplier.getStore().load();
}
else {
theThis.tab_StockBySuppliers.cmbSupplier.getStore().baseParams.IsForRequisitionIn = false;
theThis.tab_StockBySuppliers.cmbSupplier.getStore().load();
}
// Hide tab recipe
if (theThis.HideTab_Recipe){
theThis.allTabs.hideTabStripItem(theThis.tab_Recipe);
}
// Hide tab stock by suppliers
if (theThis.HideTab_StockBySupplier){
theThis.allTabs.hideTabStripItem(theThis.tab_StockBySuppliers);
}
if (theThis.Global_StockBrowser_Callback_AfterShow != null)
{
theThis.Global_StockBrowser_Callback_AfterShow();
theThis.Global_StockBrowser_Callback_AfterShow = null;
}
if (theThis.searchAllStocksValue != null && theThis.searchAllStocksValue != '') {
theThis.tab_ListOfDistinctStock.searchByStockDescription(theThis.searchAllStocksValue);
theThis.searchAllStocksValue = '';
}
}
},
initComponent : function(){
var theThis = this;
// Init buttons
var myButtons = theThis.initButtons();
theThis.tab_ListOfDistinctStock = new Ext.CTBAllStocks({
Global_StockBrowser_Parent : theThis,
Global_StockBrowser_PageSize : theThis.Global_StockBrowser_PageSize,
HideSupplierBy : theThis.HideSupplierBy,
HideColumn_StockCode : theThis.HideColumn_StockCode,
HideColumn_SupplierStockCode : theThis.HideColumn_SupplierStockCode,
HideColumn_ParLevel : theThis.HideColumn_ParLevel,
HideColumn_GST : theThis.HideColumn_GST,
HideColumn_Nutrition : theThis.HideColumn_Nutrition,
HideColumn_Report : theThis.HideColumn_Report,
HideColumn_Wastage : theThis.HideColumn_Wastage,
readOnly : theThis.readOnly
});
theThis.tab_StockBySuppliers = new Ext.CTBStockBySuppliers({
Global_StockBrowser_Parent : theThis,
Global_StockBrowser_PageSize : theThis.Global_StockBrowser_PageSize,
HideColumn_StockCode : theThis.HideColumn_StockCode,
HideColumn_SupplierStockCode : theThis.HideColumn_SupplierStockCode,
HideColumn_ParLevel : theThis.HideColumn_ParLevel,
HideColumn_GST : theThis.HideColumn_GST,
HideColumn_Nutrition : theThis.HideColumn_Nutrition,
HideColumn_Report : theThis.HideColumn_Report,
HideColumn_Wastage : theThis.HideColumn_Wastage,
HideColumn_UnitAvailable : theThis.HideColumn_UnitAvailable,
HideColumn_UnitPoints : theThis.HideColumn_UnitPoints,
HideColumn_InvoiceUnit : theThis.HideColumn_InvoiceUnit,
HideColumn_InvoiceUOM : theThis.HideColumn_InvoiceUOM,
readOnly : theThis.readOnly
});
theThis.tab_Recipe = new Ext.CTBRecipeTreePanel({
title : 'Recipe',
readOnly : true,
HideWhatsNextButton : true,
ShowCheckboxSelection : true,
HideImportRecipeButton : true/*,
listeners : {
show : function(){
theThis.tab_Recipe.reloadData();
}
}*/
});
// All tabs
theThis.allTabs = new Ext.TabPanel({
region : 'center',
margins : '5 0 0 0',
activeTab : theThis.activeTab,
defaults : { autoScroll: false },
items : [
theThis.tab_StockBySuppliers, theThis.tab_ListOfDistinctStock, theThis.tab_Recipe
]
});
theThis.items = [theThis.allTabs];
this.buttons = myButtons;
this.initTools();
Ext.CTBStockBrowser.superclass.initComponent.call(this);
},
clearSelections : function(){
var theThis = this;
if (theThis.tab_StockBySuppliers.rendered)
theThis.tab_StockBySuppliers.clearSelections();
if (theThis.tab_ListOfDistinctStock.rendered)
theThis.tab_ListOfDistinctStock.clearSelections();
},
initButtons : function(){
var theThis = this;
var buttons = [
theThis.btn_SelectAndMoveToNextPage = new Ext.Button({
cls : 'ctb-btn-red',
text: 'Select and move to next page',
iconCls : 'icon-ok-large', scale : 'large',
handler : function(){
theThis.processSelections(true);
}
}),
theThis.btn_Select = new Ext.Button({
cls : 'ctb-btn-red',
text: 'Select',
iconCls : 'icon-ok-large', scale : 'large',
handler : function(){
theThis.processSelections();
}
}),
theThis.btn_Cancel = new Ext.Button({
text: 'Cancel',
iconCls : 'icon-cancel-large', scale : 'large',
handler : function(){
if (theThis.callback_Cancel != null) theThis.callback_Cancel();
theThis.hide();
}
})
];
return buttons;
},
returnStockRecordsOnly : function(){
var theThis = this;
// Get selected stock
var selectedStocks = theThis.tab_ListOfDistinctStock.getGrid_MasterStock().getSelectionModel().getSelections();
if (selectedStocks.length == 0) {
showErrorNotification('Notice', 'Please select stocks.');
return;
}
theThis.Global_StockBrowser_CallbackFunction(selectedStocks);
theThis.hide();
},
returnTabAllStocksSelections : function(processSelectionsNow){
var theThis = this;
// Get selected stock
var selectedStocks = theThis.tab_ListOfDistinctStock.getGrid_MasterStock().getSelectionModel().getSelections();
theThis.Global_StockBrowser_SelectedRecords = new Array();
for (var i = 0; i < selectedStocks.length; i++){
if (selectedStocks[i].data.stockSupplierId != -1){
theThis.Global_StockBrowser_SelectedRecords[i] = selectedStocks[i];
}
else {
theThis.Global_StockBrowser_SelectedRecords = null;
showWarningMessage('Some stocks that you have choosen don\'t have supplier.
Please check the suppliers for these stocks.');
return;
}
}
processSelectionsNow();
},
getStockSupplierIdsFromSelectedRecipes : function(recipeIds, recipeFolderIds, isRecipeTotalCostIncludingLabour, callback_Function){
var theThis = this;
theThis.tab_Recipe.loadMask.show();
Ext.Ajax.request({
method: 'POST',
url: '/StockSupplier/GetStockSupplierIdsFromSelectedRecipes',
params:
{
recipeIds : Ext.util.JSON.encode(recipeIds),
recipeFolderIds : Ext.util.JSON.encode(recipeFolderIds),
isRecipeTotalCostIncludingLabour : isRecipeTotalCostIncludingLabour,
forcedOutletId : theThis.forcedOutletId
},
success : function(result, request) {
theThis.tab_Recipe.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
//showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
theThis.Global_StockBrowser_SelectedRecords = jsonData.data;
callback_Function(); // jsonData.data is a list of stockSupplierIds returned
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.tab_Recipe.loadMask.hide();
}
}); // End ajax
},
returnTabRecipeSelections : function(processSelectionsNow){
var theThis = this;
var selectedRecipes = theThis.tab_Recipe.getSelectedRecipes();
if (!theThis.returnRecipeRecords) { // Save recipe as stock items and then return the stockSupplierId(s)
var recipeIds = new Array();
var recipeFolderIds = new Array();
for (var i = 0; i < selectedRecipes.length; i++){
var nodeId = getNumberIdFromStringId(selectedRecipes[i].id);
var nodeType = getPrefixFromStringId(selectedRecipes[i].id);
if (nodeType == 'recipe'){
recipeIds[recipeIds.length] = nodeId;
}
else if (nodeType == 'folder'){
recipeFolderIds[recipeFolderIds.length] = nodeId;
}
}
// Don't need below code any more because will always get the total cost without labour
/*
Ext.Msg.show({
title:'Confirm',
msg: 'Do you want to including labour into recipe\'s portion cost ?',
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.QUESTION,
fn : function(btn) {
if (btn == "yes") {
theThis.isRecipeTotalCostIncludingLabour = true;
} // End if
else {
theThis.isRecipeTotalCostIncludingLabour = false;
}
theThis.getStockSupplierIdsFromSelectedRecipes(recipeIds, recipeFolderIds, theThis.isRecipeTotalCostIncludingLabour, processSelectionsNow);
} // End handler function
});*/
theThis.isRecipeTotalCostIncludingLabour = false;
theThis.getStockSupplierIdsFromSelectedRecipes(recipeIds, recipeFolderIds, theThis.isRecipeTotalCostIncludingLabour, processSelectionsNow);
}
else {
theThis.tab_Recipe.getSelectedRecipeFullRecords(function(recipeRecords){
// Assign recipe records instead
theThis.Global_StockBrowser_CallbackFunction(recipeRecords);
theThis.hide();
});
}
},
processSelections : function(isMoveToNextPage){
var theThis = this;
if (isMoveToNextPage == null) isMoveToNextPage = false; // Default
// This function will check the selected records and validate them before pass them to the callback function
function processSelectionsNow(){
if (theThis.Global_StockBrowser_SelectedRecords != null && theThis.Global_StockBrowser_SelectedRecords.length > 0)
{
// Get selected stock supplier records
for (var i = 0; i < theThis.Global_StockBrowser_SelectedRecords.length; i++)
{
// Save data automatically if it's from online store
if (theThis.Global_StockBrowser_SelectedRecords[i].data.isFromOnline == true) {
theThis.tab_StockBySuppliers.saveData(function(){
theThis.Global_StockBrowser_CallbackFunction(theThis.Global_StockBrowser_SelectedRecords);
if (!isMoveToNextPage) theThis.hide();
});
return;
}
// Check if the stock is new and hasn't been saved
if (theThis.Global_StockBrowser_SelectedRecords[i].data.stockSupplierId < 0
|| theThis.Global_StockBrowser_SelectedRecords[i].data.stockId < 0
)
{
Ext.Msg.show({
title:'Notice',
msg: 'You have choosed some stocks has not been saved.
Please save before use.',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
return;
}
}
if (!isMoveToNextPage) theThis.hide();
theThis.Global_StockBrowser_CallbackFunction(theThis.Global_StockBrowser_SelectedRecords);
// If flag tell us to move to next page
if (isMoveToNextPage) {
// Check if there is possible to move to the next page
if (theThis.allTabs.getActiveTab() == theThis.tab_ListOfDistinctStock)
{
var pt_StockBrowser_AllStocks = theThis.tab_ListOfDistinctStock.getPagingToolbar();
var activePage = Math.ceil((pt_StockBrowser_AllStocks.cursor + pt_StockBrowser_AllStocks.pageSize) / pt_StockBrowser_AllStocks.pageSize);
var totalCount = theThis.tab_ListOfDistinctStock.getGrid_MasterStock().getStore().getTotalCount();
// Only move to next page if the active page is not out of range
// Example :
// activePage = 2 => activePage + 1 = 3
// totalCount = 160
// pageSize = 100
// Math.ceil(totalCount / pt_StockBrowser_AllStocks.pageSize) = 2
// So activePage > Math.ceil(totalCount / pt_StockBrowser_AllStocks.pageSize), we can not move
if ((activePage+1) <= Math.ceil(totalCount / theThis.tab_ListOfDistinctStock.getPagingToolbar().pageSize))
{
theThis.tab_ListOfDistinctStock.getPagingToolbar().moveNext();
}
else {
showErrorNotification('Notice', 'This is the last page !');
}
}
else if (theThis.allTabs.getActiveTab() == theThis.tab_StockBySuppliers)
{
var pt_StockBrowser_StockBySupplier = theThis.tab_StockBySuppliers.getPagingToolbar();
var activePage = Math.ceil((pt_StockBrowser_StockBySupplier.cursor + pt_StockBrowser_StockBySupplier.pageSize) / pt_StockBrowser_StockBySupplier.pageSize);
var totalCount = theThis.tab_StockBySuppliers.getGrid_StockBySuppliers().getStore().getTotalCount();
// Only move to next page if the active page is not out of range
// Example :
// activePage = 2 => activePage + 1 = 3
// totalCount = 160
// pageSize = 100
// Math.ceil(totalCount / pt_StockBrowser_StockBySupplier.pageSize) = 2
// So activePage > Math.ceil(totalCount / pt_StockBrowser_StockBySupplier.pageSize), we cannot move
if ((activePage+1) <= Math.ceil(totalCount / theThis.tab_StockBySuppliers.getPagingToolbar().pageSize))
{
theThis.tab_StockBySuppliers.getPagingToolbar().moveNext();
}
else {
showErrorNotification('Notice', 'This is the last page !');
}
}
}
}
else {
showWarningMessage('Please select some stocks !');
}
}
// Check if there is callback function has been set
if (theThis.Global_StockBrowser_CallbackFunction != null)
{
var activeTab = theThis.allTabs.getActiveTab();
// This special condition is to only return stock record without stock-supplier relationship
if (theThis.onlyReturnStockRecord == true && activeTab == theThis.tab_ListOfDistinctStock){
theThis.returnStockRecordsOnly();
return;
}
// If the selected record from All stocks tab
if (activeTab == theThis.tab_ListOfDistinctStock)
{
theThis.returnTabAllStocksSelections(function(){
processSelectionsNow();
});
}
else if (activeTab == theThis.tab_StockBySuppliers){ // Select stocks from StockBySupplier tab
// Get selected stock
var selectedStocks = theThis.tab_StockBySuppliers.getGrid().getSelectionModel().getSelections();
theThis.Global_StockBrowser_SelectedRecords = selectedStocks;
processSelectionsNow();
}
else if (activeTab == theThis.tab_Recipe) { // Select stocks from Recipe tab
theThis.returnTabRecipeSelections(function(){
processSelectionsNow();
});
}
}
else {
Ext.Msg.show({
title:'Notice',
msg: 'Call back function has not been supplied !',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
}
}
});
// Get combobox unit of measurement
function getCombobox_UnitOfMeasurement()
{
var cmbGridUOM = new Ext.form.ComboBox({
store: Global_UnitOfMeasurement_Store,
displayField: 'UOMName',
valueField: 'UOMId',
typeAhead: true,
triggerAction: 'all',
editable: true,
lazyRender: true,
mode: 'local',
autoSelect : true,
forceSelection: true,
listeners: {
focus: function(p_This){
p_This.getEl().dom.select();
/*setTimeout(function(){
p_This.getEl().dom.select();
}, 500);*/
}
}
});
return cmbGridUOM;
}
// Get combobox stock category
function getCombobox_StockCategory()
{
var cmbGridStockCategory = new Ext.form.ComboBox({
store: Global_StockCategory_Store,
displayField: 'stockCategoryName',
valueField: 'stockCategoryId',
typeAhead: true,
triggerAction: 'all',
editable: true,
lazyRender: true,
mode: 'local',
autoSelect : true,
forceSelection: true,
listeners : {
focus: function(p_This){
p_This.getEl().dom.select();
}
}
});
return cmbGridStockCategory;
}
Ext.reg('CTBStockBrowser', Ext.CTBStockBrowser);
var Global_ContactBrowser_CallbackFunction;
var Global_ContactBrowser_SelectedContactId = -1; // Nothing has been choosed
var Global_ContactBrowser_SelectedRecords = null;
//var Global_ContactBrowser_LoadMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
var Global_ContactBrowser_PageSize = CTB.init.itemPerPage || 100;
var Global_ContactBrowser_AssignedSupplierId = -1;
function chk_PrimaryContact_OnChange(checkbox_Object, identifier)
{
if (identifier == null) identifier = ""; // Identifier is using for make another stock browser in the same script file (Prevent Duplicated ID)
Ext.getCmp('grid_ContactBySuppliers' + identifier).getStore().getById(checkbox_Object.id).set('isPrimary', checkbox_Object.checked);
}
function getContactBrowserDialog(identifier){
if (identifier == null) identifier = ""; // Identifier is using for make another stock browser in the same script file (Prevent Duplicated ID)
// Combobox supplier
var cmbSupplier = getCombobox_ContactSupplier(identifier);
// ***************************************************************************************************
// Component Events
// ***************************************************************************************************
cmbSupplier.on({
select: function (p_combo, p_record, p_index) {
var supplierId = p_record.get('supId');
//Global_ContactBrowser_SelectedSupplierId = supplierId;
Ext.getCmp('grid_ContactBySuppliers' + identifier).getStore().baseParams = {supplierId : supplierId, start: 0, limit : Global_ContactBrowser_PageSize};
Ext.getCmp('grid_ContactBySuppliers' + identifier).getStore().load();
}
});
// Get stock by suppliers tab
var tab_ContactBySuppliers = getContactBySuppliers(identifier);
if (identifier != "") return allTabs; // Only return the tab panel if the identifier has been set (use for Stock Maintenance)
/**********************************/
/* Stock Browser Window Dialog */
/**********************************/
var ContactBrowserDialog = new Ext.Window({
title: 'Contact Browser',
id : 'dlg_ContactBrowser',
layout: 'border',
closeAction: 'hide',
iconCls : 'icon-stock',
expandOnShow : true,
closable: true,
resizable: true,
modal: true,
plain: true,
minimizable : true,
maximizable : true,
monitorResize : true,
//maximized : true,
width:800,
height:500,
defaults: {
split: true,
animFloat: false,
autoHide: false,
useSplitTips: true
},
buttons: [{
text: 'Select and go to next page',
iconCls : 'icon-ok-large', scale : 'large',
handler : function(){
if (Global_ContactBrowser_CallbackFunction)
{
//if (selectedSupplierIds.length > 0)
if (Global_ContactBrowser_SelectedContactId != -1)
{
// Get selected stock supplier records
for (var i = 0; i < Global_ContactBrowser_SelectedRecords.length; i++)
{
if (Global_ContactBrowser_SelectedRecords[i].data.contactId < 0)
{
Ext.Msg.show({
title:'Notice',
msg: 'You have choosed some contacts has not been saved.
Please save before use.',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
return;
}
}
Global_ContactBrowser_CallbackFunction(Global_ContactBrowser_SelectedRecords);
}
else {
Ext.Msg.show({
title:'Notice',
msg: 'Please select a contact',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
}
}
else {
Ext.Msg.show({
title:'Notice',
msg: 'Call back function has not been supplied !',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
}
}
},{
text: 'Select',
iconCls : 'icon-ok-large', scale : 'large',
handler : function(){
if (Global_ContactBrowser_CallbackFunction)
{
//if (selectedSupplierIds.length > 0)
if (Global_ContactBrowser_SelectedContactId != -1)
{
// Get selected stock supplier records
for (var i = 0; i < Global_ContactBrowser_SelectedRecords.length; i++)
{
if (Global_ContactBrowser_SelectedRecords[i].data.contactId < 0)
{
Ext.Msg.show({
title:'Notice',
msg: 'You have choosed some contacts has not been saved.
Please save before use.',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
return;
}
}
ContactBrowserDialog.hide();
Global_ContactBrowser_CallbackFunction(Global_ContactBrowser_SelectedRecords);
}
else {
Ext.Msg.show({
title:'Notice',
msg: 'Please select a contact',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
}
}
else {
Ext.Msg.show({
title:'Notice',
msg: 'Call back function has not been supplied !',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
}
}
},{
text: 'Cancel',
iconCls : 'icon-cancel-large', scale : 'large',
handler : function(){
ContactBrowserDialog.hide();
}
}],
items : [tab_ContactBySuppliers],
listeners : {
'beforehide' : function(p_This){
Global_ContactBrowser_AssignedSupplierId = -1;
},
'beforeshow' : function(p_This){
// Fit this window to the client browser screen with 90%
fitWindowSize(p_This, 80);
},
'show' : function(p_This){
if (Global_ContactBrowser_AssignedSupplierId != -1){
cmbSupplier.setValue(Global_ContactBrowser_AssignedSupplierId);
cmbSupplier.disable();
Ext.getCmp('grid_ContactBySuppliers').getStore().baseParams = {supplierId : Global_ContactBrowser_AssignedSupplierId, start : 0, limit : Global_ContactBrowser_PageSize};
Ext.getCmp('grid_ContactBySuppliers').getStore().load();
}
else {
cmbSupplier.enable();
cmbSupplier.setValue(cmbSupplier.getStore().getAt(0).get('supId'));
Ext.getCmp('grid_ContactBySuppliers').getStore().baseParams = {supplierId : cmbSupplier.getValue(), start: 0, limit : Global_ContactBrowser_PageSize};
Ext.getCmp('grid_ContactBySuppliers').getStore().load();
}
//p_This.getEl().fadeIn();
}
}
});
return ContactBrowserDialog;
}
var Global_ContactBrowser_ContactRecord = null;
// This return a panel
// Contains list of stock but filter by supplier
// Choose stocks in multiple mode (can choose more than one stock at the same time)
function getContactBySuppliers(identifier)
{
if (identifier == null) identifier = "";
// shorthand alias
var fm = Ext.form;
// ***************************************************************************************************
// Data Fields
// ***************************************************************************************************
var record = Ext.data.Record.create([
{ name: 'contactId', type: 'number' },
{ name: 'contactFirstName', type: 'string' },
{ name: 'phoneNo', type: 'string' },
{ name: 'phone2', type: 'string' },
{ name: 'phone3', type: 'string' },
{ name: 'faxNo', type: 'string' },
{ name: 'email', type: 'string' },
{ name: 'website', type: 'string' },
{ name: 'isPrimary', type: 'boolean' },
{ name: 'notes', type: 'string' },
{ name: 'supplierId', type: 'number' },
{ name: 'isActive', type: 'boolean'}, // Using for deleting
{ name: 'outletId', type: 'number'}
]);
Global_ContactBrowser_ContactRecord = record; // Initialize for the global variable
// ***************************************************************************************************
// Stores
// ***************************************************************************************************
var contactBySupplier_Store = new Ext.data.JsonStore({
baseParams : {supplierId: -1, start : 0, limit : Global_ContactBrowser_PageSize},
proxy: new Ext.data.HttpProxy({
url: '/Contact/SearchContactsBySupplierId',
dataType: 'json',
method: 'POST'
}),
fields: record,
root: 'data',
idProperty: 'contactId',
totalProperty : 'totalCount',
listeners : {
'load' : function(){
contactSm.clearSelections();
},
'loadexception' : function(){
showStoreLoadingErrorMessage(contactBySupplier_Store);
}
}
});
// ***************************************************************************************************
// Combobox
// ***************************************************************************************************
var cmbSupplier = Ext.getCmp('cmb_ContactBrowser_Supplier' + identifier);
//-------------------------------------------------------------------
// Selection model
//-------------------------------------------------------------------
var contactSm = new Ext.grid.CheckboxSelectionModel({
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
// Do nothing at the moment
var selectedRecords = sm.getSelections();
// Assign the selected records
Global_ContactBrowser_SelectedRecords = selectedRecords;
// Assign the selected ids
Global_ContactBrowser_SelectedContactId = -1;
if (selectedRecords.length > 0){
Global_ContactBrowser_SelectedContactId = new Array();
for (var i = 0;i < selectedRecords.length;i++)
{
Global_ContactBrowser_SelectedContactId[i] = selectedRecords[i].data.contactId;
}
}
}
}
});
// ***************************************************************************************************
// Grid
// ***************************************************************************************************
// Column Models
var contactCM = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults: {
sortable: true // columns are not sortable by default
},
columns: [ contactSm,
{ header: 'contactId', dataIndex: 'contactId', hidden: true },
{
header: '', dataIndex: 'contactId', hidden: false, width: 2,
//renderer: Ext.util.Format.comboRenderer(cmbSupplier)
renderer: function(val)
{
var theRecord = contactBySupplier_Store.getById(val);
var result = markNormal("", true);
if (val < 0) result = markNew(result, true);
if (!theRecord.data.isActive) result = markDeleted(result, true);
return result;
}
},
{ header: 'Name', dataIndex: 'contactFirstName', width : 18,
editor: {
xtype: 'textfield',
allowBlank: false
},
renderer : function(val){
if (val == "")
{
return '
Empty ... ';
}
else return '
'+val+' ';
}
},
{ header: 'Email', dataIndex: 'email', width : 35,
editor: {
xtype: 'textfield',
allowBlank: false
},
renderer : function(val){
if (val == "")
{
return '
Empty ... ';
}
else return '
'+val+' ';
}
},
{ header: 'Phone', dataIndex: 'phoneNo', width : 10,
editor: {
xtype: 'textfield',
allowBlank: false
},
renderer : function(val){
if (val == "")
{
return '
Empty ... ';
}
else return '
'+val+' ';
}
},
{ header: 'Fax', dataIndex: 'faxNo', width : 10,
editor: {
xtype: 'textfield',
allowBlank: false
},
renderer : function(val){
if (val == "")
{
return '
Empty ... ';
}
else return '
'+val+' ';
}
},
{ header: 'Website', dataIndex: 'website', width : 20,
editor: {
xtype: 'textfield',
allowBlank: false
},
renderer : function(val){
if (val == "")
{
return '
Empty ... ';
}
else return '
'+val+' ';
}
},
{ header: 'Primary Contact', dataIndex: 'contactId', width: 5,
renderer: function(value) {
var realValue = grid_ContactBySuppliers.getStore().getById(value).get('isPrimary');
return "
";
}
}
]
});
/********************************************************************************************/
var txt_ContactBySupplier_SearchContactValue;
/****************************/
/* Master Stock Grid */
/****************************/
var grid_ContactBySuppliers = new Ext.grid.EditorGridPanel({
id : 'grid_ContactBySuppliers' + identifier,
region: 'center',
store: contactBySupplier_Store,
frame: true,
listeners : {
rowclick : function ( p_this, p_rowIndex, p_eventObject ) {
// Hightlight the selected row
var selectedRow = p_this.getView().getRow(p_rowIndex);
Ext.get(selectedRow).highlight();
},
beforeshow : function(p_This){
//cmbSupplier.reset();
}
},
tbar: [
{
xtype : 'button',
iconCls : 'icon-save-large', scale : 'large',
text : 'Save',
handler : function(){
// Get modified records
var modifiedRecords = grid_ContactBySuppliers.getStore().getModifiedRecords();
var jsonArray = new Array();
for (var i = 0, row; row = modifiedRecords[i]; i++)
{
jsonArray[i] = {
contactId : modifiedRecords[i].data.contactId,
contactFirstName : modifiedRecords[i].data.contactFirstName,
phoneNo : modifiedRecords[i].data.phoneNo,
phone2 : modifiedRecords[i].data.phone2,
phone3 : modifiedRecords[i].data.phone3,
faxNo : modifiedRecords[i].data.faxNo,
email : modifiedRecords[i].data.email,
website : modifiedRecords[i].data.website,
isPrimary : modifiedRecords[i].data.isPrimary,
notes : modifiedRecords[i].data.notes,
supplierId : modifiedRecords[i].data.supplierId,
isActive : modifiedRecords[i].data.isActive,
outletId : modifiedRecords[i].data.outletId
};
}
var listOfContacts = {listOfContacts : jsonArray};
var jsonObject = Ext.util.JSON.encode(listOfContacts);
// Submit data
var Global_ContactBrowser_LoadMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
Global_ContactBrowser_LoadMask.show();
Ext.Ajax.request({
method: 'POST',
url: '/Contact/UpdateContacts',
params:
{
contactData : jsonObject
},
success : function(result, request) {
Global_ContactBrowser_LoadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
grid_ContactBySuppliers.getStore().commitChanges();
grid_ContactBySuppliers.getStore().reload();
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
Global_ContactBrowser_LoadMask.hide();
}
});
}
}, // And Save button
'-',
new Ext.Button({
iconCls: 'icon-add', scale : 'large',
id : 'btn_Add_Contact' + identifier,
text: 'Add',
//disabled: true,
handler: function () {
if (cmbSupplier.getStore().getById(cmbSupplier.getValue()) == null)
{
Ext.Msg.show({
title:'Notice',
msg: 'Please select a supplier!',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
return;
}
var newId = -getRandomNumber(); // Negative for new entry
var aNewRecord = new Global_ContactBrowser_ContactRecord({
contactId : newId,
contactFirstName : 'Name',
phoneNo : '',
phone2 : '',
phone3 : '',
faxNo : '',
email : '',
website : '',
isPrimary : false,
notes : '',
supplierId : cmbSupplier.getValue(),
isActive : true,
outletId : -1
}, newId);
grid_ContactBySuppliers.stopEditing();
grid_ContactBySuppliers.getStore().insert(0, aNewRecord);
grid_ContactBySuppliers.getStore().getById(newId).set('contactFirstName', '');
}
}),
'-',
new Ext.Button({
iconCls: 'icon-delete', scale : 'large',
text: 'Delete',
id : 'btn_Delete_Contact' + identifier,
//disabled: true,
handler: function () {
var selectedItems = grid_ContactBySuppliers.getSelectionModel().getSelections();
if (selectedItems.length > 0)
{
Ext.Msg.show({
title:'Confirm',
msg: 'Are you sure you want to delete the contact(s) ?',
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.QUESTION,
fn : function(btn) {
if (btn == "yes") {
for (var i = 0, row; row = selectedItems[i]; i++) {
row.set('isActive', false);
}
}
}
});
}
else {
Ext.Msg.show({
title:'Notice',
msg: 'Please select contact(s) to delete!',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
}// End if
}
}),
'-',
{
text: 'Refresh',
iconCls: 'icon-refresh-large', scale : 'large',
handler: function (button, event) {
cmbSupplier.getStore().reload();
grid_ContactBySuppliers.getStore().commitChanges();
grid_ContactBySuppliers.getStore().reload();
}
},
'-',
' Choose supplier : ',
cmbSupplier,
'-',
{
xtype : 'button',
iconCls : 'icon-search-large', scale : 'large',
id : 'btn_Dialog_ContactBySupplier_SearchContact' + identifier,
text : 'Search',
handler : function(){
var searchValue = txt_ContactBySupplier_SearchContactValue.getValue();
if (searchValue == "")
{
Ext.Msg.show({
title:'Notice',
msg: 'Please enter value you want to search!',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
}
else {
grid_ContactBySuppliers.getStore().baseParams = {keyword : searchValue, supplierId : cmbSupplier.getValue(), start : 0, limit : Global_ContactBrowser_PageSize};
grid_ContactBySuppliers.getStore().load();
}
}
},
txt_ContactBySupplier_SearchContactValue = new Ext.form.TextField({
id : 'txt_ContactBySupplier_SearchContactValue' + identifier,
emptyText : 'Name ...',
listeners: {
specialkey: function(f,e){
if (e.getKey() == e.ENTER) {
Ext.getCmp("btn_Dialog_ContactBySupplier_SearchContact" + identifier).handler.call(Ext.getCmp("btn_Dialog_ContactBySupplier_SearchContact" + identifier).scope);
}
}
}
}),
{
xtype : 'button',
id : 'btn_ContactBySupplier_StopSearch' + identifier,
iconCls : 'icon-stop-search',
handler : function(){
cmbSupplier.reset();
grid_ContactBySuppliers.getStore().baseParams = {supplierId : -1, start : 0, limit : Global_ContactBrowser_PageSize};
grid_ContactBySuppliers.getStore().load();
}
}
],
cm: contactCM,
sm : contactSm,
autoHeight: false,
clicksToEdit: 1,
loadMask: true,
bbar: new Ext.CTBPagingToolbar({
store: contactBySupplier_Store,
pageSize: Global_ContactBrowser_PageSize,
id: 'pt_ContactBrowser_ContactBySupplier' + identifier,
displayInfo: true,
emptyMsg: "No contacts to display"
}),
viewConfig:
{
enableRowBody: true,
forceFit: true // IMPORTANT (USE THIS ATTRIBUTE TO USE PERCENTAGE IN COLUMN MODEL)
}
});
// var wrapPanel = new Ext.Panel({
// layout : 'border',
// region : 'center',
// id : 'pnl_ContactBySuppliers' + identifier,
// autoScroll: true,
// items : [grid_ContactBySuppliers],
// listeners : {
// 'afterrender' : function(){
// // Do nothing
// }
// }
// });
return grid_ContactBySuppliers;
}
// Get combobox supplier
function getCombobox_ContactSupplier(identifier)
{
if (identifier == null) identifier = "";
var cmbSupplier = new Ext.form.ComboBox({
store: Global_Supplier_Store,
id : 'cmb_ContactBrowser_Supplier' + identifier,
displayField: 'supName',
valueField: 'supId',
typeAhead: true,
mode : 'remote',
listeners : {
beforequery: function(qe){
delete qe.combo.lastQuery; // Reload every click
}
},
triggerAction: 'all',
lazyRender: true,
forceSelection: true,
emptyText: 'Select a Supplier...',
width: 200,
style: { fontSize: '11px' }
});
return cmbSupplier;
}
var MAIN_TAB_MARGINS_CONFIG = '155 0 0 0';
var DISPLAY_LOGIN_FORM_WHEN_SESSION_OUT = true;
Ext.onReady(function () {
/*var StockBrowserDialog = new Ext.CTBStockBrowser({
id : 'dlg_StockBrowser'
});*/
// -------------------------------------------------------------------------------
// ALL TABS WRAPPER
// -------------------------------------------------------------------------------
// Tab wrapper
var allTabs = new Ext.TabPanel({
region:'center',
activeTab: 0,
activeTabIndex: 0,
border : false,
//margins: '115 5 0 5',
//margins: '228 0 0 0',
margins: MAIN_TAB_MARGINS_CONFIG,
plain:true,
id: 'tab_XeroSection',
headerCfg : {
cls : 'tab_XeroSection'
},
defaults:{autoScroll: true},
items:[{
title: 'Order',
id : 'pnl_Invoice',
layout: 'fit'
},{
title: 'Recipe Menu',
id: 'pnl_RecipeMenu',
layout: 'fit'
},{
title: 'Revenue',
id : 'pnl_Revenue',
layout: 'fit'
},{
title: 'Supplier',
id : 'pnl_Supplier',
layout: 'fit'
},{
title: 'Inventory',
layout: 'fit',
id : 'pnl_StockMaintenance'
},{
title: 'Report',
id : 'pnl_ReportXero',
layout: 'fit'
}
],
listeners : {
tabchange : function(p_This, p_Tab){
if (p_Tab.getId() == "pnl_Invoice"){
setVideoHelp('uchF0kq64tM', 'Invoice');
}
else if (p_Tab.getId() == "pnl_StockMaintenance") {
setVideoHelp('HdoPvaMuxA0', 'Stock Maintenance');
}
else if (p_Tab.getId() == "pnl_ReportXero"){
setVideoHelp(C_RECIPEBOOK_VIDEO_ID, C_RECIPEBOOK_VIDEO_DESC);
}
}
}
});
new Ext.Viewport({
layout : 'border',
id : 'div_layout',
items: [allTabs],
cls : 'viewPortBody',
renderTo: "div_layout"
});
}); // End Ext.Ready
function hideAllMainTabs(activeTab)
{
Ext.getCmp('tab_XeroSection').hideTabStripItem(Ext.getCmp('pnl_Invoice'));
Ext.getCmp('tab_XeroSection').hideTabStripItem(Ext.getCmp('pnl_ReportXero'));
Ext.getCmp('tab_XeroSection').hideTabStripItem(Ext.getCmp('pnl_StockMaintenance'));
if (activeTab != null)
{
Ext.getCmp('tab_XeroSection').unhideTabStripItem(activeTab);
Ext.getCmp('tab_XeroSection').setActiveTab(activeTab);
}
}
function unhideAllMainTabs(beHiddenTab, focusTab)
{
Ext.getCmp('tab_XeroSection').unhideTabStripItem(Ext.getCmp('pnl_Invoice'));
Ext.getCmp('tab_XeroSection').unhideTabStripItem(Ext.getCmp('pnl_ReportXero'));
Ext.getCmp('tab_XeroSection').unhideTabStripItem(Ext.getCmp('pnl_StockMaintenance'));
if (beHiddenTab != null)
{
Ext.getCmp('tab_XeroSection').hideTabStripItem(beHiddenTab);
}
if (focusTab != null)
{
Ext.getCmp('tab_XeroSection').setActiveTab(focusTab);
}
}
Ext.CTBMYOBSelectCompanyFilesGrid = Ext.extend(Ext.Panel, {
layout : 'border',
loadMask: null,
pageSize: CTB.init.itemPerPage || 100,
recordObject : null,
instructionText : 'Select the company file you want to connect to',
instructionBackgroundColor : '#66c010',
callback_ContinueButtonClick : null,
dlg_Parent : null,
listeners : {
afterrender : function(theThis){
// Init loadMask
theThis.loadMask = new Ext.LoadMask(this.getEl(), {msg:"Please wait..."});
},
show : function(theThis){
}
},
initComponent: function(){
var theThis = this;
theThis.tpl_Instruction = new Ext.XTemplate(
'
',
'',
'
',
'',
'',
'{instructionText} ',
' ',
' ',
'
',
'
',
' '
);
theThis.pnl_Instruction = new Ext.Panel({
frame : true,
region : 'north',
height : 70,
tpl : theThis.tpl_Instruction,
listeners : {
afterrender : function(p_This){
p_This.update({instructionBackgroundColor : theThis.instructionBackgroundColor, instructionText : theThis.instructionText});
}
}
});
theThis.grid_CompanyFiles = theThis.getGrid_CompanyFiles();
theThis.items = [theThis.grid_CompanyFiles, theThis.pnl_Instruction];
// Call super class to initialize componenets
Ext.CTBMYOBSelectCompanyFilesGrid.superclass.initComponent.call(this);
},
clearSelections : function(){
var theThis = this;
theThis.getGrid().getSelectionModel().clearSelections();
},
getGrid: function(){
var theThis = this;
return theThis.grid_CompanyFiles;
},
getPagingToolbar: function(){
var theThis = this;
return theThis.pt_CompanyFile;
},
getSelectedRecords: function(){
var theThis = this;
return theThis.getGrid().getSelectionModel().getSelections();
},
loadData: function(){
var theThis = this;
theThis.getGrid().getStore().commitChanges();
theThis.getGrid().getStore().baseParams = {start : 0, limit : theThis.getPagingToolbar().pageSize};
theThis.getGrid().getStore().load();
},
getGrid_CompanyFiles: function(){
var theThis = this;
// shorthand alias
var fm = Ext.form;
// ***************************************************************************************************
// Data Fields
// ***************************************************************************************************
theThis.companyFileRecord = Ext.data.Record.create([
{ name: 'Id' , type: 'string' },
{ name: 'LibraryPath' , type: 'string' },
{ name: 'Name' , type: 'string' },
{ name: 'ProductVersion' , type: 'string' },
{ name: 'Uri' , type: 'string' }
]);
// ***************************************************************************************************
// Stores
// ***************************************************************************************************
theThis.store_CompanyFile = new Ext.data.GroupingStore({
proxy: new Ext.data.HttpProxy({
url: '/Kounta/GetCompanyFiles',
dataType: 'json',
method: 'POST'
}),
reader: new Ext.data.JsonReader({
fields: theThis.companyFileRecord,
root: 'data',
idProperty: 'Id',
totalProperty : 'totalCount'
}),
autoLoad : false,
groupField : 'ProductVersion',
listeners : {
'load' : function(){
},
'loadexception' : function(){
showStoreLoadingErrorMessage(theThis.store_CompanyFile, function(){
CheckMYOBConnection(function(){
ShowSelectCompanyFilesDialog();
});
});
}
}
//})
});
// ***************************************************************************************************
// Grid
// ***************************************************************************************************
//-------------------------------------------------------------------
// Selection model
//-------------------------------------------------------------------
var sm = new Ext.grid.CheckboxSelectionModel({
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
// Do nothing at the moment
}
}
});
var companyFileSm = new Ext.grid.CheckboxSelectionModel({
singleSelect : true,
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
}
}
});
// Column Models
var stockCM = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults: {
sortable: true // columns are not sortable by default
},
columns: [ companyFileSm,
{ header: 'Id', dataIndex: 'Id', width: 25 },
//{ header: 'LibraryPath', dataIndex: 'LibraryPath', width: 25 },
{ header: 'Name', dataIndex: 'Name', width: 75 },
{ header: 'ProductVersion', dataIndex: 'ProductVersion', hidden : true },
//{ header: 'Uri', dataIndex: 'Uri', width: 25 }
]
});
// Context menu for right clicking
var contextMenu = new Ext.menu.Menu({
items:
[
{
iconCls: 'icon-add', scale : 'large',
text: 'New',
handler: function () {
theThis.btn_Add_CompanyFile.handler.call(theThis.btn_Add_CompanyFile.scope);
}
},
{
iconCls: 'icon-delete', scale : 'large',
text: 'Delete',
handler: function () {
theThis.btn_Delete_CompanyFile.handler.call(theThis.btn_Delete_CompanyFile.scope);
}
},
{
iconCls: 'icon-recipe',
text: 'View detail',
handler: function () {
if (theThis.selectedCompanyFileId != -1){
theThis.dlg_CompanyFileDetail.show();
}
}
}
]
});
/********************************************************************************************/
/****************************/
/* Searching Stock Combobox */
/****************************/
var data_SearchType = [
['By CompanyFile Code', 1],
['By CompanyFile Name' , 2]
];
var cmb_SearchCompanyFile = new Ext.form.ComboBox({
store: new Ext.data.ArrayStore({
fields: [
{name: 'searchTypeDesc'},
{name: 'searchType', type: 'int'}
]
}),
editable: false,
displayField: 'searchTypeDesc',
valueField: 'searchType',
typeAhead: true,
triggerAction: 'all',
lazyRender: true,
mode: 'local',
emptyText: 'Choose search by ...'
});
// CompanyFile grid
var grid_CompanyFile = new Ext.grid.EditorGridPanel({
store : theThis.store_CompanyFile,
frame : true,
region : 'center',
sm : companyFileSm,
/*buttons : [
theThis.btn_Continue = new Ext.Button({
text: 'Continue',
iconCls : 'icon-ok-large', scale : 'large',
handler : function(){
var selectedRecords = theThis.getGrid().getSelectionModel().getSelections();
if (selectedRecords.length == 0) {
showErrorNotification('Notice', 'You need to select one companyFile.');
}
else {
var selectedCompanyFileCode = selectedRecords[0].data.Code;
if (theThis.callback_ContinueButtonClick != null) theThis.callback_ContinueButtonClick(selectedCompanyFileCode);
}
}
}),
theThis.btn_Cancel = new Ext.Button({
text: 'Cancel',
iconCls : 'icon-cancel-large', scale : 'large',
handler : function(){
if (theThis.dlg_Parent != null) theThis.dlg_Parent.hide();
}
})
],*/
listeners : {
rowclick : function ( p_this, p_rowIndex, p_eventObject ) {
// Hightlight the selected row
var selectedRow = p_this.getView().getRow(p_rowIndex);
Ext.get(selectedRow).highlight();
},
rowdblclick : function ( p_this, p_rowIndex, p_eventObject ) {
},
afterrender : function(){
/*theThis.store_CompanyFile.baseParams = {keyword: "", start: 0, limit: theThis.pageSize},
theThis.store_CompanyFile.load();*/
}
},
cm: stockCM,
width: 780,
height: 400,
autoHeight: false,
clicksToEdit: 1,
loadMask: true,
bbar:
theThis.pt_CompanyFile = new Ext.CTBPagingToolbar({
store: theThis.store_CompanyFile,
pageSize: theThis.pageSize,
displayInfo: true,
emptyMsg: "No company files to display"
}),
view: new Ext.grid.GroupingView({
forceFit: true, // IMPORTANT (USE THIS ATTRIBUTE TO USE PERCENTAGE IN COLUMN MODEL)
groupTextTpl: '
{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})
'
})
/*viewConfig:
{
enableRowBody: true,
forceFit: true // IMPORTANT (USE THIS ATTRIBUTE TO USE PERCENTAGE IN COLUMN MODEL)
}*/
});
grid_CompanyFile.on({
rowcontextmenu: function (grid, rowIndex, e) {
e.stopEvent();
var row = grid.getView().getRow(rowIndex);
Ext.get(row).highlight();
companyFileSm.selectRow(rowIndex);
contextMenu.showAt(e.getXY());
}
});
return grid_CompanyFile;
} // End generateGrid_Databases
});
Ext.reg('CTBMYOBSelectCompanyFilesGrid', Ext.CTBMYOBSelectCompanyFilesGrid);
Ext.CTBMYOBSelectCompanyFilesWindow = Ext.extend(Ext.Window, {
title: 'Kounta Company Files',
layout: 'border',
closeAction: 'hide',
iconCls : 'icon-v3-ctb-logo',
cls : 'ctbwindow-detail-general',
expandOnShow: true,
closable: true,
resizable: true,
modal: true,
plain: true,
minimizable: true,
maximizable: true,
monitorResize: true,
width: 500,
height: 300,
activeItem : 0,
defaults: {
split: true,
animFloat: false,
autoHide: false,
useSplitTips: true
},
pageSize: CTB.init.itemPerPage || 100,
accountCode : '',
selectedInvoiceRecords : null,
selectedCompanyFileID : null,
callback_AfterSelect : null,
setSelectedInvoiceRecords : function(selectedInvoiceRecords){
var theThis = this;
theThis.selectedInvoiceRecords = selectedInvoiceRecords;
},
listeners: {
scope : this,
'beforehide': function(theThis){
},
'beforeshow': function(theThis){
// Fit this window to the client browser screen with 90%
fitWindowSize(theThis, 80);
},
'show': function(theThis){
theThis.grid_MYOBCompanyFiles.loadData();
}
},
initComponent : function(){
var theThis = this;
theThis.grid_MYOBCompanyFiles = new Ext.CTBMYOBSelectCompanyFilesGrid({
dlg_Parent : theThis,
region : 'center'
});
theThis.items = [theThis.grid_MYOBCompanyFiles];
// BUTTONS
var myButtons = theThis.initButtons();
this.buttons = myButtons;
this.initTools();
Ext.CTBMYOBSelectCompanyFilesWindow.superclass.initComponent.call(this);
},
initButtons : function(){
var theThis = this;
var buttons = [
theThis.btn_Select = new Ext.Button({
text: 'Select',
iconCls : 'icon-cancel-large', scale : 'large',
cls : 'ctb-btn-red',
handler : function(){
var selectedRecords = theThis.grid_MYOBCompanyFiles.getGrid().getSelectionModel().getSelections();
if (selectedRecords != null && selectedRecords.length > 0){
var theRecord = theThis.grid_MYOBCompanyFiles.getGrid().getSelectionModel().getSelections()[0];
theThis.selectedCompanyFileID = theRecord.data.Id;
theThis.finalizeMYOBConnectionConfiguration(theThis.selectedCompanyFileID);
/*ShowMYOBLoginForm(theRecord, function(theLoginForm, username, password){
theThis.finalizeMYOBConnectionConfiguration(theLoginForm, username, password);
});*/
}
else {
showErrorNotification('Notice', 'Please select at least one company file to work with.');
}
}
}),
theThis.btn_Cancel = new Ext.Button({
text: 'Cancel',
iconCls : 'icon-cancel-large', scale : 'large',
handler : function(){
theThis.hide();
}
})
];
return buttons;
},
finalizeMYOBConnectionConfiguration : function(selectedCompanyFileID){
var theThis = this;
theThis.grid_MYOBCompanyFiles.loadMask.show();
Ext.Ajax.request({
method: "POST",
url: '/Kounta/FinalizeMYOBConnectionConfiguration',
params:
{
companyFileID : theThis.selectedCompanyFileID
},
success : function(result, request) {
theThis.grid_MYOBCompanyFiles.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
theThis.hide();
if (theThis.callback_AfterSelect != null) {
theThis.callback_AfterSelect();
}
else {
window.location = window.location; // Refresh the page
}
}
else {
//showErrorMessageWithEmailNotify(jsonData.message.Info);
showErrorNotification('Notice', jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.grid_MYOBCompanyFiles.loadMask.hide();
}
}); // End ajax
}
});
Ext.reg('CTBMYOBSelectCompanyFilesWindow', Ext.CTBMYOBSelectCompanyFilesWindow);
Ext.CTBKountaSelectSiteWindow = Ext.extend(Ext.Component, {
onLoadCallback: null,
preloadData: null,
initComponent: function() {
Ext.CTBKountaSelectSiteWindow.superclass.initComponent.call(this);
var theThis = this;
theThis.siteStore = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy(
new Ext.data.Connection({
url: '/Kounta/GetSites',
dataType: 'json',
method: 'POST'
})
),
autoLoad: false,
fields: [
{ name: 'id', type: 'number' },
{ name: 'name', type: 'string' }
],
root: 'data',
idProperty: 'id',
totalProperty: 'totalCount',
listeners: {
'load': function (store, records, options) {
theThis.loadMask.hide();
//console.log(p_This);
if(typeof(theThis.onLoadCallback) === 'function') theThis.onLoadCallback(store);
},
'exception': function (store, type, action, options, response, arg) {
theThis.loadMask.hide();
showErrorNotification('Error', 'Failed to load site information from Kounta. Message: ' + response.responseText);
}
}
});
theThis.loadMask = new Ext.LoadMask(Ext.getBody(), { msg: "Please wait..." });
},
setPreloadData: function(data)
{
var theThis = this;
theThis.preloadData = data;
},
clearPreloadData: function()
{
var theThis = this;
theThis.preloadData = null;
},
showSelectSiteWindow: function(onSelectedCallback) {
//Ext.Msg.alert('Select Site', 'Please select a site');
var theThis = this;
if(theThis.selectSiteWindow) {
theThis.selectSiteWindow.show();
return;
}
var onSelectSiteRequest = function(store) {
//console.log('on callback');
if(!store || store.getCount() == 0) {
showErrorNotification('Notification', 'Cannot find site information from Kounta.');
return;
}
if (store.getCount() == 1) { //call the callback function directly
var data = store.getAt(0).data;
if (typeof (onSelectedCallback) === 'function') onSelectedCallback(data.id, data.name);
}
else {
theThis.selectSiteWindow = theThis.getSelectSiteWindow(store, onSelectedCallback);
theThis.selectSiteWindow.show();
}
};
//if there is data in the store
if(theThis.siteStore.getCount() > 0) {
onSelectSiteRequest(theThis.siteStore);
}
else {
theThis.onLoadCallback = onSelectSiteRequest;
theThis.loadMask.show();
theThis.siteStore.load();
}
},
getSelectSiteWindow: function(store, onSelectedCallback) {
/*
var sm = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
var cm = new Ext.grid.ColumnModel({
columns: [
sm,
{ header: 'id', dataIndex: 'id', hidden: true},
{ header: 'name', dataIndex: 'name' }
]
});
var grid = new Ext.grid.GridPanel({
store: store,
sm: sm,
cm: cm,
viewConfig: { forceFit: true}
});
*/
var combo = new Ext.form.ComboBox({
store: store,
fieldLabel: 'Kounta Site',
displayField: 'name',
valueField: 'id',
mode : 'local',
editable : false,
allowBlank : false,
emptyText : 'Select a site in Kounta',
//typeAhead: true,
triggerAction: 'all',
lazyRender: true,
width : 200
});
var win = new Ext.Window({
title: 'Select a Site',
iconCls : 'icon-v3-ctb-logo',
cls : 'ctbwindow-detail-general',
width: 390,
height: 150,
modal: true,
items: combo,
layout: 'form',
buttons: [
{
text: 'Select',
handler: function() {
var siteId = combo.getValue();
var siteName = combo.getRawValue();
if(siteId) {
win.hide();
if(typeof(onSelectedCallback)==='function') onSelectedCallback(siteId, siteName);
}
else {
showErrorNotification('Error', 'Please select a site to continue.');
}
}
},
{
text: 'Cancel',
handler: function() {
win.hide();
}
}
],
});
return win;
},
showSelectCategoryWindow: function(onSelectedCallback) {
//Ext.Msg.alert('Select Site', 'Please select a site');
var theThis = this;
if(theThis.selectCategoryWindow) {
theThis.selectCategoryWindow.show();
return;
}
var onSelectCategoryRequest = function(store) {
//console.log('on callback');
if(!store || store.getCount() == 0) {
showErrorNotification('Notification', 'Cannot find site information from Kounta.');
return;
}
theThis.selectCategoryWindow = theThis.getSelectCategoryWindow(store, onSelectedCallback);
theThis.selectCategoryWindow.show();
};
//if there is data in the store
if(theThis.siteStore.getCount() > 0) {
onSelectCategoryRequest(theThis.siteStore);
}
else {
theThis.onLoadCallback = onSelectCategoryRequest;
theThis.loadMask.show();
theThis.siteStore.load();
}
},
getSelectCategoryWindow: function(store, onSelectedCallback) {
var theThis = this;
var cateStore = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy(
new Ext.data.Connection({
url: '/Kounta/GetCategoriesBySite',
dataType: 'json',
method: 'POST'
})
),
autoLoad: false,
fields: [
{ name: 'id', type: 'number' },
{ name: 'name', type: 'string' }
],
root: 'data',
idProperty: 'id',
totalProperty: 'totalCount',
listeners: {
'load': function (cateStore, records, options) {
var data = theThis.preloadData;
if(data != null)
{
var categories = data.categories;
for (var i = 0; i < categories.length; i++){
var rec = theThis.categoryGrid.store.getById(categories[i].id);
if(rec != null)
{
theThis.categoryGrid.getSelectionModel().selectRecords([rec], true);
}
}
}
},
'exception': function (store, type, action, options, response, arg) {
theThis.loadMask.hide();
showErrorNotification('Error', 'Failed to load category information from Kounta. Message: ' + response.responseText);
}
}
});
var sm = new Ext.grid.CheckboxSelectionModel({singleSelect:false});
var cm = new Ext.grid.ColumnModel({
columns: [
sm,
{ header: 'id', dataIndex: 'id', hidden: true},
{ header: 'name', dataIndex: 'name' }
]
});
theThis.categoryGrid = new Ext.grid.GridPanel({
region: 'center',
store: cateStore,
sm: sm,
cm: cm,
viewConfig: { forceFit: true},
stripeRows: true
});
var checkFilter = new Ext.form.Checkbox({
boxLabel: 'Filter by Categories',
checked: false,
listeners: {
check: function(checkbox, checked) {
if(checked) {
var siteId = comboSite.getValue();
if(siteId > 0) {
cateStore.setBaseParam('siteId', siteId);
cateStore.load();
}
}
else {
cateStore.removeAll();
}
}
}
});
var comboSite = new Ext.form.ComboBox({
store: store,
//fieldLabel: 'Kounta Site',
displayField: 'name',
valueField: 'id',
mode : 'local',
editable : false,
allowBlank : false,
emptyText : 'Select a site in Kounta',
//typeAhead: true,
triggerAction: 'all',
lazyRender: true,
width : 200,
height:30,
listeners: {
select: function(combo, record, index) {
//console.log(record.data);
sm.clearSelections();
theThis.preloadData = null;
if(checkFilter.getValue()==true) {
cateStore.setBaseParam('siteId', record.id);
cateStore.load();
}
}
}
});
var topPanel = new Ext.Panel({
region: 'north',
layout: 'hbox',
height: 40,
style: 'margin-top:10px',
items: [
{
xtype: 'label',
text: 'Select a Site: in Kounta:',
width: 160,
style: 'text-align:right'
},
comboSite,
{
xtype: 'label',
text: ' ',
width: 100,
style: 'text-align:right'
},
checkFilter
]
});
var win = new Ext.Window({
title: 'Select Categories',
iconCls : 'icon-v3-ctb-logo',
cls : 'ctbwindow-detail-general',
width: 600,
height: 400,
modal: true,
items: [topPanel, theThis.categoryGrid],
layout: 'border',
listeners: {
'beforeshow': function(pThis){
// Fit this window to the client browser screen with 90%
fitWindowSize(pThis, 80);
},
'show': function(){
var data = theThis.preloadData;
if(data != null)
{
if(data.categories != null)
{
checkFilter.setValue(1);
}
comboSite.setValue(data.siteId);
cateStore.setBaseParam('siteId', data.siteId);
cateStore.load();
}
}
},
buttons: [
{
text: 'Select',
handler: function() {
var siteId = comboSite.getValue();
var siteName = comboSite.getRawValue();
var selectedCategories = [];
if(checkFilter.getValue() == true) {
var selections = sm.getSelections();
if(selections != null && selections.length > 0) {
for(var i=0; i
',
'',
''
);
theThis.pnl_Instruction = new Ext.Panel({
//frame : true,
region : 'north',
height : 70,
tpl : theThis.tpl_Instruction,
listeners : {
afterrender : function(p_This){
if (theThis.instructionText != '') {
p_This.setVisible(true);
p_This.update({instructionBackgroundColor : theThis.instructionBackgroundColor, instructionText : theThis.instructionText});
}
else {
p_This.setVisible(false);
}
}
}
});
theThis.tpl_Main = new Ext.XTemplate(
'',
'',
'',
'',
'',
'{btn1_text}',
' ',
' ',
' ',
'',
'',
'',
'{btn2_text}',
' ',
' ',
' ',
'',
'',
'',
'{btn3_text}',
' ',
' ',
' ',
'
',
' '
);
theThis.pnl_Main = new Ext.Panel({
region : 'center',
tpl : theThis.tpl_Main,
listeners : {
afterrender : function(p_This) {
theThis.pnl_Main.update({
uniqueId : theThis.id,
btn1_text : 'I want to use freight\'s input field of the MYOB invoice to store freight.',
btn2_text : 'I want to use another account for freight.',
btn3_text : 'Oops ! I don\'t know.'
});
Ext.get(theThis.id + '_btn_1').on('click', function(p_This){
theThis.hide();
if (theThis.callback_AfterSelect != null) theThis.callback_AfterSelect(true);
});
Ext.get(theThis.id + '_btn_2').on('click', function(p_This){
theThis.hide();
if (theThis.callback_AfterSelect != null) theThis.callback_AfterSelect(false);
});
Ext.get(theThis.id + '_btn_3').on('click', function(p_This){
theThis.hide();
});
}
}
});
theThis.items = [
theThis.pnl_Instruction,
theThis.pnl_Main
];
// BUTTONS
var myButtons = theThis.initButtons();
this.buttons = myButtons;
this.initTools();
Ext.CTBFreightQuestionWindow.superclass.initComponent.call(this);
},
getRecipeFolderBrowser : function(){
var theThis = this;
var dlg_RecipeFolderBrowser = new Ext.Window({
title : 'Select recipe folder',
frame : true,
layout : 'border',
modal : true,
width : 800,
height : 600,
callback_AfterSelect : null,
getRecipeTreePanel : function(){
return theThis.pnl_RFB_RecipeFolderTree;
},
listeners : {
show : function(p_This){
p_This.getRecipeTreePanel().loadData();
}
},
items : [
theThis.pnl_RFB_Instruction = new Ext.Panel({
html : '',
region : 'north',
height : 30,
html : 'Select where you want to store the selected recipes/folders.
'
}),
theThis.pnl_RFB_RecipeFolderTree = new Ext.CTBRecipeTreePanel({
region : 'center',
HideProcessPendingRecipesButton : true,
HideImportRecipeButton : true,
isAutoLoad : false,
readOnly : true,
showAddFolderButtonInReadOnlyMode : true,
Hide_Tooltip : true
})
],
buttons : [
{
xtype : 'button',
text : 'Select',
iconCls : 'icon-ok-large',
scale : 'large',
handler : function(){
var selectedNode = theThis.pnl_RFB_RecipeFolderTree.recipeTreePanel.selModel.selNode;
if (selectedNode != null){
var selectedNodeId = selectedNode.id;
var nodeId = getNumberIdFromStringId(selectedNodeId);
var nodeType = getPrefixFromStringId(selectedNodeId);
if (nodeType == "folder"){
if (dlg_RecipeFolderBrowser.callback_AfterSelect != null)
{
dlg_RecipeFolderBrowser.hide();
dlg_RecipeFolderBrowser.callback_AfterSelect(nodeId);
}
}
else {
showErrorNotification('Notice', 'Please choose only folder.');
}
}
}
},
{
xtype : 'button',
text : 'Cancel',
iconCls : 'icon-cancel-large',
scale : 'large',
handler : function(){
dlg_RecipeFolderBrowser.hide();
}
}
]
});
return dlg_RecipeFolderBrowser
},
loadData : function(){
var theThis = this;
theThis.pnl_Instruction.update({instructionBackgroundColor : theThis.instructionBackgroundColor, instructionText : theThis.instructionText});
},
initButtons : function(){
var theThis = this;
var buttons = [
];
return buttons;
}
});
Ext.reg('CTBFreightQuestionWindow', Ext.CTBFreightQuestionWindow);
Ext.CTBXeroSelectAccountGrid = Ext.extend(Ext.Panel, {
layout : 'border',
loadMask: null,
pageSize: CTB.init.itemPerPage || 100,
recordObject : null,
instructionText : 'Select the food purchase account that you want the invoices to be assigned to',
instructionBackgroundColor : '#66c010',
callback_ContinueButtonClick : null,
dlg_Parent : null,
listeners : {
afterrender : function(theThis){
// Init loadMask
theThis.loadMask = new Ext.LoadMask(this.getEl(), {msg:"Please wait..."});
},
show : function(theThis){
}
},
initComponent: function(){
var theThis = this;
theThis.tpl_Instruction = new Ext.XTemplate(
'',
'',
'
',
'',
'',
'{instructionText} ',
' ',
' ',
'
',
'
',
' '
);
theThis.pnl_Instruction = new Ext.Panel({
frame : true,
region : 'north',
height : 70,
tpl : theThis.tpl_Instruction,
listeners : {
afterrender : function(p_This){
p_This.update({instructionBackgroundColor : theThis.instructionBackgroundColor, instructionText : theThis.instructionText});
}
}
});
theThis.grid_Accounts = theThis.getGrid_Accounts();
theThis.items = [theThis.grid_Accounts, theThis.pnl_Instruction];
// Call super class to initialize componenets
Ext.CTBXeroSelectAccountGrid.superclass.initComponent.call(this);
},
clearSelections : function(){
var theThis = this;
theThis.getGrid().getSelectionModel().clearSelections();
},
getGrid: function(){
var theThis = this;
return theThis.grid_Accounts;
},
getPagingToolbar: function(){
var theThis = this;
return theThis.pt_Account;
},
getSelectedRecords: function(){
var theThis = this;
return theThis.getGrid().getSelectionModel().getSelections();
},
loadData: function(){
var theThis = this;
theThis.getGrid().getStore().commitChanges();
theThis.getGrid().getStore().baseParams = {start : 0, limit : theThis.getPagingToolbar().pageSize};
theThis.getGrid().getStore().load();
},
getGrid_Accounts: function(){
var theThis = this;
// shorthand alias
var fm = Ext.form;
// ***************************************************************************************************
// Data Fields
// ***************************************************************************************************
theThis.accountRecord = Ext.data.Record.create([
{ name: 'UID' , type: 'string' },
{ name: 'DisplayID' , type: 'string' },
{ name: 'Name' , type: 'string' },
{ name: 'Classification' , type: 'string' },
{ name: 'Type' , type: 'string' },
{ name: 'TaxCode' , type: 'string' },
{ name: 'Description' , type: 'string' },
{ name: 'Number' , type: 'string' }
]);
// ***************************************************************************************************
// Stores
// ***************************************************************************************************
theThis.store_Account = new Ext.data.GroupingStore({
proxy: new Ext.data.HttpProxy(
new Ext.data.Connection({
url: '/Kounta/SearchMYOBAccounts',
dataType: 'json',
method: 'POST',
timeout: 1800000
})
),
reader: new Ext.data.JsonReader({
fields: theThis.accountRecord,
root: 'data',
idProperty: 'UID',
totalProperty : 'totalCount'
}),
autoLoad : false,
groupField : 'Classification',
listeners : {
'load' : function(){
},
'loadexception' : function(){
/*showStoreLoadingErrorMessage(theThis.store_Account, function(){
theThis.dlg_Parent.connectToXero(function(){
theThis.store_Account.load();
});
});*/
showStoreLoadingErrorMessage(theThis.store_Account);
}
}
//})
});
// ***************************************************************************************************
// Grid
// ***************************************************************************************************
//-------------------------------------------------------------------
// Selection model
//-------------------------------------------------------------------
var sm = new Ext.grid.CheckboxSelectionModel({
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
// Do nothing at the moment
}
}
});
var accountSm = new Ext.grid.CheckboxSelectionModel({
singleSelect : true,
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
}
}
});
// Column Models
var stockCM = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults: {
sortable: true // columns are not sortable by default
},
columns: [ accountSm,
{ header: 'Classification', dataIndex: 'Classification', hidden: true },
{ header: 'UID', dataIndex: 'UID', hidden: true },
{ header: 'DisplayID', dataIndex: 'DisplayID', width: 10 },
{ header: 'Name', dataIndex: 'Name', width: 30 },
{ header: 'Description', dataIndex: 'Description', width: 60 }
]
});
// Context menu for right clicking
var contextMenu = new Ext.menu.Menu({
items:
[
{
iconCls: 'icon-add', scale : 'large',
text: 'New',
handler: function () {
theThis.btn_Add_Account.handler.call(theThis.btn_Add_Account.scope);
}
},
{
iconCls: 'icon-delete', scale : 'large',
text: 'Delete',
handler: function () {
theThis.btn_Delete_Account.handler.call(theThis.btn_Delete_Account.scope);
}
},
{
iconCls: 'icon-recipe',
text: 'View detail',
handler: function () {
if (theThis.selectedAccountId != -1){
theThis.dlg_AccountDetail.show();
}
}
}
]
});
/********************************************************************************************/
/****************************/
/* Searching Stock Combobox */
/****************************/
var data_SearchType = [
['By Account Code', 1],
['By Account Name' , 2]
];
var cmb_SearchAccount = new Ext.form.ComboBox({
store: new Ext.data.ArrayStore({
fields: [
{name: 'searchTypeDesc'},
{name: 'searchType', type: 'int'}
]
}),
editable: false,
displayField: 'searchTypeDesc',
valueField: 'searchType',
typeAhead: true,
triggerAction: 'all',
lazyRender: true,
mode: 'local',
emptyText: 'Choose search by ...'
});
// Account grid
var grid_Account = new Ext.grid.EditorGridPanel({
store : theThis.store_Account,
frame : true,
region : 'center',
sm : accountSm,
buttons : [
theThis.btn_Continue = new Ext.Button({
text: 'Continue',
iconCls : 'icon-ok-large', scale : 'large',
handler : function(){
var selectedRecords = theThis.getGrid().getSelectionModel().getSelections();
if (selectedRecords.length == 0) {
showErrorNotification('Notice', 'You need to select one account.');
}
else {
var selectedAccountCode = selectedRecords[0].data.UID;
if (theThis.callback_ContinueButtonClick != null) theThis.callback_ContinueButtonClick(selectedAccountCode);
}
}
}),
theThis.btn_Cancel = new Ext.Button({
text: 'Cancel',
iconCls : 'icon-cancel-large', scale : 'large',
handler : function(){
if (theThis.dlg_Parent != null) theThis.dlg_Parent.hide();
}
})
],
listeners : {
rowclick : function ( p_this, p_rowIndex, p_eventObject ) {
// Hightlight the selected row
var selectedRow = p_this.getView().getRow(p_rowIndex);
Ext.get(selectedRow).highlight();
},
rowdblclick : function ( p_this, p_rowIndex, p_eventObject ) {
},
afterrender : function(){
/*theThis.store_Account.baseParams = {keyword: "", start: 0, limit: theThis.pageSize},
theThis.store_Account.load();*/
}
},
cm: stockCM,
width: 780,
height: 400,
autoHeight: false,
clicksToEdit: 1,
loadMask: true,
bbar:
theThis.pt_Account = new Ext.CTBPagingToolbar({
store: theThis.store_Account,
pageSize: theThis.pageSize,
displayInfo: true,
emptyMsg: "No accounts to display"
}),
view: new Ext.grid.GroupingView({
forceFit: true, // IMPORTANT (USE THIS ATTRIBUTE TO USE PERCENTAGE IN COLUMN MODEL)
startCollapsed: true,
groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})
'
})
/*viewConfig:
{
enableRowBody: true,
forceFit: true // IMPORTANT (USE THIS ATTRIBUTE TO USE PERCENTAGE IN COLUMN MODEL)
}*/
});
grid_Account.on({
rowcontextmenu: function (grid, rowIndex, e) {
e.stopEvent();
var row = grid.getView().getRow(rowIndex);
Ext.get(row).highlight();
accountSm.selectRow(rowIndex);
//contextMenu.showAt(e.getXY());
}
});
return grid_Account;
} // End generateGrid_Databases
});
Ext.reg('CTBXeroSelectAccountGrid', Ext.CTBXeroSelectAccountGrid);
Ext.CTBXeroNonFoodItemPanel = Ext.extend(Ext.Panel, {
layout : 'border',
loadMask: null,
pageSize: CTB.init.itemPerPage || 100,
recordObject : null,
instructionText : 'There are non-food item(s) in the invoice(s). What do you want us to do with non-food item(s) ?',
instructionBackgroundColor : '#66c010',
callback_ContinueButtonClick : null,
dlg_Parent : null,
nonFoodAccountCode : null,
nonFoodItems : null,
listeners : {
afterrender : function(theThis){
// Init loadMask
theThis.loadMask = new Ext.LoadMask(this.getEl(), {msg:"Please wait..."});
},
show : function(theThis){
theThis.store_MYOBAccounts.load();
}
},
initComponent: function(){
var theThis = this;
theThis.tpl_Instruction = new Ext.XTemplate(
'',
'',
'
',
'',
'',
'{instructionText} ',
' ',
' ',
'
',
'
',
' '
);
theThis.pnl_Instruction = new Ext.Panel({
frame : true,
region : 'north',
height : 70,
tpl : theThis.tpl_Instruction,
listeners : {
afterrender : function(p_This){
p_This.update({instructionBackgroundColor : theThis.instructionBackgroundColor, instructionText : theThis.instructionText});
}
}
});
theThis.cmb_MYOBAccounts = theThis.getComboBoxMYOBAccounts();
theThis.cmb_MYOBAccountsEditor = theThis.getComboBoxMYOBAccounts();
theThis.pnl_Option1 = new Ext.Panel({
layout : 'border',
region : 'north',
height : 80,
items : [
theThis.pnl_Option1FormPanel = new Ext.form.FormPanel({
flex : 1,
frame : true,
labelWidth: 20,
region : 'center',
defaults: {
xtype: 'textfield',
width : 370
},
items : [
theThis.rd_Option1 = new Ext.form.Radio({
boxLabel: 'I want all non-food items go to only one MYOB Account ',
checked : true,
listeners : {
check : function( p_This, checked ) {
if (checked) {
theThis.rd_Option2.setValue(false);
theThis.cmb_MYOBAccounts.enable();
theThis.grid_NonFoodItem.disable();
}
}
}
}),
theThis.cmb_MYOBAccounts
]
})
]
});
theThis.grid_NonFoodItem = theThis.getGrid_NonFoodItem();
theThis.pnl_Option2 = new Ext.Panel({
layout : 'border',
region : 'center',
items : [
new Ext.form.FormPanel({
flex : 1,
frame : true,
labelWidth: 20,
region : 'north',
height : 30,
defaults: {
xtype: 'textfield',
width : 390
},
items : [
theThis.rd_Option2 = new Ext.form.Radio({
boxLabel: 'I want each non-food item go to different MYOB Accounts ',
checked : false,
listeners : {
check : function( p_This, checked ) {
if (checked) {
theThis.rd_Option1.setValue(false);
theThis.cmb_MYOBAccounts.disable();
theThis.grid_NonFoodItem.enable();
}
}
}
})
]
}),
theThis.grid_NonFoodItem
]
});
theThis.pnl_Main = new Ext.Panel({
layout : 'border',
region : 'center',
items : [
theThis.pnl_Option1, theThis.pnl_Option2
],
buttons : [
theThis.btn_Continue = new Ext.Button({
text: 'Continue',
iconCls : 'icon-ok-large', scale : 'large',
handler : function(){
if (theThis.rd_Option2.getValue() == true) {
var isPassed = true;
for(var i = 0; i < theThis.store_NonFoodItem.getCount(); i++){
if (theThis.store_NonFoodItem.getAt(i).data.NonFoodAccountCode == null || theThis.store_NonFoodItem.getAt(i).data.NonFoodAccountCode == "") {
isPassed = false;
break;
}
}
if (!isPassed) {
showErrorNotification('Notice', 'You need to select all corresponding non-food accounts.');
}
else {
var MYOBNonFoodStockAccounts = new Array();
for (var i = 0; i < theThis.store_NonFoodItem.getCount(); i++) {
MYOBNonFoodStockAccounts[i] = {
CTBStockId : theThis.store_NonFoodItem.getAt(i).data.CTBStockId,
NonFoodAccountCode : theThis.store_NonFoodItem.getAt(i).data.NonFoodAccountCode
}
}
function saveNow() {
theThis.loadMask.show();
Ext.Ajax.request({
method: 'POST',
url: '/Kounta/SaveMYOBNonFoodStockAccount',
params:
{
MYOBNonFoodStockAccounts : Ext.util.JSON.encode(MYOBNonFoodStockAccounts)
},
success : function(result, request) {
theThis.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
if (theThis.callback_ContinueButtonClick != null) theThis.callback_ContinueButtonClick(false, null);
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.loadMask.hide();
}
}); // End ajax
}
saveNow();
}
}
else {
theThis.nonFoodAccountCode = theThis.cmb_MYOBAccounts.getValue();
if (theThis.nonFoodAccountCode == null || theThis.nonFoodAccountCode == "") {
showErrorNotification('Notice', 'You need to select a non-food account');
}
else if (theThis.callback_ContinueButtonClick != null) theThis.callback_ContinueButtonClick(true, theThis.nonFoodAccountCode);
}
}
}),
theThis.btn_Cancel = new Ext.Button({
text: 'Cancel',
iconCls : 'icon-cancel-large', scale : 'large',
handler : function(){
if (theThis.dlg_Parent != null) theThis.dlg_Parent.hide();
}
})
]
})
theThis.items = [theThis.pnl_Instruction, theThis.pnl_Main];
// Call super class to initialize componenets
Ext.CTBXeroNonFoodItemPanel.superclass.initComponent.call(this);
},
clearSelections : function(){
var theThis = this;
theThis.getGrid().getSelectionModel().clearSelections();
},
getGrid: function(){
var theThis = this;
return theThis.grid_NonFoodItem;
},
getPagingToolbar: function(){
var theThis = this;
return theThis.pt_NonFoodItem;
},
getSelectedRecords: function(){
var theThis = this;
return theThis.getGrid().getSelectionModel().getSelections();
},
loadData: function(selectedInvoiceRecords){
var theThis = this;
var selectedInvoiceIds = new Array();
for (var i = 0; i < selectedInvoiceRecords.length; i++) {
selectedInvoiceIds[i] = selectedInvoiceRecords[i].data.invoiceId;
}
theThis.getGrid().getStore().commitChanges();
theThis.getGrid().getStore().baseParams = {start : 0, limit : theThis.pageSize, CTBInvoiceIds : Ext.util.JSON.encode(selectedInvoiceIds)};
theThis.getGrid().getStore().load();
},
getGrid_NonFoodItem: function(){
var theThis = this;
// shorthand alias
var fm = Ext.form;
// ***************************************************************************************************
// Data Fields
// ***************************************************************************************************
theThis.nonFoodItemRecord = Ext.data.Record.create([
{ name: 'CTBStockId' , type: 'string' },
{ name: 'Description' , type: 'string' },
{ name: 'NonFoodAccountCode' , type: 'string' }
]);
// ***************************************************************************************************
// Stores
// ***************************************************************************************************
theThis.store_NonFoodItem = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy(
new Ext.data.Connection({
url: '/Kounta/SearchNonFoodItemMYOBAccountLinks',
dataType: 'json',
method: 'POST',
timeout: 1800000
})
),
autoLoad : false,
fields: theThis.nonFoodItemRecord,
root: 'data',
idProperty: 'CTBStockId',
totalProperty : 'totalCount',
listeners : {
'load' : function(){
},
'loadexception' : function(){
/*showStoreLoadingErrorMessage(theThis.store_NonFoodItem, function(){
theThis.dlg_Parent.connectToXero(function(){
theThis.store_NonFoodItem.load();
});
});*/
showStoreLoadingErrorMessage(theThis.store_NonFoodItem);
}
}
//})
});
// ***************************************************************************************************
// Grid
// ***************************************************************************************************
//-------------------------------------------------------------------
// Selection model
//-------------------------------------------------------------------
var sm = new Ext.grid.CheckboxSelectionModel({
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
// Do nothing at the moment
}
}
});
var accountSm = new Ext.grid.CheckboxSelectionModel({
singleSelect : true,
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
}
}
});
// Column Models
var stockCM = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults: {
sortable: true // columns are not sortable by default
},
columns: [ accountSm,
{ header: 'CTBStockId', dataIndex: 'CTBStockId', hidden: true },
{ header: 'Non Food Item Name/Description', dataIndex: 'Description', width: 50 },
{ header: 'MYOB Account', dataIndex: 'NonFoodAccountCode', width: 50,
renderer: Ext.util.Format.comboRenderer(theThis.cmb_MYOBAccountsEditor),
editor : theThis.cmb_MYOBAccountsEditor
}
]
});
// Account grid
var grid_NonFoodItem = new Ext.grid.EditorGridPanel({
store : theThis.store_NonFoodItem,
frame : true,
region : 'center',
sm : accountSm,
disabled : true,
listeners : {
rowclick : function ( p_this, p_rowIndex, p_eventObject ) {
// Hightlight the selected row
var selectedRow = p_this.getView().getRow(p_rowIndex);
Ext.get(selectedRow).highlight();
},
rowdblclick : function ( p_this, p_rowIndex, p_eventObject ) {
},
afterrender : function(){
/*theThis.store_NonFoodItem.baseParams = {keyword: "", start: 0, limit: theThis.pageSize},
theThis.store_NonFoodItem.load();*/
}
},
cm: stockCM,
width: 780,
height: 400,
autoHeight: false,
clicksToEdit: 1,
loadMask: true,
/*bbar:
theThis.pt_NonFoodItem = new Ext.CTBPagingToolbar({
store: theThis.store_NonFoodItem,
pageSize: theThis.pageSize,
displayInfo: true,
emptyMsg: "No accounts to display"
}),*/
/*view: new Ext.grid.GroupingView({
forceFit: true, // IMPORTANT (USE THIS ATTRIBUTE TO USE PERCENTAGE IN COLUMN MODEL)
startCollapsed: true,
groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})
'
})*/
viewConfig:
{
enableRowBody: true,
forceFit: true // IMPORTANT (USE THIS ATTRIBUTE TO USE PERCENTAGE IN COLUMN MODEL)
}
});
grid_NonFoodItem.on({
rowcontextmenu: function (grid, rowIndex, e) {
e.stopEvent();
var row = grid.getView().getRow(rowIndex);
Ext.get(row).highlight();
accountSm.selectRow(rowIndex);
}
});
return grid_NonFoodItem;
}, // End generateGrid_Databases
getComboBoxMYOBAccounts : function(){
var theThis = this;
// Business Departments store
if (theThis.store_MYOBAccounts == null) {
var accountRecord = Ext.data.Record.create([
{ name: 'UID' , type: 'string' },
{ name: 'DisplayID' , type: 'string' },
{ name: 'Name' , type: 'string' },
{ name: 'Classification' , type: 'string' },
{ name: 'Type' , type: 'string' },
{ name: 'TaxCode' , type: 'string' },
{ name: 'Description' , type: 'string' },
{ name: 'Number' , type: 'string' }
]);
theThis.store_MYOBAccounts = new Ext.data.GroupingStore({
baseParams : {start : 0, limit : theThis.pageSize},
proxy: new Ext.data.HttpProxy(
new Ext.data.Connection({
url: '/Kounta/SearchMYOBAccounts',
dataType: 'json',
method: 'POST',
timeout: 1800000
})
),
reader: new Ext.data.JsonReader({
fields: accountRecord,
root: 'data',
idProperty: 'UID',
totalProperty : 'totalCount'
}),
autoLoad : false,
groupField : 'Classification',
listeners : {
'load' : function(){
},
'loadexception' : function(){
showStoreLoadingErrorMessage(theThis.store_MYOBAccounts);
}
}
//})
});
}
var cmb_MYOBAccounts = new Ext.ux.form.GroupComboBox({
store: theThis.store_MYOBAccounts,
//fieldLabel: fieldLabel,
displayField: 'Name',
valueField: 'UID',
typeAhead: true,
editable: true,
mode : 'local',
minChars: 1,
triggerAction: 'all',
lazyRender: true,
forceSelection: true,
width : 200,
mode: 'local',
emptyText : 'Select an account...',
groupTextTpl: '{text} ({[values.rs.length]})',
tpl : '{Name}
',
showGroupName: false,
startCollapsed: true
});
return cmb_MYOBAccounts;
}
});
Ext.reg('CTBXeroNonFoodItemPanel', Ext.CTBXeroNonFoodItemPanel);
Ext.CTBXeroSelectCorrespondingSuppliers = Ext.extend(Ext.Panel, {
layout : 'border',
loadMask: null,
pageSize: CTB.init.itemPerPage || 100,
recordObject : null,
instructionText : 'Select the corresponding suppliers between Cooking the Books and MYOB',
instructionBackgroundColor : '#4587ff',
callback_ContinueButtonClick : null,
dlg_Parent : null,
listeners : {
afterrender : function(theThis){
// Init loadMask
theThis.loadMask = new Ext.LoadMask(this.getEl(), {msg:"Please wait..."});
},
show : function(theThis){
}
},
initComponent: function(){
var theThis = this;
theThis.tpl_Instruction = new Ext.XTemplate(
'',
'',
'
',
'',
'',
'{instructionText} ',
' ',
' ',
'
',
'
',
' '
);
theThis.pnl_Instruction = new Ext.Panel({
frame : true,
region : 'north',
height : 70,
tpl : theThis.tpl_Instruction,
listeners : {
afterrender : function(p_This){
p_This.update({instructionBackgroundColor : theThis.instructionBackgroundColor, instructionText : theThis.instructionText});
}
}
});
theThis.grid_CorrespondingSupplierss = theThis.getGrid_CorrespondingSupplierss();
theThis.items = [theThis.grid_CorrespondingSupplierss, theThis.pnl_Instruction];
// Call super class to initialize componenets
Ext.CTBXeroSelectCorrespondingSuppliers.superclass.initComponent.call(this);
},
clearSelections : function(){
var theThis = this;
theThis.getGrid().getSelectionModel().clearSelections();
},
getGrid: function(){
var theThis = this;
return theThis.grid_CorrespondingSupplierss;
},
getPagingToolbar: function(){
var theThis = this;
return theThis.pt_CorrespondingSuppliers;
},
getSelectedRecords: function(){
var theThis = this;
return theThis.getGrid().getSelectionModel().getSelections();
},
loadData: function(){
var theThis = this;
theThis.callback_LoadData = function(){
theThis.loadMask.hide();
theThis.getGrid().getStore().commitChanges();
var distinctSupplierIds = new Array();
for (var i = 0; i < theThis.dlg_Parent.selectedInvoiceRecords.length; i++){
if (distinctSupplierIds.indexOf(theThis.dlg_Parent.selectedInvoiceRecords[i].data.supplierId) == -1) {
distinctSupplierIds[distinctSupplierIds.length] = theThis.dlg_Parent.selectedInvoiceRecords[i].data.supplierId;
}
}
theThis.getGrid().getStore().baseParams = {start : 0, limit : theThis.getPagingToolbar().pageSize, supplierIds : Ext.util.JSON.encode(distinctSupplierIds)};
theThis.getGrid().getStore().load();
}
if (theThis.store_XeroSuppliers.baseParams.query != null || theThis.store_XeroSuppliers.baseParams.query != "")
theThis.store_XeroSuppliers.baseParams.query = "";
theThis.loadMask.show();
theThis.store_XeroSuppliers.load();
},
getGrid_CorrespondingSupplierss: function(){
var theThis = this;
// shorthand alias
var fm = Ext.form;
// ***************************************************************************************************
// Data Fields
// ***************************************************************************************************
theThis.correspondingSuppliersRecord = Ext.data.Record.create([
{ name: 'CTBSupplierId' , type: 'number' },
{ name: 'CTBSupplierName' , type: 'string' },
{ name: 'MYOBSupplierID' , type: 'string' }
]);
// ***************************************************************************************************
// Stores
// ***************************************************************************************************
theThis.store_CorrespondingSuppliers = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy({
url: '/Kounta/SearchCorrespondingSuppliers',
dataType: 'json',
method: 'POST'
}),
fields: theThis.correspondingSuppliersRecord,
root: 'data',
idProperty: 'supplierId',
totalProperty : 'totalCount',
autoLoad : false,
groupField : 'Class',
listeners : {
'load' : function(){
},
'loadexception' : function(){
showStoreLoadingErrorMessage(theThis.store_CorrespondingSuppliers, function(){
theThis.dlg_Parent.connectToXero(function(){
theThis.store_CorrespondingSuppliers.load();
});
});
}
}
//})
});
// ***************************************************************************************************
// Grid
// ***************************************************************************************************
//-------------------------------------------------------------------
// Selection model
//-------------------------------------------------------------------
var sm = new Ext.grid.CheckboxSelectionModel({
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
// Do nothing at the moment
}
}
});
var correspondingSuppliersSm = new Ext.grid.CheckboxSelectionModel({
singleSelect : true,
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
}
}
});
theThis.cmb_XeroSuppliers = theThis.getCombobox_XeroSuppliers(function(){
if (theThis.callback_LoadData != null) {
theThis.callback_LoadData();
theThis.callback_LoadData = null;
}
});
// Column Models
var stockCM = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults: {
sortable: true // columns are not sortable by default
},
columns: [ correspondingSuppliersSm,
{ header: 'CTBSupplierId', dataIndex: 'CTBSupplierId', hidden: true },
{ header: 'Cooking the Books suppliers', dataIndex: 'CTBSupplierName', width: 50 },
{ header: 'MYOB suppliers', dataIndex: 'MYOBSupplierID', width: 50,
editor: theThis.cmb_XeroSuppliers,
renderer: Ext.util.Format.comboRenderer(theThis.cmb_XeroSuppliers)
}
]
});
// Context menu for right clicking
var contextMenu = new Ext.menu.Menu({
items:
[
{
iconCls: 'icon-add', scale : 'large',
text: 'New',
handler: function () {
theThis.btn_Add_CorrespondingSuppliers.handler.call(theThis.btn_Add_CorrespondingSuppliers.scope);
}
},
{
iconCls: 'icon-delete', scale : 'large',
text: 'Delete',
handler: function () {
theThis.btn_Delete_CorrespondingSuppliers.handler.call(theThis.btn_Delete_CorrespondingSuppliers.scope);
}
},
{
iconCls: 'icon-recipe',
text: 'View detail',
handler: function () {
if (theThis.selectedCorrespondingSuppliersId != -1){
theThis.dlg_CorrespondingSuppliersDetail.show();
}
}
}
]
});
/********************************************************************************************/
/****************************/
/* Searching Stock Combobox */
/****************************/
var data_SearchType = [
['By CorrespondingSuppliers Code', 1],
['By CorrespondingSuppliers Name' , 2]
];
var cmb_SearchCorrespondingSuppliers = new Ext.form.ComboBox({
store: new Ext.data.ArrayStore({
fields: [
{name: 'searchTypeDesc'},
{name: 'searchType', type: 'int'}
]
}),
editable: false,
displayField: 'searchTypeDesc',
valueField: 'searchType',
typeAhead: true,
triggerAction: 'all',
lazyRender: true,
mode: 'local',
emptyText: 'Choose search by ...'
});
// CorrespondingSuppliers grid
var grid_CorrespondingSuppliers = new Ext.grid.EditorGridPanel({
store : theThis.store_CorrespondingSuppliers,
frame : true,
region : 'center',
sm : correspondingSuppliersSm,
buttons : [
theThis.btn_Continue = new Ext.Button({
text: 'Continue',
iconCls : 'icon-ok-large', scale : 'large',
handler : function(){
theThis.saveXeroCorrespondingSuppliers(theThis.callback_ContinueButtonClick);
}
}),
theThis.btn_Cancel = new Ext.Button({
text: 'Cancel',
iconCls : 'icon-cancel-large', scale : 'large',
handler : function(){
if (theThis.dlg_Parent != null) theThis.dlg_Parent.hide();
}
})
],
listeners : {
rowclick : function ( p_this, p_rowIndex, p_eventObject ) {
// Hightlight the selected row
var selectedRow = p_this.getView().getRow(p_rowIndex);
Ext.get(selectedRow).highlight();
},
rowdblclick : function ( p_this, p_rowIndex, p_eventObject ) {
},
afterrender : function(){
/*theThis.store_CorrespondingSuppliers.baseParams = {keyword: "", start: 0, limit: theThis.pageSize},
theThis.store_CorrespondingSuppliers.load();*/
},
afteredit : function(p_Editor) {
if (p_Editor.record.data.ContactID != null && p_Editor.record.data.ContactID != ""){
p_Editor.record.set('Name', theThis.store_XeroSuppliers.getById(p_Editor.record.data.ContactID).data.Name);
}
}
},
cm: stockCM,
width: 780,
height: 400,
autoHeight: false,
clicksToEdit: 1,
loadMask: true,
bbar:
theThis.pt_CorrespondingSuppliers = new Ext.CTBPagingToolbar({
store: theThis.store_CorrespondingSuppliers,
pageSize: theThis.pageSize,
displayInfo: true,
emptyMsg: "No suppliers to display"
}),
viewConfig:
{
enableRowBody: true,
forceFit: true // IMPORTANT (USE THIS ATTRIBUTE TO USE PERCENTAGE IN COLUMN MODEL)
}
});
grid_CorrespondingSuppliers.on({
rowcontextmenu: function (grid, rowIndex, e) {
e.stopEvent();
var row = grid.getView().getRow(rowIndex);
Ext.get(row).highlight();
correspondingSuppliersSm.selectRow(rowIndex);
contextMenu.showAt(e.getXY());
}
});
return grid_CorrespondingSuppliers;
},
getCombobox_XeroSuppliers : function(callback_AfterLoad){
var theThis = this;
// Importing suppliers
theThis.store_XeroSuppliers = new Ext.data.JsonStore({
autoLoad : false,
proxy: new Ext.data.HttpProxy({
url: '/Kounta/SearchMYOBSuppliers',
dataType: 'json',
method: 'POST'
}),
fields: [
{ name: 'UID' , type: 'string' },
{ name: 'DisplayID' , type: 'string' },
{ name: 'Name' , type: 'string' }, // Processed on server to choose either company or individual's name
{ name: 'CompanyName' , type: 'string' },
{ name: 'FirstName' , type: 'string' },
{ name: 'LastName' , type: 'string' },
{ name: 'Notes' , type: 'string' }
],
root: 'data',
idProperty : 'UID',
listeners : {
'loadexception' : function(){
showStoreLoadingErrorMessage(theThis.store_XeroSuppliers);
},
'load' : function(){
if (cmbSupplier.callback_AfterLoad != null){
cmbSupplier.callback_AfterLoad();
}
}
}
});
//store.load();
var cmbSupplier = new Ext.form.ComboBox({
store: theThis.store_XeroSuppliers,
displayField: 'Name',
valueField: 'UID',
typeAhead: true,
editable: true,
mode : 'local',
minChars: 1,
colspan : 3,
/*listeners : {
beforequery: function(qe){
delete qe.combo.lastQuery; // Reload every click
}
},*/
callback_AfterLoad : callback_AfterLoad,
triggerAction: 'all',
lazyRender: true,
forceSelection: true,
emptyText: 'Select a supplier ...'/*,
onFocus: function (txt, e) {
this.getEl().dom.select();
}*/
//width: 338,
//style: { fontSize: '11px' }
});
return cmbSupplier;
},
saveXeroCorrespondingSuppliers : function(callback_Function){
var theThis = this;
var isPassed = true;
for(var i = 0; i < theThis.store_CorrespondingSuppliers.getCount(); i++){
if (theThis.store_CorrespondingSuppliers.getAt(i).data.MYOBSupplierID == null || theThis.store_CorrespondingSuppliers.getAt(i).data.MYOBSupplierID == "") {
isPassed = false;
break;
}
}
if (!isPassed) {
showErrorNotification('Notice', 'You need to select all corresponding suppliers.');
}
else {
//if (theThis.callback_ContinueButtonClick != null) theThis.callback_ContinueButtonClick(theThis.store_CorrespondingSuppliers);
var MYOBCorrespondingSuppliers = new Array();
for (var i = 0; i < theThis.store_CorrespondingSuppliers.getCount(); i++) {
MYOBCorrespondingSuppliers[i] = {
CTBSupplierId : theThis.store_CorrespondingSuppliers.getAt(i).data.CTBSupplierId,
MYOBSupplierID : theThis.store_CorrespondingSuppliers.getAt(i).data.MYOBSupplierID
}
}
function saveNow() {
theThis.loadMask.show();
Ext.Ajax.request({
method: 'POST',
url: '/Kounta/SaveMYOBCorrespondingSuppliers',
params:
{
MYOBCorrespondingSuppliers : Ext.util.JSON.encode(MYOBCorrespondingSuppliers)
},
success : function(result, request) {
theThis.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
theThis.getGrid().getStore().commitChanges();
showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
theThis.MYOBCorrespondingSuppliers = MYOBCorrespondingSuppliers;
if (callback_Function != null) callback_Function();
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.loadMask.hide();
}
}); // End ajax
}
saveNow();
}
}
});
Ext.reg('CTBXeroSelectCorrespondingSuppliers', Ext.CTBXeroSelectCorrespondingSuppliers);
Ext.CTBXeroInvoiceTransferingLogGrid = Ext.extend(Ext.Panel, {
layout : 'border',
loadMask: null,
pageSize: CTB.init.itemPerPage || 100,
recordObject : null,
instructionText : 'Transfering invoices in progress, please wait ...',
instructionBackgroundColor : '#fd4242',
callback_ContinueButtonClick : null,
dlg_Parent : null,
isCancelled : false,
MYOBHistoryTransactionRecord : null,
MYOBCorrespondingSuppliers : null,
totalProcessedRecord : 0,
listeners : {
afterrender : function(theThis){
// Init loadMask
theThis.loadMask = new Ext.LoadMask(this.getEl(), {msg:"Please wait..."});
},
show : function(theThis){
theThis.totalProcessedRecord = 0;
}
},
initComponent: function(){
var theThis = this;
theThis.tpl_Instruction = new Ext.XTemplate(
'',
'',
'
',
'',
'',
'{instructionText} ',
' ',
' ',
'
',
'
',
' '
);
theThis.pnl_Instruction = new Ext.Panel({
frame : true,
region : 'north',
height : 70,
tpl : theThis.tpl_Instruction,
listeners : {
afterrender : function(p_This){
p_This.update({instructionBackgroundColor : theThis.instructionBackgroundColor, instructionText : theThis.instructionText});
}
}
});
theThis.grid_InvoiceTransferingLogs = theThis.getGrid_InvoiceTransferingLogs();
theThis.items = [theThis.grid_InvoiceTransferingLogs, theThis.pnl_Instruction];
// Call super class to initialize componenets
Ext.CTBXeroInvoiceTransferingLogGrid.superclass.initComponent.call(this);
},
clearSelections : function(){
var theThis = this;
theThis.getGrid().getSelectionModel().clearSelections();
},
getGrid: function(){
var theThis = this;
return theThis.grid_InvoiceTransferingLogs;
},
getPagingToolbar: function(){
var theThis = this;
return theThis.pt_InvoiceTransferingLog;
},
getSelectedRecords: function(){
var theThis = this;
return theThis.getGrid().getSelectionModel().getSelections();
},
loadData: function(){
var theThis = this;
theThis.isCancelled = false;
theThis.getGrid().getStore().removeAll();
theThis.instructionText = "Transfering invoices in progress, please wait ...";
theThis.instructionBackgroundColor = "#fd4242";
theThis.pnl_Instruction.update({instructionBackgroundColor : theThis.instructionBackgroundColor, instructionText : theThis.instructionText});
theThis.btn_Continue.setVisible(false);
theThis.getXeroHistoryTransaction(function(){
theThis.transferAllInvoicesFromCTBToXero();
});
/*theThis.getGrid().getStore().commitChanges();
theThis.getGrid().getStore().baseParams = {start : 0, limit : theThis.pageSize};
theThis.getGrid().getStore().load();*/
},
getGrid_InvoiceTransferingLogs: function(){
var theThis = this;
// shorthand alias
var fm = Ext.form;
// ***************************************************************************************************
// Data Fields
// ***************************************************************************************************
theThis.invoiceTransferingLogRecord = Ext.data.Record.create([
{ name: 'invoiceTransferingLogID' , type: 'string' },
{ name: 'xeroInvoiceId' , type: 'string' },
{ name: 'invoiceId' , type: 'number' },
{ name: 'invoiceDate' , type: 'date' },
{ name: 'invoiceNo' , type: 'string' },
{ name: 'supplierName' , type: 'string' },
{ name: 'supplierId' , type: 'number' },
{ name: 'totalAmount' , type: 'number' },
{ name: 'totalTax' , type: 'number' },
{ name: 'discount' , type: 'number' },
{ name: 'freightIncludeGST' , type: 'number' },
{ name: 'isReturned' , type: 'boolean'},
{ name: 'xeroProcessingStatus' , type: 'string' },
{ name: 'xeroTransferingMessage' , type: 'string' }
]);
// ***************************************************************************************************
// Stores
// ***************************************************************************************************
theThis.store_InvoiceTransferingLog = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy({
url: '/Xero/SearchInvoiceTransferingLogs',
dataType: 'json',
method: 'POST'
}),
fields: theThis.invoiceTransferingLogRecord,
root: 'data',
idProperty: 'invoiceTransferingLogID',
totalProperty : 'totalCount',
autoLoad : false,
listeners : {
'load' : function(){
},
'loadexception' : function(){
showStoreLoadingErrorMessage(theThis.store_InvoiceTransferingLog, function(){
theThis.dlg_Parent.connectToXero(function(){
theThis.store_InvoiceTransferingLog.load();
});
});
}
}
//})
});
// ***************************************************************************************************
// Grid
// ***************************************************************************************************
//-------------------------------------------------------------------
// Selection model
//-------------------------------------------------------------------
var sm = new Ext.grid.CheckboxSelectionModel({
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
// Do nothing at the moment
}
}
});
var invoiceTransferingLogSm = new Ext.grid.CheckboxSelectionModel({
singleSelect : true,
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
}
}
});
// Column Models
var stockCM = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults: {
sortable: true // columns are not sortable by default
},
columns: [ invoiceTransferingLogSm,
{ header: 'invoiceTransferingLogID', dataIndex: 'invoiceTransferingLogID', hidden: true },
{ header: 'invoiceId', dataIndex: 'invoiceId', hidden: true },
{ header: 'Date', dataIndex: 'invoiceDate', width: 10,
renderer : function(val){
return Ext.util.Format.date(val, 'd/m/Y');
}
},
{ header: 'Supplier(s)', dataIndex: 'supplierName', width: 25,
renderer : function(val){
var supplierName = val;
return ''+supplierName+' ';
}
},
{ header: 'Invoice No.', dataIndex: 'invoiceNo', width: 10
},
{ header: 'Type', dataIndex: 'isReturned', width: 5,
renderer: function(val)
{
if (val) return "Return";
else return "Purchase";
}
},
{ header: 'Total', dataIndex: 'totalAmount', width: 10,
renderer: Ext.util.Format.usMoney
},
{ header: 'Message', dataIndex: 'xeroTransferingMessage', width: 35,
renderer: function(val, meta, theRecord)
{
if (theRecord.data.xeroProcessingStatus == XERO_PROCESSING_STATUS.PROCESSING) return 'Processing...';
else return val;
}
},
{ header: 'Status', dataIndex: 'xeroProcessingStatus', width: 5,
renderer: function(val)
{
if (val == XERO_PROCESSING_STATUS.PROCESSING) return '';
else if (val == XERO_PROCESSING_STATUS.SUCCEED) return '';
else if (val == XERO_PROCESSING_STATUS.FAILED) return '';
}
}
]
});
/********************************************************************************************/
// InvoiceTransferingLog grid
var grid_InvoiceTransferingLog = new Ext.grid.EditorGridPanel({
store : theThis.store_InvoiceTransferingLog,
frame : true,
region : 'center',
sm : invoiceTransferingLogSm,
buttons : [
theThis.btn_Continue = new Ext.Button({
text: 'Finish',
iconCls : 'icon-ok-large', scale : 'large',
hidden : true,
handler : function(){
if (theThis.callback_ContinueButtonClick != null) theThis.callback_ContinueButtonClick();
}
}),
theThis.btn_Cancel = new Ext.Button({
text: 'Cancel',
iconCls : 'icon-cancel-large', scale : 'large',
handler : function(){
theThis.isCancelled = true;
if (theThis.dlg_Parent != null)
theThis.dlg_Parent.hide();
}
})
],
listeners : {
rowclick : function ( p_this, p_rowIndex, p_eventObject ) {
// Hightlight the selected row
var selectedRow = p_this.getView().getRow(p_rowIndex);
Ext.get(selectedRow).highlight();
},
rowdblclick : function ( p_this, p_rowIndex, p_eventObject ) {
},
afterrender : function(){
/*theThis.store_InvoiceTransferingLog.baseParams = {keyword: "", start: 0, limit: theThis.pageSize},
theThis.store_InvoiceTransferingLog.load();*/
}
},
cm: stockCM,
width: 780,
height: 400,
autoHeight: false,
clicksToEdit: 1,
loadMask: true,
/*bbar:
theThis.pt_InvoiceTransferingLog = new Ext.CTBPagingToolbar({
store: theThis.store_InvoiceTransferingLog,
pageSize: theThis.pageSize,
displayInfo: true,
emptyMsg: "No logs to display"
}),*/
viewConfig:
{
enableRowBody: true,
forceFit: true // IMPORTANT (USE THIS ATTRIBUTE TO USE PERCENTAGE IN COLUMN MODEL)
}
});
return grid_InvoiceTransferingLog;
}, // End generateGrid_Databases
transferAllInvoicesFromCTBToXero : function(){
var theThis = this;
theThis.totalProcessedRecord = 0;
theThis.transferInvoicesInBatch();
//theThis.startProcessingIndex = 0;
//theThis.loopTransferInvoice();
},
getXeroHistoryTransaction : function(callback_Function){
var theThis = this;
theThis.loadMask.show();
Ext.Ajax.request({
method: 'POST',
url: '/Kounta/GetNewMYOBHistoryTransaction',
params:
{
},
success : function(result, request) {
theThis.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
theThis.MYOBHistoryTransactionRecord = jsonData.data;
if (callback_Function != null) callback_Function();
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.loadMask.hide();
}
}); // End ajax
},
loopTransferInvoice : function(){
var theThis = this;
if (theThis.isCancelled) return false;
var selectedInvoiceRecords = theThis.dlg_Parent.selectedInvoiceRecords;
if (theThis.startProcessingIndex < selectedInvoiceRecords.length) {
var theNewRecord = theThis.addNewRecord(selectedInvoiceRecords[theThis.startProcessingIndex]);
theThis.startProcessingIndex++;
function transferInvoiceNow(){
Ext.Ajax.request({
method: 'POST',
url: '/Kounta/TransferInvoiceFromCTBtoXero',
params:
{
invoiceId : theNewRecord.data.invoiceId,
MYOBHistoryId : theThis.MYOBHistoryTransactionRecord.MYOBHistoryId,
accountCode : theThis.dlg_Parent.accountCode
},
success : function(result, request) {
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
theThis.updateInvoiceTransferingStatus(theNewRecord.data.invoiceTransferingLogID, XERO_PROCESSING_STATUS.SUCCEED, jsonData.message.Info);
theThis.loopTransferInvoice();
}
else {
if (jsonData.message.Info == XERO_MESSAGE.ACCESS_TOKEN_EXPIRED || jsonData.message.Info == XERO_MESSAGE.INVALID_ACCESS_TOKEN) {
// Reconnect
theThis.dlg_Parent.connectToXero(transferInvoiceNow);
}
else {
theThis.updateInvoiceTransferingStatus(theNewRecord.data.invoiceTransferingLogID, XERO_PROCESSING_STATUS.FAILED, jsonData.message.Info);
theThis.loopTransferInvoice();
// showErrorMessageWithEmailNotify(jsonData.message.Info);
}
}
},
failure : function(result, request) {
theThis.updateInvoiceTransferingStatus(theNewRecord.data.invoiceTransferingLogID, XERO_PROCESSING_STATUS.FAILED, "Server unavailable!");
}
}); // End ajax
}
transferInvoiceNow();
return true;
}
else {
theThis.instructionText = "Transfering progress completed";
theThis.pnl_Instruction.update({instructionBackgroundColor : theThis.instructionBackgroundColor, instructionText : theThis.instructionText});
theThis.btn_Continue.setVisible(true);
return false;
}
},
transferInvoicesInBatch : function(){
var theThis = this;
if (theThis.isCancelled) return false;
var selectedInvoiceRecords = theThis.dlg_Parent.selectedInvoiceRecords;
var MYOBInvoiceSupplierLinks = new Array();
var invoiceIds = new Array();
var lastTotalProcessedRecords = theThis.totalProcessedRecord;
var countBatch = 0;
for (var i = lastTotalProcessedRecords; i < selectedInvoiceRecords.length; i++){
var theNewRecord = theThis.addNewRecord(selectedInvoiceRecords[i]);
invoiceIds[i] = theNewRecord.data.invoiceId;
// Find the corresponding MYOB supplier ID
var CTBSupplierId = theNewRecord.data.supplierId;
var MYOBSupplierID = '';
if (theThis.MYOBCorrespondingSuppliers != null){
for (var j = 0; j < theThis.MYOBCorrespondingSuppliers.length; j++) {
if (theThis.MYOBCorrespondingSuppliers[j].CTBSupplierId == CTBSupplierId){
MYOBSupplierID = theThis.MYOBCorrespondingSuppliers[j].MYOBSupplierID;
break;
}
}
}
// Wrap up the data (invoice & the link with its MYOB Supplier)
MYOBInvoiceSupplierLinks[i] = {
CTBInvoiceId : theNewRecord.data.invoiceId,
MYOBSupplierID : MYOBSupplierID
}
theThis.totalProcessedRecord++; // Increase processed record
countBatch++;
if (countBatch == 10) // 10 item in each batch
break; // No need to continue, wait for next batch
}
if (countBatch == 0) { // End the batch, no more item to process
theThis.instructionText = "Transfering progress completed";
theThis.instructionBackgroundColor = "#01DF01";
theThis.pnl_Instruction.update({instructionBackgroundColor : theThis.instructionBackgroundColor, instructionText : theThis.instructionText});
theThis.btn_Continue.setVisible(true);
return false;
}
else if (theThis.totalProcessedRecord <= selectedInvoiceRecords.length && theThis.MYOBCorrespondingSuppliers != null) {
//var theNewRecord = theThis.addNewRecord(selectedInvoiceRecords[theThis.startProcessingIndex]);
//theThis.startProcessingIndex++;
function transferInvoiceNow(){
Ext.Ajax.request({
method: 'POST',
url: '/Kounta/TransferInvoiceBatchFromCTBtoMYOB',
timeout: 1800000,
params:
{
MYOBInvoiceSupplierLinks : Ext.util.JSON.encode(MYOBInvoiceSupplierLinks),
MYOBHistoryId : theThis.MYOBHistoryTransactionRecord.MYOBHistoryId,
accountCode : theThis.dlg_Parent.accountCode,
freightAccountCode : theThis.dlg_Parent.freightAccountCode == null ? "" : theThis.dlg_Parent.freightAccountCode,
isOnlyOneNonFoodAccount : theThis.dlg_Parent.isOnlyOneNonFoodAccount,
nonFoodAccountCode : theThis.dlg_Parent.nonFoodAccountCode == null ? "" : theThis.dlg_Parent.nonFoodAccountCode,
},
success : function(result, request) {
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
if (jsonData.data.length > 0) {
for (var i = 0; i < jsonData.data.length; i++) {
var returnBatchMessage = jsonData.data[i];
if (returnBatchMessage.isSuccess)
theThis.updateInvoiceTransferingStatusByInvoiceId(returnBatchMessage.invoiceId, XERO_PROCESSING_STATUS.SUCCEED, returnBatchMessage.message);
else
theThis.updateInvoiceTransferingStatusByInvoiceId(returnBatchMessage.invoiceId, XERO_PROCESSING_STATUS.FAILED, returnBatchMessage.message);
}
}
theThis.transferInvoicesInBatch(); // Continue another batch (if have)
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
showErrorNotification('Notice', 'Server unavailable!');
//theThis.updateInvoiceTransferingStatus(theNewRecord.data.invoiceTransferingLogID, XERO_PROCESSING_STATUS.FAILED, "Server unavailable!");
}
}); // End ajax
}
transferInvoiceNow();
return true;
}
},
updateInvoiceTransferingStatus : function(invoiceTransferingLogID, theStatus, xeroTransferingMessage) {
var theThis = this;
theThis.getGrid().getStore().getById(invoiceTransferingLogID).set('xeroProcessingStatus', theStatus);
theThis.getGrid().getStore().getById(invoiceTransferingLogID).set('xeroTransferingMessage', xeroTransferingMessage);
},
updateInvoiceTransferingStatusByInvoiceId : function(invoiceId, theStatus, xeroTransferingMessage) {
var theThis = this;
for (var i = 0; i < theThis.getGrid().getStore().getCount(); i++) {
var theRecord = theThis.getGrid().getStore().getAt(i);
if (theRecord.data.invoiceId == invoiceId) {
theRecord.set('xeroProcessingStatus', theStatus);
theRecord.set('xeroTransferingMessage', xeroTransferingMessage);
break;
}
}
//theThis.getGrid().getStore().getById(invoiceTransferingLogID).set('xeroProcessingStatus', theStatus);
//theThis.getGrid().getStore().getById(invoiceTransferingLogID).set('xeroTransferingMessage', xeroTransferingMessage);
},
addNewRecord : function(invoiceRecord, quantity){
var theThis = this;
var theStore = theThis.getGrid().getStore();
var newId = theStore.getCount();
var aNewRecord = new theThis.invoiceTransferingLogRecord({
invoiceTransferingLogID : newId,
xeroInvoiceId : '',
invoiceId : invoiceRecord.data.invoiceId,
invoiceDate : invoiceRecord.data.invoiceDate,
invoiceNo : invoiceRecord.data.invoiceNo,
supplierName : invoiceRecord.data.supplierName,
supplierId : invoiceRecord.data.supplierId,
totalAmount : invoiceRecord.data.totalAmount,
totalTax : invoiceRecord.data.totalTax,
discount : invoiceRecord.data.discount,
freightIncludeGST : invoiceRecord.data.freightIncludeGST,
isReturned : invoiceRecord.data.isReturned,
xeroProcessingStatus : XERO_PROCESSING_STATUS.PROCESSING
}, newId);
theStore.insert(theThis.getGrid().getStore().getCount(), aNewRecord);
return aNewRecord;
}
});
Ext.reg('CTBXeroInvoiceTransferingLogGrid', Ext.CTBXeroInvoiceTransferingLogGrid);
Ext.CTBXeroTransferInvoiceWindow = Ext.extend(Ext.Window, {
title: 'Export invoices to MYOB',
layout: 'card',
closeAction: 'hide',
iconCls : 'icon-v3-ctb-logo',
cls : 'ctbwindow-detail-general',
expandOnShow: true,
closable: true,
resizable: true,
modal: true,
plain: true,
minimizable: true,
maximizable: true,
monitorResize: true,
width: 800,
height: 500,
activeItem : 0,
defaults: {
split: true,
animFloat: false,
autoHide: false,
useSplitTips: true
},
pageSize: CTB.init.itemPerPage || 100,
accountCode : '',
freightAccountCode : null,
selectedInvoiceRecords : null,
callback_AfterHide : null,
isOnlyOneNonFoodAccount : true,
nonFoodAccountCode : null,
setSelectedInvoiceRecords : function(selectedInvoiceRecords){
var theThis = this;
theThis.selectedInvoiceRecords = selectedInvoiceRecords;
},
listeners: {
scope : this,
'beforehide': function(theThis){
},
'beforeshow': function(theThis){
// Fit this window to the client browser screen with 90%
fitWindowSize(theThis, 90);
},
'show': function(theThis){
theThis.layout.setActiveItem(theThis.pnl_XeroSelectAccount);
theThis.pnl_XeroSelectAccount.loadData();
},
'hide': function(theThis){
if (theThis.callback_AfterHide != null) {
theThis.callback_AfterHide();
}
}
},
initComponent : function(){
var theThis = this;
// Select account for food purchase
theThis.pnl_XeroSelectAccount = new Ext.CTBXeroSelectAccountGrid({
dlg_Parent : theThis,
callback_ContinueButtonClick : function(accountCode) {
theThis.accountCode = accountCode;
theThis.dlg_FreightQuestion.show(); // Ask user question about what they want to do with freight
}
});
// Select account for freight
theThis.pnl_XeroSelectFreightAccount = new Ext.CTBXeroSelectAccountGrid({
dlg_Parent : theThis,
instructionText : 'Select the freight account that you want the freight value to be assigned to'
});
// Ask user question about what do they want to do with Freight value in the invoice
theThis.dlg_FreightQuestion = new Ext.CTBFreightQuestionWindow({
callback_AfterSelect : function(isAssignToMYOBFreightField){
function moveToNextStep(){
// Move to next step
// Select corresponding suppliers
theThis.layout.setActiveItem(theThis.pnl_XeroSelectCorrespondingSuppliers);
theThis.pnl_XeroSelectCorrespondingSuppliers.loadData();
}
if (isAssignToMYOBFreightField == true) {
theThis.freightAccountCode = null; // Not using freightAccountCode
moveToNextStep();
}
else {
theThis.pnl_XeroSelectFreightAccount.callback_ContinueButtonClick = function(accountCode){
theThis.freightAccountCode = accountCode;
moveToNextStep();
};
theThis.layout.setActiveItem(theThis.pnl_XeroSelectFreightAccount);
theThis.pnl_XeroSelectFreightAccount.loadData();
}
}
});
theThis.pnl_XeroSelectCorrespondingSuppliers = new Ext.CTBXeroSelectCorrespondingSuppliers({
dlg_Parent : theThis,
callback_ContinueButtonClick : function(theStore) {
// Check if the selected invoices contained non-food item
var doesContainNonFoodItems = false;
for (var i = 0; i < theThis.selectedInvoiceRecords.length; i++) {
if (theThis.selectedInvoiceRecords[i].data.doesContainNonFoodItems == true){
doesContainNonFoodItems = true;
break;
}
}
// If contain non food item(appear the non food item link with MYOB accounts)
if (doesContainNonFoodItems) {
theThis.layout.setActiveItem(theThis.pnl_XeroNonFoodItem);
theThis.pnl_XeroNonFoodItem.loadData(theThis.selectedInvoiceRecords);
}
else { // If not, simply move to the transfering step
// Move to next step
// Transfering the invoices
theThis.layout.setActiveItem(theThis.pnl_XeroInvoiceTransferingLogGrid);
theThis.pnl_XeroInvoiceTransferingLogGrid.MYOBCorrespondingSuppliers = theThis.pnl_XeroSelectCorrespondingSuppliers.MYOBCorrespondingSuppliers;
theThis.pnl_XeroInvoiceTransferingLogGrid.loadData();
}
}
});
theThis.pnl_XeroNonFoodItem = new Ext.CTBXeroNonFoodItemPanel({
dlg_Parent : theThis,
callback_ContinueButtonClick : function(isOnlyOneNonFoodAccount, nonFoodAccountCode) { // the data variable will be one account code if isOnlyOneAccount = true
// Move to next step
// Transfering the invoices
theThis.layout.setActiveItem(theThis.pnl_XeroInvoiceTransferingLogGrid);
theThis.nonFoodAccountCode = nonFoodAccountCode;
theThis.isOnlyOneNonFoodAccount = isOnlyOneNonFoodAccount;
theThis.pnl_XeroInvoiceTransferingLogGrid.MYOBCorrespondingSuppliers = theThis.pnl_XeroSelectCorrespondingSuppliers.MYOBCorrespondingSuppliers;
theThis.pnl_XeroInvoiceTransferingLogGrid.loadData();
}
});
theThis.pnl_XeroInvoiceTransferingLogGrid = new Ext.CTBXeroInvoiceTransferingLogGrid({
dlg_Parent : theThis,
callback_ContinueButtonClick : function(theStore) {
// Reload the invoice grid
theThis.hide();
}
});
theThis.items = [
theThis.pnl_XeroSelectAccount,
theThis.pnl_XeroSelectFreightAccount,
theThis.pnl_XeroSelectCorrespondingSuppliers,
theThis.pnl_XeroNonFoodItem,
theThis.pnl_XeroInvoiceTransferingLogGrid
];
// BUTTONS
var myButtons = theThis.initButtons();
this.buttons = myButtons;
this.initTools();
Ext.CTBXeroTransferInvoiceWindow.superclass.initComponent.call(this);
},
initButtons : function(){
var theThis = this;
var buttons = [
/*theThis.btn_Cancel = new Ext.Button({
text: 'Cancel',
iconCls : 'icon-cancel-large', scale : 'large',
handler : function(){
theThis.hide();
}
})*/
];
return buttons;
},
connectToXero : function(callbackFunction, customMessage){
var theThis = this;
if (customMessage == null) customMessage = "Your access to Xero has been expired. Please reconnect.";
if (theThis.dlg_ConnectToXero == null) {
theThis.dlg_ConnectToXero = new Ext.CTBXeroConnectWindow({
callback_ContinueButtonClick : function() { // Continue the process if only there is a valid connection established
theThis.dlg_ConnectToXero.hide();
if (callbackFunction != null) callbackFunction();
}
});
}
theThis.dlg_ConnectToXero.customMessage = customMessage;
theThis.dlg_ConnectToXero.show();
}
});
Ext.reg('CTBXeroTransferInvoiceWindow', Ext.CTBXeroTransferInvoiceWindow);
Ext.CTBXeroConnectWindow = Ext.extend(Ext.Window, {
title: 'Connect to Kounta',
layout: 'border',
closeAction: 'hide',
iconCls : 'icon-v3-ctb-logo',
expandOnShow: true,
closable: true,
resizable: true,
modal: true,
plain: true,
minimizable: true,
maximizable: true,
monitorResize: true,
width: 400,
height: 200,
defaults: {
split: true,
animFloat: false,
autoHide: false,
useSplitTips: true
},
callback_ContinueButtonClick : null,
pageSize: CTB.init.itemPerPage || 100,
customMessage : 'You haven\'t connected to Kounta. Please click the link below to connect to Kounta.',
listeners: {
scope : this,
'beforehide': function(theThis){
},
'beforeshow': function(theThis){
// Fit this window to the client browser screen with 90%
// fitWindowSize(theThis, 90);
},
'show': function(theThis){
theThis.btn_Continue.setVisible(false);
theThis.pnl_ConnectPage.update({isLoading : true, isCompleted : false, dialogId : theThis.id, customMessage : theThis.customMessage});
theThis.isThereConnectionEstablished(false);
}
},
initComponent : function(){
var theThis = this;
theThis.tpl_ConnectPage = new Ext.XTemplate(
'',
'',
'',
'',
' ',
'',
'',
'
Connection established successfully.
',
'
',
' ',
' ',
'',
'',
'
Connecting to Kounta ...',
'
',
'
',
'
',
' ',
' '
);
theThis.items = [
theThis.pnl_ConnectPage = new Ext.Panel ({
region : 'center',
frame : true,
tpl : theThis.tpl_ConnectPage,
listeners : {
afterrender : function(p_This){
}
}
})
];
// BUTTONS
var myButtons = theThis.initButtons();
this.buttons = myButtons;
this.initTools();
Ext.CTBXeroConnectWindow.superclass.initComponent.call(this);
},
initButtons : function(){
var theThis = this;
var buttons = [
theThis.btn_Continue = new Ext.Button({
text: 'Continue',
hidden : true,
iconCls : 'icon-ok-large', scale : 'large',
handler : function(){
if (theThis.callback_ContinueButtonClick != null) theThis.callback_ContinueButtonClick();
theThis.hide();
}
}),
theThis.btn_Cancel = new Ext.Button({
text: 'Cancel',
iconCls : 'icon-cancel-large', scale : 'large',
handler : function(){
theThis.hide();
}
})
];
return buttons;
},
isThereConnectionEstablished : function(isCallingUntilThereIsConnectionEstablished) {
var theThis = this;
Ext.Ajax.request({
method: "POST",
url: '/Kounta/IsThereConnectionEstablished',
params:
{
},
success : function(result, request) {
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
theThis.pnl_ConnectPage.update({isLoading : false, isCompleted : true, dialogId : theThis.id, customMessage : theThis.customMessage});
theThis.btn_Continue.setVisible(true);
}
else {
// showErrorMessageWithEmailNotify(jsonData.message.Info);
if (isCallingUntilThereIsConnectionEstablished) {
setTimeout(function(){
theThis.isThereConnectionEstablished(true);
}, 2000);
}
else {
theThis.pnl_ConnectPage.update({isLoading : false, isCompleted : false, dialogId : theThis.id, customMessage : theThis.customMessage});
}
}
},
failure : function(result, request) {
//loadMask.hide();
setTimeout(function(){
theThis.isThereConnectionEstablished(true);
}, 2000);
}
}); // End ajax
}
});
Ext.reg('CTBXeroConnectWindow', Ext.CTBXeroConnectWindow);
function CTBXeroConnectWindow_ActivateLoader(dialogId){
Ext.getCmp(dialogId).pnl_ConnectPage.update({isLoading : true, isCompleted : false, dialogId : dialogId, customMessage : Ext.getCmp(dialogId).customMessage});
Ext.getCmp(dialogId).isThereConnectionEstablished(true);
}
Ext.CTBXeroTransferInvoice = Ext.extend(Ext.Panel, {
layout : 'border',
loadMask: null,
pageSize: CTB.init.itemPerPage || 100,
recordObject : null,
selectedInvoiceRecords : null,
listeners : {
afterrender : function(p_This){
// Init loadMask
p_This.loadMask = new Ext.LoadMask(this.getEl(), {msg:"Please wait..."});
}
},
initComponent: function(){
var theThis = this;
/* commented by Andy C on 4/5/2015
theThis.dlg_InvoiceDetail = new Ext.CTBInvoiceDetailWindow({
callback_AfterSave : function(){
theThis.grid_Invoices.getStore().load();
}
});
*/
//init the select Kounta site window component
this.ctbCountaSelectSitesWindow = new Ext.CTBKountaSelectSiteWindow();
this.ctbCountaSelectSitesForConfigurationWindow = new Ext.CTBKountaSelectSiteWindow();
theThis.grid_Invoices = theThis.getGrid_Invoices();
theThis.items = [theThis.grid_Invoices];
// Call super class to initialize componenets
Ext.CTBXeroTransferInvoice.superclass.initComponent.call(this);
},
clearSelections : function(){
var theThis = this;
theThis.getGrid().getSelectionModel().clearSelections();
},
getGrid: function(){
var theThis = this;
return theThis.grid_Invoices;
},
getPagingToolbar: function(){
var theThis = this;
return theThis.pt_Invoice;
},
getSelectedRecords: function(){
var theThis = this;
return theThis.getGrid().getSelectionModel().getSelections();
},
loadData: function(){
var theThis = this;
theThis.getGrid().getStore().commitChanges();
theThis.getGrid().getStore().baseParams = {start : 0, limit : theThis.getPagingToolbar().pageSize};
theThis.getGrid().getStore().load();
},
getGrid_Invoices: function(){
var theThis = this;
// shorthand alias
var fm = Ext.form;
// ***************************************************************************************************
// Data Fields
// ***************************************************************************************************
theThis.invoiceRecord = Ext.data.Record.create([
{ name: 'id' , type: 'number' },
{ name: 'status' , type: 'string' },
{ name: 'total' , type: 'number' },
{ name: 'created_at' , type: 'date' },
{ name: 'updated_at' , type: 'date' }
]);
// ***************************************************************************************************
// Stores
// ***************************************************************************************************
theThis.store_Invoice = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy(
new Ext.data.Connection({
url: '/Kounta/SearchOrders',
dataType: 'json',
method: 'POST',
timeout: 1800000
})
),
autoLoad : false,
fields: theThis.invoiceRecord,
root: 'data',
idProperty: 'invoiceId',
totalProperty: 'totalCount',
listeners : {
'load' : function(p_This, records, options){
//console.log(p_This);
},
'loadexception' : function(){
showStoreLoadingErrorMessage(theThis.store_Invoice);
}
}
//})
});
// ***************************************************************************************************
// Grid
// ***************************************************************************************************
//-------------------------------------------------------------------
// Selection model
//-------------------------------------------------------------------
var sm = new Ext.grid.CheckboxSelectionModel({
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
// Do nothing at the moment
}
}
});
var invoiceSm = new Ext.grid.CheckboxSelectionModel({
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
// Do nothing at the moment
var selectedInvoices = sm.getSelections();
theThis.selectedInvoiceId = -1;
if (selectedInvoices.length > 0){
theThis.selectedInvoiceId = selectedInvoices[0].get('invoiceId');
}
}
}
});
// Column Models
var stockCM = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults: {
sortable: true // columns are not sortable by default
},
columns: [ invoiceSm,
{ header: 'id', dataIndex: 'id', hidden: true },
{ header: 'Created date', dataIndex: 'created_at', width: 25,
renderer : function(val){
return Ext.util.Format.date(val, 'd/m/Y');
}
},
{ header: 'Updated date', dataIndex: 'updated_at', width: 25,
renderer : function(val){
return Ext.util.Format.date(val, 'd/m/Y');
}
},
{ header: 'Status', dataIndex: 'status', width: 25
},
{ header: 'Total', dataIndex: 'total', width: 25,
renderer: Ext.util.Format.usMoney
}
]
});
/********************************************************************************************/
/****************************/
/* Searching Stock Combobox */
/****************************/
var data_SearchType = [
['By Date range' , 2]
];
var cmb_SearchInvoice = new Ext.form.ComboBox({
store: new Ext.data.ArrayStore({
fields: [
{name: 'searchTypeDesc'},
{name: 'searchType', type: 'int'}
]
}),
editable: false,
displayField: 'searchTypeDesc',
valueField: 'searchType',
typeAhead: true,
triggerAction: 'all',
lazyRender: true,
mode: 'local',
emptyText: 'Choose search by ...'
});
// manually load local data
cmb_SearchInvoice.getStore().loadData(data_SearchType);
cmb_SearchInvoice.setValue(2);
cmb_SearchInvoice.on({
select: function (p_combo, p_record, p_index) {
var searchType = p_record.get('searchType');
if (searchType == 1 || searchType == 3){
theThis.txt_Invoice_SearchInvoiceValue.setVisible(true);
theThis.txt_Invoice_SearchInvoiceDateFrom.setVisible(false);
theThis.txt_Invoice_SearchInvoiceDateTo.setVisible(false);
theThis.lbl_Invoice_SearchInvoiceDateFrom.setVisible(false);
theThis.lbl_Invoice_SearchInvoiceDateTo.setVisible(false);
}
else if (searchType == 2){
theThis.txt_Invoice_SearchInvoiceValue.setVisible(false);
theThis.txt_Invoice_SearchInvoiceDateFrom.setVisible(true);
theThis.txt_Invoice_SearchInvoiceDateTo.setVisible(true);
theThis.lbl_Invoice_SearchInvoiceDateFrom.setVisible(true);
theThis.lbl_Invoice_SearchInvoiceDateTo.setVisible(true);
}
}
});
// Invoice grid
var grid_Invoice = new Ext.grid.EditorGridPanel({
store : theThis.store_Invoice,
title : 'Kounta\'s orders',
frame : true,
region : 'center',
sm : invoiceSm,
listeners : {
rowclick : function ( p_this, p_rowIndex, p_eventObject ) {
theThis.selectedInvoiceId = p_this.getStore().getAt(p_rowIndex).get("invoiceId");
// Hightlight the selected row
var selectedRow = p_this.getView().getRow(p_rowIndex);
Ext.get(selectedRow).highlight();
},
rowdblclick : function ( p_this, p_rowIndex, p_eventObject ) {
//theThis.btn_Edit_Invoice.handler.call(theThis.btn_Edit_Invoice.scope);
},
afterrender : function(){
theThis.store_Invoice.baseParams = {keyword: "", start: 0, limit: theThis.pageSize},
theThis.store_Invoice.load();
theThis.txt_Invoice_SearchInvoiceValue.setVisible(false);
theThis.txt_Invoice_SearchInvoiceDateFrom.setVisible(true);
theThis.txt_Invoice_SearchInvoiceDateTo.setVisible(true);
theThis.lbl_Invoice_SearchInvoiceDateFrom.setVisible(true);
theThis.lbl_Invoice_SearchInvoiceDateTo.setVisible(true);
}
},
tbar: [
/*theThis.btn_Add_Invoice = new Ext.Button({
iconCls: 'icon-add',
scale : 'large',
text: 'New',
handler: function () {
theThis.selectedInvoiceId = -1;
theThis.dlg_InvoiceDetail.setSelectedInvoiceRecord(null);
theThis.dlg_InvoiceDetail.show();
}
}),
'-',
theThis.btn_Edit_Invoice = new Ext.Button({
iconCls: 'icon-edit',
text: 'Edit',
scale : 'large',
handler: function () {
// Get selected invoice id
var selectedItems = theThis.grid_Invoices.getSelectionModel().getSelections();
if (selectedItems.length > 0)
{
theThis.dlg_InvoiceDetail.setSelectedInvoiceRecord(selectedItems[0]);
theThis.dlg_InvoiceDetail.show();
}
else {
Ext.Msg.show({
title:'Notice',
msg: 'Please choose an item to edit ?',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
}
}
}),
'-',
theThis.btn_Delete_Invoice = new Ext.Button({
iconCls: 'icon-delete',
text: 'Delete',
scale : 'large',
//disabled: true,
handler: function () {
var selectedItems = theThis.grid_Invoices.getSelectionModel().getSelections();
if (selectedItems.length > 0)
{
Ext.Msg.show({
title:'Confirm',
msg: 'Are you sure you want to delete the item(s) ?',
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.QUESTION,
fn : function(btn) {
if (btn == "yes") {
loadMask.show();
var collectionOfDeletedIds = new Array();
for (var i = 0, row; row = selectedItems[i]; i++) {
collectionOfDeletedIds[i] = row.get("invoiceId");
}
// Calling delete
Ext.Ajax.request({
method: 'POST',
url: '/Invoice/DeleteInvoices',
params:
{
invoiceIds : Ext.util.JSON.encode(collectionOfDeletedIds)
},
success : function(result, request) {
loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
theThis.grid_Invoices.getStore().load();
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
loadMask.hide();
}
}); // End ajax
}
}
});
}
else {
Ext.Msg.show({
title:'Notice',
msg: 'Please select item(s) to delete!',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
} // End if
}
}),
'-',
theThis.btn_Connect = new Ext.Button({
iconCls: 'icon-move-right',
text: 'Connect',
tooltip : 'Export invoices from Cooking the Books to Xero',
scale : 'large',
handler: function () {
if (theThis.dlg_ConnectToXero == null) {
theThis.dlg_ConnectToXero = new Ext.CTBXeroConnectWindow({
callback_ContinueButtonClick : function() { // Continue the process if only there is a valid connection established
// Do nothing for now
}
});
}
theThis.dlg_ConnectToXero.show();
}
}),
'-',*/
theThis.btn_Transfer_Invoice = new Ext.Button({
iconCls: 'icon-move-right',
text: 'Transfer orders',
tooltip : 'Import Kounta\'s orders to Cooking the Books',
scale : 'large',
handler: function () {
// Get selected invoice id
var selectedItems = theThis.grid_Invoices.getSelectionModel().getSelections();
if (selectedItems.length > 0)
{
theThis.getPOSIntegratedBusinessDepartments(selectedItems, function(selectedOrders, POSCustomerBusinessDepartmentId){
theThis.importOrdersToCTB(POSCustomerBusinessDepartmentId, selectedOrders);
});
}
else {
Ext.Msg.show({
title:'Notice',
msg: 'Please select at least one order to transfer ?',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
}
}
}),
theThis.btn_Show_AutoTransfer = new Ext.Button({
iconCls: 'icon-move-right',
text: 'Setup Auto-Transfer',
tooltip : 'Setup Auto-Transfer Kounta\'s orders to Cooking the Books',
scale : 'large',
handler: function() {
theThis.getAutoTransferConfigurationWindow();
}
}),
// theThis.btn_Auto_Transfer = new Ext.Button({
// iconCls: 'icon-move-right',
// text: 'Setup Auto-Transfer',
// tooltip : 'Setup Auto-Transfer Kounta\'s orders to Cooking the Books',
// scale : 'large',
// handler: function ()
// }),
theThis.btn_ShowExportedInvoice = new Ext.Button({
iconCls: 'icon-visible',
enableToggle : true,
hidden : true,
text: 'Show exported invoices',
tooltip : 'Show all the invoices included the invoices has been exported to Xero before.',
scale : 'large',
toggleHandler : function(p_Button, p_State){
Ext.apply(theThis.store_Invoice.baseParams,
{
start : 0,
limit : theThis.getPagingToolbar().pageSize,
isShowExported : p_State
});
theThis.store_Invoice.load();
if (p_State) p_Button.setText('Hide exported invoices');
else p_Button.setText('Show exported invoices');
}
}),
'-',
theThis.btn_Invoice_StopSearch = new Ext.Button({
xtype : 'button',
iconCls : 'icon-stop-search',
handler : function(){
theThis.store_Invoice.commitChanges();
//store_Invoice.baseParams = {start : 0, limit : theThis.pageSize};
Ext.apply(theThis.store_Invoice.baseParams,
{
keyword : "",
searchType : -1,
start : 0,
limit : theThis.pt_Invoice.pageSize
});
theThis.store_Invoice.load();
}
}),
theThis.txt_Invoice_SearchInvoiceValue = new Ext.form.TextField({
emptyText : 'Search value ...',
listeners: {
specialkey: function(f,e){
if (e.getKey() == e.ENTER) {
theThis.btn_Invoice_SearchInvoice.handler.call(theThis.btn_Invoice_SearchInvoice.scope);
}
}
}
}),
theThis.lbl_Invoice_SearchInvoiceDateFrom = new Ext.form.Label({
xtype : 'label',
text : "From :",
hidden : true
}),' ',
theThis.txt_Invoice_SearchInvoiceDateFrom = new Ext.form.DateField({
xtype : 'datefield',
format : "j/n/Y",
altFormats : 'j/n/y',
value : new Date(),
hidden : true,
width : 200
}),' ',
theThis.lbl_Invoice_SearchInvoiceDateTo = new Ext.form.Label({
xtype : 'label',
text : "To :",
hidden : true
}),' ',
theThis.txt_Invoice_SearchInvoiceDateTo = new Ext.form.DateField({
xtype : 'datefield',
format : "j/n/Y",
altFormats : 'j/n/y',
value : new Date(),
hidden : true,
width : 200
}),
' ',
cmb_SearchInvoice,
theThis.btn_Invoice_SearchInvoice = new Ext.Button({
iconCls : 'icon-search-large', scale : 'large',
text : 'Search',
handler : function(){
theThis.store_Invoice.commitChanges();
var searchType = cmb_SearchInvoice.getValue();
var searchValue;
if (searchType == 1 || searchType == 3)
{
searchValue = theThis.txt_Invoice_SearchInvoiceValue.getValue();
}
else if (searchType == 2) {
// Get the From Date
var fromDate = theThis.txt_Invoice_SearchInvoiceDateFrom.getValue();
fromDate = Ext.util.JSON.encode(fromDate).replace(/"/g, '');
// Get the To Date
var toDate = theThis.txt_Invoice_SearchInvoiceDateTo.getValue();
toDate = Ext.util.JSON.encode(toDate).replace(/"/g, '');
searchValue = fromDate + ";" + toDate;
}
if (searchType == "")
{
Ext.Msg.show({
title:'Notice',
msg: 'Please choose a search type !',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
}
else {
// Send search request
theThis.store_Invoice.commitChanges();
// store_Invoice.baseParams = {keyword : searchValue, searchType : searchType, start : 0, limit : theThis.pageSize};
Ext.apply(theThis.store_Invoice.baseParams,
{
keyword : searchValue,
searchType : searchType,
start : 0,
limit : theThis.pt_Invoice.pageSize
});
theThis.store_Invoice.load();
}
}
}),
theThis.btn_Invoice_FilterConfiguration = new Ext.Button({
iconCls : 'icon-search-large', scale : 'large',
text : 'Filter Configuration',
handler : function(){
theThis.setFilterCondition();
}
})
],
cm: stockCM,
width: 780,
height: 400,
autoHeight: false,
clicksToEdit: 1,
loadMask: true,
bbar:
theThis.pt_Invoice = new Ext.CTBPagingToolbar({
store: theThis.store_Invoice,
pageSize: theThis.pageSize,
displayInfo: true,
emptyMsg: "No orders to display"
})
,
viewConfig:
{
enableRowBody: true,
forceFit: true // IMPORTANT (USE THIS ATTRIBUTE TO USE PERCENTAGE IN COLUMN MODEL)
}
});
grid_Invoice.on({
rowcontextmenu: function (grid, rowIndex, e) {
e.stopEvent();
var row = grid.getView().getRow(rowIndex);
Ext.get(row).highlight();
invoiceSm.selectRow(rowIndex);
}
});
return grid_Invoice;
}, // End generateGrid_Databases
setFilterCondition: function(){
var theThis = this;
Ext.Ajax.request({
method: 'POST',
url: '/Kounta/GetIntegrationConfiguration',
success: function(result, request) {
var jsonData = Ext.decode(result.responseText);
var dataObj = jsonData.data;
var filterOption = null;
if(dataObj != null)
{
filterOption = {
siteId: dataObj.siteId,
siteName: dataObj.siteName,
categories: dataObj.categories,
};
theThis.ctbCountaSelectSitesForConfigurationWindow.setPreloadData(filterOption);
}
theThis.ctbCountaSelectSitesForConfigurationWindow.showSelectCategoryWindow(function(siteId, siteName, categories){
var integrationConfiguration = {
siteId: siteId,
siteName: siteName,
categories: categories
};
Ext.Ajax.request({
method: 'POST',
url: '/Kounta/SaveIntegrationConfiguration',
params: {
integrationConfiguration: Ext.encode(integrationConfiguration)
},
success: function(result, request) {
//console.log(result.responseText);
//dlg_setup.close();
var jsonData = Ext.decode(result.responseText);
if(jsonData.message.IsSuccess) {
showSuccessNotification(jsonData.message.Info);
}
else {
showErrorNotification('Error', jsonData.message.Info);
}
},
failure: function(result, request) {
//dlg_setup.close();
showErrorNotification('Error', 'Cannot setup the process, please try again. Error: ' + result.responseText);
}
});
});
},
failure: function(result, request) {
//dlg_setup.close();
showErrorNotification('Error', 'Cannot setup the process, please try again. Error: ' + result.responseText);
}
});
},// END setFilterCondition
importOrdersToCTB : function(POSCustomerBusinessDepartmentId, selectedRecords){
var theThis = this;
var selectedOrderIds = new Array();
for (var i = 0; i < selectedRecords.length; i++) {
selectedOrderIds[i] = selectedRecords[i].data.id;
}
theThis.loadMask.show();
Ext.Ajax.request({
method: "POST",
url: '/Kounta/ImportOrdersToCTB',
timeout: 1800000,
params:
{
POSCustomerBusinessDepartmentId : POSCustomerBusinessDepartmentId,
selectedOrderIds : Ext.util.JSON.encode(selectedOrderIds)
},
success : function(result, request) {
theThis.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification('The selected orders have been transferred to Kounta.', NOTIFICATION.ICON_INFORMATION);
}
else {
//showErrorMessageWithEmailNotify(jsonData.message.Info);
showErrorNotification('Notice', jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.loadMask.hide();
}
}); // End ajax
}, // End generateGrid_Databases
getPOSIntegratedBusinessDepartments : function(selectedOrders, callback_Function){
var theThis = this;
theThis.loadMask.show();
Ext.Ajax.request({
method: "POST",
url: '/Kounta/GetPOSIntegratedBusinessDepartments',
timeout: 1800000,
params:
{
},
success : function(result, request) {
theThis.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
if (jsonData.data != null && jsonData.data.length > 0) {
if (jsonData.data.length > 1) { // More than 2
for(var i=0; i 0) d.businessDepartmentName += ' - ' + d.outletName;
}
var dlg_BusinessDepartmentSelector = new Ext.Window({
title : 'Select a business department',
closeAction: 'close',
iconCls : 'icon-v3-ctb-logo',
cls : 'ctbwindow-detail-general',
width:390,
height: 150,
modal : true,
callback_AfterSelect : null,
defaultPOSCustomerBusinessDepartmentId : jsonData.data[0].POSCustomerBusinessDepartmentId,
items : [
new Ext.form.FormPanel ({
region : 'center',
frame : true,
items : [
new Ext.form.ComboBox({
store: new Ext.data.ArrayStore({
fields: [
{name: 'POSCustomerBusinessDepartmentId', type: 'number'},
{name: 'businessDepartmentId', type: 'number'},
{name: 'businessDepartmentName', type: 'string'}
]
}),
fieldLabel: 'Business Department',
displayField: 'businessDepartmentName',
valueField: 'POSCustomerBusinessDepartmentId',
mode : 'local',
editable : false,
allowBlank : false,
emptyText : 'Select a business department ...',
typeAhead: true,
triggerAction: 'all',
lazyRender: true,
width : 200,
listeners : {
afterrender : function(p_This){
var data = new Array();
for (var i = 0; i < jsonData.data.length; i++) {
data[i] = [jsonData.data[i].POSCustomerBusinessDepartmentId, jsonData.data[i].businessDepartmentId, jsonData.data[i].businessDepartmentName];
}
p_This.getStore().loadData(data);
p_This.setValue(dlg_BusinessDepartmentSelector.defaultPOSCustomerBusinessDepartmentId);
dlg_BusinessDepartmentSelector.cmb_BusinessDepartments = p_This;
}
}
})
]
})
],
buttons : [
new Ext.Button({
text: 'Select',
iconCls : 'icon-ok-large', scale : 'large',
handler : function(){
if (!dlg_BusinessDepartmentSelector.cmb_BusinessDepartments.isValid() || dlg_BusinessDepartmentSelector.cmb_BusinessDepartments.getValue() == '') {
showErrorNotification('Notice', 'Please select a valid department');
}
else {
var POSCustomerBusinessDepartmentId = dlg_BusinessDepartmentSelector.cmb_BusinessDepartments.getValue();
//need to check whether it works
var businessDepartmentName = dlg_BusinessDepartmentSelector.cmb_BusinessDepartments.getRawValue();//.getText();
if (callback_Function != null) {
callback_Function(selectedOrders, POSCustomerBusinessDepartmentId, businessDepartmentName);
}
dlg_BusinessDepartmentSelector.hide();
}
}
}),
new Ext.Button({
text: 'Cancel',
iconCls : 'icon-cancel-large', scale : 'large',
handler : function(){
dlg_BusinessDepartmentSelector.hide();
}
})
]
});
dlg_BusinessDepartmentSelector.show();
}
else if (jsonData.data.length == 1) {
var POSCustomerBusinessDepartmentId = jsonData.data[0].POSCustomerBusinessDepartmentId;
var businessDepartmentName = jsonData.data[0].businessDepartmentName;
if (callback_Function != null) {
callback_Function(selectedOrders, POSCustomerBusinessDepartmentId, businessDepartmentName);
}
}
}
else {
showErrorNotification('Error', 'Cannot find deparment information. Please setup a department first.');
}
}
else {
showErrorNotification('Notice', jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.loadMask.hide();
showErrorNotification('Error', result.responseText);
}
}); // End ajax
},
getAutoTransferConfigurationWindow: function() {
var theThis = this;
var tpl = new Ext.XTemplate(
'Current settings for auto-transfer sales data from Kounta ',
'',
'',
'# ',
'Business Department ',
'Site from Kounta ',
'Selected Categories ',
' ',
' ',
'',
'',
'{[xindex]} ',
'{posDepartmentName} ',
'{siteName} ',
'',
'',
'{id}: {name} ',
' ',
' ',
'Delete ',
' ',
' ',
'
'
);
var store = new Ext.data.JsonStore({
autoLoad : false,
baseParams : {start : 0, limit : theThis.pageSize},
proxy: new Ext.data.HttpProxy({
url: '/Kounta/GetAutoTransferConfiguration',
dataType: 'json',
method: 'POST'
}),
root: 'data',
fields: [
{ name: 'connectionId', type: 'number' },
{ name: 'posDepartmentId', type: 'number' },
{ name: 'posDepartmentName', type: 'string' },
{ name: 'optionsJson', type: 'object' }
],
idProperty : 'connectionId',
listeners: {
load: function(store, records, options) {
var connections = [];
for(var i=0; i' + siteName + '';
html += ' to department: ';
html += ''+ businessDepartmentName + ' ?';
html += ' After this process has been configured, your sales orders will be transfered from Kounta into Cooking the Books automatically on daily basis.';
var dlg_setup = new Ext.Window({
title: 'Confirmation',
iconCls : 'icon-v3-ctb-logo',
cls : 'ctbwindow-detail-general',
width: 400,
height: 250,
modal: true,
frame: true,
html: html,
buttons: [
{
text: 'OK',
handler: function() {
Ext.Ajax.request({
method: 'POST',
url: '/Kounta/SetupAutoTransfer',
params: {
POSCustomerBusinessDepartmentId: POSCustomerBusinessDepartmentId,
kountaSiteId: siteId,
kountaSiteName: siteName,
categories: Ext.encode(categories)
},
success: function(result, request) {
//console.log(result.responseText);
dlg_setup.close();
var jsonData = Ext.decode(result.responseText);
if(jsonData.message.IsSuccess) {
showSuccessNotification(jsonData.message.Info);
}
else {
showErrorNotification('Error', jsonData.message.Info);
}
},
failure: function(result, request) {
dlg_setup.close();
showErrorNotification('Error', 'Cannot setup the process, please try again. Error: ' + result.responseText);
}
});
}
},
{
text: 'Cancel',
handler: function() {
dlg_setup.close();
}
}
]
});
dlg_setup.show();
}); //end select business department
}); //end select Kounta site
}
});
Ext.reg('CTBXeroTransferInvoice', Ext.CTBXeroTransferInvoice);
Ext.CTBBoard_FoodCostLiveCalendar = Ext.extend(Ext.Window, {
title: 'Food cost - Live Calendar',
layout: 'border',
closeAction: 'hide',
iconCls : 'icon-v3-ctb-logo',
cls : 'ctbwindow-black-bg',
expandOnShow : true,
closable: true,
resizable: true,
modal: true,
plain: true,
minimizable : true,
maximizable : true,
monitorResize : true,
width:800,
height:500,
defaults: {
split: true,
animFloat: false,
autoHide: false,
useSplitTips: true
},
listeners : {
scope : this,
'beforehide' : function(theThis){
},
'beforeshow' : function(theThis){
// Fit this window to the client browser screen with 90%
fitWindowSize(theThis, 90);
},
'show' : function(theThis){
var today = new Date();
theThis.loadData(today.getMonth() + 1, today.getFullYear());
}
},
initComponent : function(){
var theThis = this;
// MAIN GRID
theThis.pnl_LiveCalendar = theThis.getPanel_LiveCalendar();
theThis.cmb_Month = theThis.getCombobox_Month();
theThis.cmb_Year = theThis.getCombobox_Year();
theThis.btn_LoadData = new Ext.Button({
iconCls : 'icon-stop-search',
//text : 'Load data',
tooltip : 'Click to reload data',
handler : function(){
theThis.loadData(theThis.cmb_Month.getValue(), theThis.cmb_Year.getValue());
}
});
theThis.pnl_Main = new Ext.Panel({
layout : 'border',
region : 'center',
frame : false,
tbar : ['-', theThis.cmb_Month, '-', theThis.cmb_Year, '-', theThis.btn_LoadData],
items : [theThis.pnl_LiveCalendar]
});
theThis.items = [theThis.pnl_Main];
// BUTTONS
var myButtons = theThis.initButtons();
this.buttons = myButtons;
this.initTools();
Ext.CTBBoard_FoodCostLiveCalendar.superclass.initComponent.call(this);
},
loadData : function(month, year){
var theThis = this;
theThis.loadMask.show();
Ext.Ajax.request({
method: 'POST',
url: '/Invoice/GetBoard_FoodCostLiveCalendar',
params:
{
month : month,
year : year
},
success : function(result, request) {
theThis.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
theThis.cmb_Month.setValue(jsonData.data.month);
theThis.cmb_Year.setValue(jsonData.data.year);
theThis.tpl_LiveCalendar.overwrite(theThis.pnl_LiveCalendar.body, jsonData.data);
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.loadMask.hide();
}
});
},
getPanel_LiveCalendar : function(){
var theThis = this;
var str_TemplateBuilder = '';
str_TemplateBuilder +=
''+
'July 2011
'+
''+
'
';
// Loop to create calendar
for (var rowIndex = 0; rowIndex < 5; rowIndex++){
str_TemplateBuilder += '';
for (var colIndex = 0; colIndex < 7; colIndex++){
str_TemplateBuilder += '' +
'' +
'' +
'' +
(rowIndex == 0 ? 'Sun 26' : '15')+
' ' +
' ' +
'' +
'' +
'Daily Food Cost33.22% ' +
' {extraCellInfo_' + rowIndex + '_' + colIndex + '}' +
' ' +
' ' +
'
' +
' ';
}
str_TemplateBuilder += ' ';
}
str_TemplateBuilder +=
'
'+
'
'+
' ';
// Create template container
theThis.tpl_LiveCalendar = new Ext.XTemplate(
'',
//'{headerInfo}
',
'',
'
',
'',
'',
'',
'#575f4b#c4df9b ">',
'',
'',
'',
' ',
'{timeInfo} ',
' ',
' ',
'',
'',
' ',
'',
'Daily Food Cost{dailyFoodCost}% ',
'{extraCellInfo}',
' ',
' ',
' ',
'
',
' ',
' ',
' ',
' ',
'
',
'
',
' '
);
var pnl_LiveCalendar = new Ext.Panel({
region : 'center',
frame : false,
bodyBorder : false,
autoScroll : true,
tpl : theThis.tpl_LiveCalendar,
listeners : {
afterrender : function(p_This){
theThis.loadMask = new Ext.LoadMask(p_This.getEl(), {msg:"Please wait..."});
}
}
});
return pnl_LiveCalendar;
},
getCombobox_Month : function(){
var data = [
['January', 1],
['February', 2],
['March', 3],
['April', 4],
['May', 5],
['June', 6],
['July', 7],
['August', 8],
['September', 9],
['October', 10],
['November', 11],
['December', 12]
];
var cmb = new Ext.form.ComboBox({
store: new Ext.data.ArrayStore({
fields: [
{name: 'monthText'},
{name: 'monthNumber', type: 'int'}
],
data : data
}),
width : 150,
displayField: 'monthText',
valueField: 'monthNumber',
typeAhead: true,
editable: false,
triggerAction: 'all',
lazyRender: true,
mode: 'local',
emptyText: 'Month...'
});
return cmb;
},
getCombobox_Year : function(){
// Get the current year
var today = new Date();
var currentYear = today.getFullYear();
var data = [
[currentYear - 9, currentYear - 9],
[currentYear - 8, currentYear - 8],
[currentYear - 7, currentYear - 7],
[currentYear - 6, currentYear - 6],
[currentYear - 5, currentYear - 5],
[currentYear - 4, currentYear - 4],
[currentYear - 3, currentYear - 3],
[currentYear - 2, currentYear - 2],
[currentYear - 1, currentYear - 1],
[currentYear, currentYear]
];
var cmb = new Ext.form.ComboBox({
store: new Ext.data.ArrayStore({
fields: [
{name: 'yearText'},
{name: 'yearNumber', type: 'int'}
],
data : data
}),
width : 80,
displayField: 'yearText',
valueField: 'yearNumber',
typeAhead: true,
editable: false,
triggerAction: 'all',
lazyRender: true,
mode: 'local',
emptyText: 'Year...'
});
return cmb;
},
initButtons : function(){
var theThis = this;
var buttons = [
/*theThis.btn_Cancel = new Ext.Button({
text: 'Cancel',
iconCls : 'icon-cancel-large', scale : 'large',
handler : function(){
theThis.hide();
}
})*/
];
return buttons;
}
});
Ext.reg('CTBBoard_FoodCostLiveCalendar', Ext.CTBBoard_FoodCostLiveCalendar);
function changeCardLayoutByTimeInterval(containerId, timeInterval){
setTimeout(function(){
var container = Ext.getCmp(containerId);
var currentIndex = container.items.indexOf(container.layout.activeItem);
var nextIndex = currentIndex + 1 == container.items.length ? 0 : currentIndex + 1;
container.layout.setActiveItem(nextIndex);
changeCardLayoutByTimeInterval(containerId, timeInterval);
}, timeInterval);
}
Ext.CTBBoard_InvoiceFoodCost = Ext.extend(Ext.Panel, {
layout : 'border',
title : 'Live Food Cost: based on Purchases to Sales',
loadMask: null,
timeInterval : 3000,
stopSlide : true,
weekIndex : 0,
pageSize: CTB.init.itemPerPage || 100,
startDayOfTheWeek : DAY_SELECTION.MONDAY,
stocktakeDate : null,
listeners : {
afterrender : function(theThis){
// Init loadMask
theThis.loadMask = new Ext.LoadMask(this.getEl(), {msg:"Please wait..."});
theThis.changeSlide();
}
},
changeSlide : function() {
var theThis = this;
setTimeout(function(){
if (!theThis.stopSlide) {
theThis.moveToNextSlide();
theThis.changeSlide();
}
}, theThis.timeInterval);
//changeCardLayoutByTimeInterval(theThis.pnl_LiveFoodCost.id, theThis.timeInterval);
},
moveToNextSlide : function(){
var theThis = this;
var container = theThis.pnl_LiveFoodCost;
var currentIndex = container.items.indexOf(container.layout.activeItem);
var nextIndex = currentIndex + 1 == container.items.length ? 0 : currentIndex + 1;
container.layout.setActiveItem(nextIndex);
theThis.setTitle(container.layout.activeItem.titleDescription);
},
getDialogSelectDate : function(){
var theThis = this;
var buttons = [];
var buttons_text = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
for (var i = 0; i < buttons_text.length; i++){
buttons[i] = new Ext.Button({
text : buttons_text[i],
scale : 'large',
width : 100,
height : 30,
dateIndex : i,
handler : function(){
theThis.startDayOfTheWeek = this.dateIndex;
theThis.cookieProvider.set("startDayOfTheWeek", theThis.startDayOfTheWeek);
theThis.loadData();
theThis.dlg_SelectDate.hide();
}
});
}
var dlg_SelectDate = new Ext.Window({
buttons : buttons,
modal : true,
closeAction : 'hide',
resizable : false,
title : 'Select date',
width : 770,
height : 0
});
return dlg_SelectDate;
},
loadData : function(){
var theThis = this;
theThis.loadMask.show();
Ext.Ajax.request({
method: 'POST',
url: '/Invoice/GetBoard_InvoiceFoodCost',
params:
{
weekIndex : theThis.weekIndex,
startDayOfTheWeek : theThis.startDayOfTheWeek,
stocktakeDate : theThis.stocktakeDate
},
success : function(result, request) {
theThis.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
var weekdays = jsonData.data.weekdays;
for (var i = 0; i < weekdays.length; i++){
weekdays[i].foodCostOfTheDate = weekdays[i].kitchenRevenueOfTheDate == 0 ? '0.00' : addFullDigitToNumber(roundNumber(weekdays[i].purchaseOfTheDate / weekdays[i].kitchenRevenueOfTheDate * 100, 2), 2),
weekdays[i].purchaseOfTheDate = addFullDigitToNumber(roundNumber(weekdays[i].purchaseOfTheDate, 2), 2);
weekdays[i].kitchenRevenueOfTheDate = addFullDigitToNumber(roundNumber(weekdays[i].kitchenRevenueOfTheDate, 2), 2);
}
var wrapperData = {
uniqueId : theThis.id,
weekdays : weekdays,
stocktakeDate : jsonData.data.stocktakeDate,
endDateOfTheWeek : jsonData.data.endDateOfTheWeek,
purchaseToday : addFullDigitToNumber(roundNumber(jsonData.data.purchaseToday, 2), 2),
purchaseYesterday : addFullDigitToNumber(roundNumber(jsonData.data.purchaseYesterday, 2), 2),
purchaseThisWeek : addFullDigitToNumber(roundNumber(jsonData.data.purchaseThisWeek, 2), 2),
purchaseThisMonth : addFullDigitToNumber(roundNumber(jsonData.data.purchaseThisMonth, 2), 2),
purchaseThisYear : addFullDigitToNumber(roundNumber(jsonData.data.purchaseThisYear, 2), 2),
purchaseFromLastStocktake : addFullDigitToNumber(roundNumber(jsonData.data.purchaseFromLastStocktake, 2), 2),
purchaseMonthUntilEndOfWeekDate : addFullDigitToNumber(roundNumber(jsonData.data.purchaseMonthUntilEndOfWeekDate, 2), 2),
purchaseYearUntilEndOfWeekDate : addFullDigitToNumber(roundNumber(jsonData.data.purchaseYearUntilEndOfWeekDate, 2), 2),
kitchenRevenueToday : addFullDigitToNumber(roundNumber(jsonData.data.kitchenRevenueToday, 2), 2),
kitchenRevenueYesterday : addFullDigitToNumber(roundNumber(jsonData.data.kitchenRevenueYesterday, 2), 2),
kitchenRevenueThisWeek : addFullDigitToNumber(roundNumber(jsonData.data.kitchenRevenueThisWeek, 2), 2),
kitchenRevenueThisMonth : addFullDigitToNumber(roundNumber(jsonData.data.kitchenRevenueThisMonth, 2), 2),
kitchenRevenueThisYear : addFullDigitToNumber(roundNumber(jsonData.data.kitchenRevenueThisYear, 2), 2),
kitchenRevenueFromLastStocktake : addFullDigitToNumber(roundNumber(jsonData.data.kitchenRevenueFromLastStocktake, 2), 2),
kitchenRevenueMonthUntilEndOfWeekDate : addFullDigitToNumber(roundNumber(jsonData.data.kitchenRevenueMonthUntilEndOfWeekDate, 2), 2),
kitchenRevenueYearUntilEndOfWeekDate : addFullDigitToNumber(roundNumber(jsonData.data.kitchenRevenueYearUntilEndOfWeekDate, 2), 2),
foodCostToday : jsonData.data.kitchenRevenueToday == 0 ? '0.00' : addFullDigitToNumber(roundNumber(jsonData.data.purchaseToday / jsonData.data.kitchenRevenueToday * 100, 2), 2),
foodCostYesterday : jsonData.data.kitchenRevenueYesterday == 0 ? '0.00' : addFullDigitToNumber(roundNumber(jsonData.data.purchaseYesterday / jsonData.data.kitchenRevenueYesterday * 100, 2), 2),
foodCostThisWeek : jsonData.data.kitchenRevenueThisWeek == 0 ? '0.00' : addFullDigitToNumber(roundNumber(jsonData.data.purchaseThisWeek / jsonData.data.kitchenRevenueThisWeek * 100, 2), 2),
foodCostThisMonth : jsonData.data.kitchenRevenueThisMonth == 0 ? '0.00' : addFullDigitToNumber(roundNumber(jsonData.data.purchaseThisMonth / jsonData.data.kitchenRevenueThisMonth * 100, 2), 2),
foodCostThisYear : jsonData.data.kitchenRevenueThisYear == 0 ? '0.00' : addFullDigitToNumber(roundNumber(jsonData.data.purchaseThisYear / jsonData.data.kitchenRevenueThisYear * 100, 2), 2),
foodCostFromLastStocktake : jsonData.data.kitchenRevenueFromLastStocktake == 0 ? '0.00' : addFullDigitToNumber(roundNumber(jsonData.data.purchaseFromLastStocktake / jsonData.data.kitchenRevenueFromLastStocktake * 100, 2), 2),
foodCostMonthUntilEndOfWeekDate : jsonData.data.kitchenRevenueMonthUntilEndOfWeekDate == 0 ? '0.00' : addFullDigitToNumber(roundNumber(jsonData.data.purchaseMonthUntilEndOfWeekDate / jsonData.data.kitchenRevenueMonthUntilEndOfWeekDate * 100, 2), 2),
foodCostYearUntilEndOfWeekDate : jsonData.data.kitchenRevenueYearUntilEndOfWeekDate == 0 ? '0.00' : addFullDigitToNumber(roundNumber(jsonData.data.purchaseYearUntilEndOfWeekDate / jsonData.data.kitchenRevenueYearUntilEndOfWeekDate * 100, 2), 2)
};
theThis.pnl_FoodCostTable.update(wrapperData);
if (Ext.get(theThis.id + '_SelectStartDateOfTheWeek') != null){
Ext.get(theThis.id + '_SelectStartDateOfTheWeek').on('click', function(){
theThis.dlg_SelectDate.show();
});
}
if (Ext.get(theThis.id + '_SelectStocktakeDate') != null){
Ext.get(theThis.id + '_SelectStocktakeDate').on('click', function(){
if (theThis.dlg_StocktakeDateSelector == null) {
theThis.dlg_StocktakeDateSelector = new Ext.CTBStocktakeDateRangeSelectorDialog({
title: 'Please select a stocktake date',
isForSelectSingleDate : true
});
}
theThis.dlg_StocktakeDateSelector.callback_AfterSelect = function(startDate, endDate) {
theThis.stocktakeDate = startDate;
theThis.loadData();
}
theThis.dlg_StocktakeDateSelector.show();
});
}
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.loadMask.hide();
}
});
},
initComponent: function(){
var theThis = this;
theThis.cookieProvider = new Ext.state.CookieProvider;
if (theThis.cookieProvider.get("startDayOfTheWeek") != null){
theThis.startDayOfTheWeek = theThis.cookieProvider.get("startDayOfTheWeek");
}
theThis.pnl_LiveFoodCost = theThis.getPanel_LiveFoodCost();
//theThis.pnl_ExtraButtons = theThis.getPanel_ExtraButtons();
theThis.pnl_TopButtons = theThis.getPanel_TopButtons();
theThis.dlg_SelectDate = theThis.getDialogSelectDate();
theThis.dlg_FoodCostLiveCalendar = new Ext.CTBBoard_FoodCostLiveCalendar({
});
theThis.dlg_FoodCostPredictor = new Ext.CTBFoodCostPredictorWindow({
});
theThis.items = [theThis.pnl_LiveFoodCost, theThis.pnl_TopButtons];//, theThis.pnl_ExtraButtons];
// Call super class to initialize componenets
Ext.CTBBoard_InvoiceFoodCost.superclass.initComponent.call(this);
},
getPanel_LiveFoodCost : function(){
var theThis = this;
theThis.pnl_FoodCostTable = theThis.getPanel_FoodCostTable();
theThis.chart_DailyFoodCost = theThis.getChart_DailyFoodCost(0, 'Current Week - Food Cost');
theThis.chart_PreviousWeekFoodCost = theThis.getChart_DailyFoodCost(-1, 'Previous Week - Food Cost');
theThis.chart_2WeeksBeforeFoodCost = theThis.getChart_DailyFoodCost(-2, 'Two weeks before - Food Cost');
theThis.chart_3WeeksBeforeFoodCost = theThis.getChart_DailyFoodCost(-3, 'Three weeks before - Food Cost');
theThis.chart_MonthFoodCost = theThis.getChart_MonthFoodCost();
theThis.chart_YearFoodCost = theThis.getChart_YearFoodCost();
var pnl_LiveFoodCost = new Ext.Panel({
region : 'center',
layout : 'card',
/*tbar : new Ext.Toolbar({
buttonAlign : 'center',
items : [
theThis.btn_PreviousWeek = new Ext.Button({
text : 'Previous Week ',
scale : 'large',
iconCls : 'icon-calendar-previous',
handler : function(){
theThis.stopSlide = true;
theThis.weekIndex--;
theThis.pnl_LiveFoodCost.layout.setActiveItem(theThis.pnl_FoodCostTable);
theThis.setTitle(theThis.pnl_FoodCostTable.titleDescription);
theThis.loadData();
}
}),
theThis.btn_3WeeksBefore = new Ext.Button({
text : '3 Weeks Before ',
scale : 'large',
iconCls : 'icon-calendar',
handler : function(){
theThis.stopSlide = true;
theThis.weekIndex = -3;
theThis.pnl_LiveFoodCost.layout.setActiveItem(theThis.pnl_FoodCostTable);
theThis.setTitle(theThis.pnl_FoodCostTable.titleDescription);
theThis.loadData();
}
}),
theThis.btn_2WeeksBefore = new Ext.Button({
text : '2 Weeks Before ',
scale : 'large',
iconCls : 'icon-calendar',
handler : function(){
theThis.stopSlide = true;
theThis.weekIndex = -2;
theThis.pnl_LiveFoodCost.layout.setActiveItem(theThis.pnl_FoodCostTable);
theThis.setTitle(theThis.pnl_FoodCostTable.titleDescription);
theThis.loadData();
}
}),
theThis.btn_CurrentWeek = new Ext.Button({
text : 'Current Week ',
scale : 'large',
iconCls : 'icon-calendar',
handler : function(){
theThis.stopSlide = true;
theThis.weekIndex = 0;
theThis.pnl_LiveFoodCost.layout.setActiveItem(theThis.pnl_FoodCostTable);
theThis.setTitle(theThis.pnl_FoodCostTable.titleDescription);
theThis.loadData();
}
}),
theThis.btn_NextWeek = new Ext.Button({
text : 'Next Week ',
scale : 'large',
iconCls : 'icon-calendar-next',
handler : function(){
theThis.stopSlide = true;
theThis.weekIndex++;
theThis.pnl_LiveFoodCost.layout.setActiveItem(theThis.pnl_FoodCostTable);
theThis.setTitle(theThis.pnl_FoodCostTable.titleDescription);
theThis.loadData();
}
}),
theThis.btn_Daily = new Ext.Button({
text : 'Daily ',
scale : 'large',
iconCls : 'icon-graph',
handler : function(){
theThis.stopSlide = true;
theThis.store_DailyFoodCost.baseParams.weekIndex = theThis.weekIndex;
theThis.store_DailyFoodCost.baseParams.startDayOfTheWeek = theThis.startDayOfTheWeek;
theThis.store_DailyFoodCost.load();
theThis.pnl_LiveFoodCost.layout.setActiveItem(theThis.chart_DailyFoodCost);
theThis.setTitle(theThis.chart_DailyFoodCost.titleDescription);
}
}),
theThis.btn_Monthly = new Ext.Button({
text : 'Monthly ',
scale : 'large',
iconCls : 'icon-graph',
handler : function(){
theThis.stopSlide = true;
theThis.pnl_LiveFoodCost.layout.setActiveItem(theThis.chart_MonthFoodCost);
theThis.setTitle(theThis.chart_MonthFoodCost.titleDescription);
}
}),
theThis.btn_Yearly = new Ext.Button({
text : 'Yearly ',
scale : 'large',
iconCls : 'icon-graph',
handler : function(){
theThis.stopSlide = true;
theThis.pnl_LiveFoodCost.layout.setActiveItem(theThis.chart_YearFoodCost);
theThis.setTitle(theThis.chart_YearFoodCost.titleDescription);
}
})
]
}),*/
activeItem : 0,
items : [
theThis.pnl_FoodCostTable,
theThis.chart_3WeeksBeforeFoodCost,
theThis.chart_2WeeksBeforeFoodCost,
theThis.chart_PreviousWeekFoodCost,
theThis.chart_DailyFoodCost,
theThis.chart_MonthFoodCost,
theThis.chart_YearFoodCost
],
listeners : {
afterrender : function(p_This){
}
}
});
return pnl_LiveFoodCost;
},
getPanel_TopButtons : function(){
var theThis = this;
theThis.tpl_TopButtons = new Ext.XTemplate(
'',
'',
'
',
'',
'',
'View ',
' ',
'',
'
',
' ',
'',
'See live food cost calendar
',
' ',
'',
'See food cost predictor
',
' ',
'',
' ',
' ',
' ',
'
',
'
',
' '
);
var pnl_TopButtons = new Ext.Panel({
region : 'north',
frame : false,
height : 25,
tpl : theThis.tpl_TopButtons,
activeMenuButton : 'Current week',
listeners : {
afterrender : function(p_This){
theThis.pnl_TopButtons.update({uniqueId : theThis.id});
// View options button
Ext.get(String.format('{0}btn_ViewOptions', theThis.id)).on('click', function(e){
p_This.menu_ViewOptions = new Ext.menu.Menu({
items:
[
{
iconCls: p_This.activeMenuButton == 'Previous week' ? 'icon-v3-menu-tick' : 'no-icon',
text: 'Previous week',
handler: function (p_ThisButton) {
p_This.activeMenuButton = p_ThisButton.text;
theThis.stopSlide = true;
theThis.weekIndex--;
theThis.pnl_LiveFoodCost.layout.setActiveItem(theThis.pnl_FoodCostTable);
theThis.setTitle(theThis.pnl_FoodCostTable.titleDescription);
theThis.loadData();
}
},
{
iconCls: p_This.activeMenuButton == '3 weeks before' ? 'icon-v3-menu-tick' : 'no-icon',
text: '3 weeks before',
handler: function (p_ThisButton) {
p_This.activeMenuButton = p_ThisButton.text;
theThis.stopSlide = true;
theThis.weekIndex = -3;
theThis.pnl_LiveFoodCost.layout.setActiveItem(theThis.pnl_FoodCostTable);
theThis.setTitle(theThis.pnl_FoodCostTable.titleDescription);
theThis.loadData();
}
},
{
iconCls: p_This.activeMenuButton == '2 weeks before' ? 'icon-v3-menu-tick' : 'no-icon',
text: '2 weeks before',
handler: function (p_ThisButton) {
p_This.activeMenuButton = p_ThisButton.text;
theThis.stopSlide = true;
theThis.weekIndex = -2;
theThis.pnl_LiveFoodCost.layout.setActiveItem(theThis.pnl_FoodCostTable);
theThis.setTitle(theThis.pnl_FoodCostTable.titleDescription);
theThis.loadData();
}
},
{
iconCls: p_This.activeMenuButton == 'Current week' ? 'icon-v3-menu-tick' : 'no-icon',
text: 'Current week',
handler: function (p_ThisButton) {
p_This.activeMenuButton = p_ThisButton.text;
theThis.stopSlide = true;
theThis.weekIndex = 0;
theThis.pnl_LiveFoodCost.layout.setActiveItem(theThis.pnl_FoodCostTable);
theThis.setTitle(theThis.pnl_FoodCostTable.titleDescription);
theThis.loadData();
}
},
{
iconCls: p_This.activeMenuButton == 'Next week' ? 'icon-v3-menu-tick' : 'no-icon',
text: 'Next week',
handler: function (p_ThisButton) {
p_This.activeMenuButton = p_ThisButton.text;
theThis.stopSlide = true;
theThis.weekIndex++;
theThis.pnl_LiveFoodCost.layout.setActiveItem(theThis.pnl_FoodCostTable);
theThis.setTitle(theThis.pnl_FoodCostTable.titleDescription);
theThis.loadData();
}
},
'-',
{
iconCls: p_This.activeMenuButton == 'Daily' ? 'icon-v3-menu-tick' : 'no-icon',
text: 'Daily',
handler: function (p_ThisButton) {
p_This.activeMenuButton = p_ThisButton.text;
theThis.stopSlide = true;
theThis.store_DailyFoodCost.baseParams.weekIndex = theThis.weekIndex;
theThis.store_DailyFoodCost.baseParams.startDayOfTheWeek = theThis.startDayOfTheWeek;
theThis.store_DailyFoodCost.load();
theThis.pnl_LiveFoodCost.layout.setActiveItem(theThis.chart_DailyFoodCost);
theThis.setTitle(theThis.chart_DailyFoodCost.titleDescription);
}
},
{
iconCls: p_This.activeMenuButton == 'Monthly' ? 'icon-v3-menu-tick' : 'no-icon',
text: 'Monthly',
handler: function (p_ThisButton) {
p_This.activeMenuButton = p_ThisButton.text;
theThis.stopSlide = true;
theThis.pnl_LiveFoodCost.layout.setActiveItem(theThis.chart_MonthFoodCost);
theThis.setTitle(theThis.chart_MonthFoodCost.titleDescription);
}
},
{
iconCls: p_This.activeMenuButton == 'Yearly' ? 'icon-v3-menu-tick' : 'no-icon',
text: 'Yearly',
handler: function (p_ThisButton) {
p_This.activeMenuButton = p_ThisButton.text;
theThis.stopSlide = true;
theThis.pnl_LiveFoodCost.layout.setActiveItem(theThis.chart_YearFoodCost);
theThis.setTitle(theThis.chart_YearFoodCost.titleDescription);
}
}
]
});
p_This.menu_ViewOptions.show(e.getTarget());
});
// Live food cost calendar button
Ext.get(String.format('{0}btnLiveFoodCostCalendar', theThis.id)).on('click', function(e){
theThis.dlg_FoodCostLiveCalendar.show();
});
// Food cost predictor
Ext.get(String.format('{0}btnFoodCostPredictor', theThis.id)).on('click', function(e){
theThis.dlg_FoodCostPredictor.show();
});
}
}
});
return pnl_TopButtons;
},
getPanel_FoodCostTable : function(){
var theThis = this;
theThis.tpl_FoodCostTable = new Ext.XTemplate(
'',
'',
'
',
/*'',
'',
'Food cost based on Purchase to Sales ',
' ',
' ',*/
'',
'',
'',
'',
'Food Cost %',
' ',
'',
'',
'{foodCostOfTheDate}%',
' ',
' ',
'',
'{foodCostThisWeek}%',
' ',
'',
'{foodCostMonthUntilEndOfWeekDate}%',
' ',
'',
'{foodCostThisMonth}%',
' ',
'',
'{foodCostYearUntilEndOfWeekDate}%',
' ',
'',
'{foodCostThisYear}%',
' ',
'',
'{foodCostFromLastStocktake}%',
' ',
' ',
'',
'',
'Purchase',
' ',
'',
'',
'',
' ',
' ',
'',
'',
' ',
'',
'$ {purchaseMonthUntilEndOfWeekDate}
',
' ',
'',
'',
' ',
'',
'$ {purchaseYearUntilEndOfWeekDate}
',
' ',
'',
'',
' ',
'',
'$ {purchaseFromLastStocktake}
',
' ',
' ',
'',
'',
'Sales',
' ',
'',
'',
'$ {kitchenRevenueOfTheDate}
',
' ',
' ',
'',
'$ {kitchenRevenueThisWeek}
',
' ',
'',
'$ {kitchenRevenueMonthUntilEndOfWeekDate}
',
' ',
'',
'$ {kitchenRevenueThisMonth}
',
' ',
'',
'$ {kitchenRevenueYearUntilEndOfWeekDate}
',
' ',
'',
'$ {kitchenRevenueThisYear}
',
' ',
'',
'$ {kitchenRevenueFromLastStocktake}
',
' ',
' ',
'
',
'
',
' '
);
var pnl_FoodCostTable = new Ext.Panel({
region : 'center',
titleDescription : 'Live Food Cost',
frame : false,
tpl : theThis.tpl_FoodCostTable,
listeners : {
afterrender : function(p_This){
}
}
});
return pnl_FoodCostTable;
},
getChart_DailyFoodCost : function(weekIndex, title){
var theThis = this;
theThis.store_DailyFoodCost = new Ext.data.JsonStore({
baseParams : {start : 0, limit : theThis.pageSize, weekIndex : theThis.weekIndex, startDayOfTheWeek : theThis.startDayOfTheWeek},
proxy: new Ext.data.HttpProxy({
url: '/Invoice/GetChartData_FoodCostWeek',
dataType: 'json',
method: 'POST'
}),
autoLoad : false,
fields:['name', 'foodCost'],
root: 'data',
//idProperty: 'menuAnalysisId',
//totalProperty : 'totalCount',
listeners : {
'beforeload' : function(){
},
'load' : function(){
theThis.chartObjectDaily = new Ext.chart.LineChart({
store: theThis.store_DailyFoodCost,
xField: 'name',
yField: 'foodCost',
tipRenderer : function(chart, record){
return addFullDigitToNumber(record.data.foodCost, 2) + ' % in ' + record.data.name;
},
listeners: {
itemclick: function(o){
var rec = store.getAt(o.index);
//Ext.example.msg('Item Selected', 'You chose {0}.', rec.get('name'));
}
}
});
theThis.chart_DailyFoodCost.removeAll(true);
theThis.chart_DailyFoodCost.add(theThis.chartObjectDaily);
theThis.chart_DailyFoodCost.getLayout().setActiveItem(theThis.chartObjectDaily);
},
'loadexception' : function(){
showStoreLoadingErrorMessage(store);
}
}
});
// extra extra simple
var chartContainer = new Ext.Panel({
titleDescription: title,
layout:'card',
items: [
/*theThis.chartObjectDaily = new Ext.chart.LineChart({
store: theThis.store_DailyFoodCost,
xField: 'name',
yField: 'foodCost',
tipRenderer : function(chart, record){
return addFullDigitToNumber(record.data.foodCost, 2) + ' % in ' + record.data.name;
},
listeners: {
itemclick: function(o){
var rec = store.getAt(o.index);
//Ext.example.msg('Item Selected', 'You chose {0}.', rec.get('name'));
}
}
})*/
]
});
return chartContainer;
},
getChart_MonthFoodCost : function(){
var theThis = this;
var store = new Ext.data.JsonStore({
baseParams : {start : 0, limit : theThis.pageSize},
proxy: new Ext.data.HttpProxy({
url: '/Invoice/GetChartData_FoodCostMonth',
dataType: 'json',
method: 'POST'
}),
autoLoad : true,
fields:['name', 'foodCost'],
root: 'data',
//idProperty: 'menuAnalysisId',
//totalProperty : 'totalCount',
listeners : {
'beforeload' : function(){
},
'load' : function(){
},
'loadexception' : function(){
showStoreLoadingErrorMessage(store);
}
}
});
// extra extra simple
var chartContainer = new Ext.Panel({
titleDescription: 'Month - Food Cost',
layout:'fit',
items: {
xtype: 'linechart',
store: store,
xField: 'name',
yField: 'foodCost',
/*yAxis: new Ext.chart.NumericAxis({
displayName: 'Food Cost',
labelRenderer : Ext.util.Format.numberRenderer('0,0')
}),*/
tipRenderer : function(chart, record){
return addFullDigitToNumber(record.data.foodCost, 2) + ' % in ' + record.data.name;
},
listeners: {
itemclick: function(o){
var rec = store.getAt(o.index);
//Ext.example.msg('Item Selected', 'You chose {0}.', rec.get('name'));
}
}
}
});
return chartContainer;
},
getChart_YearFoodCost : function(){
var theThis = this;
var store = new Ext.data.JsonStore({
baseParams : {start : 0, limit : theThis.pageSize},
proxy: new Ext.data.HttpProxy({
url: '/Invoice/GetChartData_FoodCostYear',
dataType: 'json',
method: 'POST'
}),
autoLoad : true,
fields:['name', 'foodCost'],
root: 'data',
//idProperty: 'menuAnalysisId',
//totalProperty : 'totalCount',
listeners : {
'beforeload' : function(){
},
'load' : function(){
},
'loadexception' : function(){
showStoreLoadingErrorMessage(store);
}
}
});
// extra extra simple
var chartContainer = new Ext.Panel({
titleDescription: 'Year - Food Cost',
layout:'fit',
items: {
xtype: 'linechart',
store: store,
xField: 'name',
yField: 'foodCost',
tipRenderer : function(chart, record){
return addFullDigitToNumber(record.data.foodCost, 2) + ' % in ' + record.data.name;
},
listeners: {
itemclick: function(o){
var rec = store.getAt(o.index);
//Ext.example.msg('Item Selected', 'You chose {0}.', rec.get('name'));
}
}
}
});
return chartContainer;
},
getPanel_ExtraButtons : function(){
var theThis = this;
var pnl_ExtraButtons = new Ext.Panel({
region : 'east',
layout : 'vbox',
frame : true,
width : 50,
layoutConfigs : {
defaultMargins : '5 5 5 5'
},
items : [
theThis.btn_ShowCalendar = new Ext.Button({
xtype : 'button',
scale : 'large',
iconCls : 'icon-calendar',
handler : function(){
theThis.dlg_FoodCostLiveCalendar.show();
},
listeners : {
afterrender : function(p_This){
var annouceTooltip = new Ext.ToolTip({
target: theThis.btn_ShowCalendar.id,
anchor: 'right',
html: 'Click me to show your LIVE FOOD COST Calendar '
});
annouceTooltip.show();
}
}
}),
theThis.btn_StopSlide = new Ext.Button({
xtype : 'button',
scale : 'large',
hidden : true,
iconCls : 'icon-cancel-large',
tooltip : 'Stop slide',
handler : function(){
theThis.stopSlide = true;
}
}),
theThis.btn_MoveNext = new Ext.Button({
xtype : 'button',
scale : 'large',
hidden : true,
iconCls : 'icon-move-right',
tooltip : 'Next slide',
handler : function(){
theThis.moveToNextSlide();
}
}),
new Ext.Panel({
height : 100,
width : 30
})
],
listeners : {
afterrender : function(p_This){
}
}
});
return pnl_ExtraButtons;
}
});
Ext.reg('CTBBoard_InvoiceFoodCost', Ext.CTBBoard_InvoiceFoodCost);
Ext.CTBInvoiceDetailGrid = Ext.extend(Ext.Panel, {
layout : 'border',
loadMask: null,
pageSize: CTB.init.itemPerPage || 100,
border: false,
recordObject : null,
selectedInvoiceRecord : null,
isForCreditNoteRequest : false,
hideInstruction : true,
isCalculateParentField : true,
setSelectedInvoiceRecord : function(theRecord){
var theThis = this;
theThis.selectedInvoiceRecord = theRecord;
if (theRecord != null)
theThis.selectedInvoiceId = theRecord.data.invoiceId;
else
theThis.selectedInvoiceId = -1;
},
parentWindowContainer : null,
listeners : {
afterrender : function(theThis){
// Init loadMask
theThis.loadMask = new Ext.LoadMask(this.getEl(), {msg:"Please wait..."});
},
show : function(theThis){
theThis.modifiedRecords = null;
}
},
instructionText : 'Physical Invoice',
instructionBackgroundColor : '#282828',
redrawInstruction : function(){
var theThis = this;
theThis.pnl_Instruction.update({instructionBackgroundColor : theThis.instructionBackgroundColor, instructionText : theThis.instructionText});
},
initComponent: function(){
var theThis = this;
theThis.StockBrowserDialog = Ext.getCmp('dlg_StockBrowser');
theThis.grid_InvoiceDetail = theThis.getGrid_InvoiceDetail();
theThis.tpl_Instruction = new Ext.XTemplate(
'',
'',
'
',
'',
'',
'{instructionText} ',
' ',
' ',
'
',
'
',
' '
);
theThis.pnl_Instruction = new Ext.Panel({
frame : true,
border : false,
region : 'north',
height : 70,
tpl : theThis.tpl_Instruction,
hidden : theThis.hideInstruction,
listeners : {
afterrender : function(p_This){
p_This.update({instructionBackgroundColor : theThis.instructionBackgroundColor, instructionText : theThis.instructionText});
}
}
});
theThis.items = [theThis.grid_InvoiceDetail, theThis.pnl_Instruction];
// Call super class to initialize componenets
Ext.CTBInvoiceDetailGrid.superclass.initComponent.call(this);
},
updateTheSubtotal : function(theRecord){
var theThis = this;
theThis.getGrid().updateTheSubtotal(theRecord);
},
clearSelections : function(){
var theThis = this;
theThis.getGrid().getStore().commitChanges();
theThis.getGrid().getSelectionModel().clearSelections();
},
getGrid: function(){
var theThis = this;
return theThis.grid_InvoiceDetail;
},
getPagingToolbar: function(){
var theThis = this;
return theThis.pt_InvoiceDetail;
},
getSelectedRecords: function(){
var theThis = this;
return theThis.getGrid().getSelectionModel().getSelections();
},
loadData: function(){
var theThis = this;
theThis.getGrid().getStore().commitChanges();
theThis.getGrid().getStore().baseParams = {invoiceId : theThis.selectedInvoiceRecord.data.invoiceId, start : 0, limit : theThis.getPagingToolbar().pageSize};
theThis.getGrid().getStore().load();
},
getCombobox_UnitOfMeasurement : function(callbackfunction)
{
var cmbGridUOM = new Ext.form.ComboBox({
store: Global_UnitOfMeasurement_Store,
displayField: 'UOMName',
valueField: 'UOMId',
typeAhead: true,
triggerAction: 'all',
lazyRender: true,
mode: 'local'
});
return cmbGridUOM;
},
getGrid_InvoiceDetail: function(){
var theThis = this;
// shorthand alias
var fm = Ext.form;
var cmbGridUOM = theThis.getCombobox_UnitOfMeasurement();
// ***************************************************************************************************
// Data Fields
// ***************************************************************************************************
theThis.recordObject = Ext.data.Record.create([
{ name: 'invoiceDetailId', type: 'number' },
{ name: 'invoiceId', type: 'number' },
{ name: 'supplierStockCode', type: 'string' },
{ name: 'stockDesc', type: 'string' },
{ name: 'stockUnit', type: 'number' },
{ name: 'stockUnitOfMeasurementId', type: 'number' },
{ name: 'stockQty', type: 'number' },
{ name: 'stockId', type: 'number' },
{ name: 'stockSupplierId', type: 'number' },
{ name: 'invoiceDetailCost', type : 'number'},
{ name: 'invoiceDetailTax', type: 'number' },
{ name: 'invoiceDetailSubtotal', type: 'number' },
{ name: 'isGstApplied', type: 'boolean' },
{ name: 'discountPercentage', type: 'number' }
]);
// ***************************************************************************************************
// Stores
// ***************************************************************************************************
var store = new Ext.data.JsonStore({
autoLoad : false,
proxy: new Ext.data.HttpProxy({
url: '/Invoice/GetInvoiceDetailByInvoiceId',
dataType: 'json',
method: 'POST'
}),
//reader: new Ext.data.JsonReader({
fields: theThis.recordObject,
root: 'data',
idProperty: 'invoiceDetailId',
listeners : {
'load' : function(){
},
'loadexception' : function(){
showStoreLoadingErrorMessage(store);
}
}
//})
});
// ***************************************************************************************************
// Selection model
// ***************************************************************************************************
var sm = new Ext.grid.CheckboxSelectionModel({
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
}
}
});
// ***************************************************************************************************
// Column model
// ***************************************************************************************************
// Column Models
var cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults: {
sortable: true // columns are not sortable by default
},
columns: [
sm,
{
header: 'invoiceDetailId', dataIndex: 'invoiceDetailId', hidden: true, width:5
},
{
header: 'invoiceId', dataIndex: 'invoiceId', hidden: true, width:5
},
{
header: 'Stock Code', dataIndex: 'supplierStockCode', width: 10, hidden : theThis.isForCreditNoteRequest,
filter: {xtype : "textfield", filterName : "supplierStockCode", callbackFunction : function(filterValue){
theThis.insertStockSupplierRecordBySupplierStockCode(filterValue, 0);
}}
},
{
header: 'Description', dataIndex: 'stockDesc', width: 30
},
{
header: 'Unit', dataIndex: 'stockUnit', width: 15, hidden : theThis.isForCreditNoteRequest
},
{
header: 'Measurement', dataIndex: 'stockUnitOfMeasurementId', width: 15, hidden : theThis.isForCreditNoteRequest,
renderer: Ext.util.Format.comboRenderer(cmbGridUOM)
},
{
header: 'Quantity' + CTB_SYMBOL.EDIT, dataIndex: 'stockQty', width: 15,
editor: new Ext.grid.GridEditor(
new Ext.form.SpinnerField({
xtype: 'spinnerfield',
allowBlank: false,
allowNegative: false,
minValue : 0,
allowDecimals : true,
decimalPrecision: 3,
onFocus: function (txt, e) {
this.getEl().dom.select();
}
}),
{
listeners: {
beforestartedit: function(editor) {
editor.field.currentRecord = editor.record;
},
complete : function(p_This, p_Value, p_StartValue){
// Value has been changed by user
if (p_Value != p_StartValue){
//updateTheSubtotal(p_This.record);
}
}
}
}
)
},
{
header: 'Cost/Unit', dataIndex: 'invoiceDetailCost', width: 15, hidden : theThis.isForCreditNoteRequest,
editor: new Ext.grid.GridEditor(
new Ext.form.SpinnerField({
xtype: 'spinnerfield',
allowBlank: false,
allowNegative: false,
minValue : 0,
allowDecimals : true,
decimalPrecision: 3,
onFocus: function (txt, e) {
this.getEl().dom.select();
}
}),
{
listeners: {
beforestartedit: function(editor) {
editor.field.currentRecord = editor.record;
},
complete : function(p_This, p_Value, p_StartValue){
// Value has been changed by user
if (p_Value != p_StartValue){
//updateTheSubtotal(p_This.record);
}
}
}
}
),
renderer: Ext.util.Format.usMoney
},
{
header: 'DISC %' + CTB_SYMBOL.EDIT, dataIndex: 'discountPercentage', width: 15, hidden : theThis.isForCreditNoteRequest,
editor: new Ext.grid.GridEditor(
new Ext.form.NumberField({
allowBlank: false,
allowNegative: false,
minValue : 0,
allowDecimals : true,
decimalPrecision: 2,
onFocus: function (txt, e) {
this.getEl().dom.select();
}
}),
{
listeners: {
beforestartedit: function(editor) {
editor.field.currentRecord = editor.record;
},
complete : function(p_This, p_Value, p_StartValue){
// Value has been changed by user
if (p_Value != p_StartValue){
//updateTheSubtotal(p_This.record);
}
}
}
}
),
renderer: function(val){
return Ext.util.Format.percentage(val);
}
},
{
header: 'Tax' + CTB_SYMBOL.EDIT, dataIndex: 'invoiceDetailTax', width: 15, hidden : theThis.isForCreditNoteRequest,
editor: new Ext.grid.GridEditor(
new Ext.form.SpinnerField({
xtype: 'spinnerfield',
moneySign : '',
allowBlank: false,
allowNegative: false,
minValue : 0,
allowDecimals : true,
decimalPrecision: 3,
onFocus: function (txt, e) {
this.getEl().dom.select();
}
}),
{
listeners: {
beforestartedit: function(editor) {
editor.field.currentRecord = editor.record;
},
complete : function(p_This, p_Value, p_StartValue){
// Value has been changed by user
if (p_Value != p_StartValue){
// Mark the record as modified
p_This.record.isUserModifiedTax = true;
}
}
}
}
),
renderer: Ext.util.Format.usMoney
},
{
header: 'Subtotal', dataIndex: 'invoiceDetailSubtotal', width: 15, hidden : theThis.isForCreditNoteRequest,
renderer: Ext.util.Format.usMoney
},
{
header: '', dataIndex: 'invoiceDetailId', width: 5,
renderer: function(val, meta, theRecord){
return String.format('
', theThis.id, val);
}
},
{
header: '', dataIndex: 'invoiceDetailId', width: 0,
renderer: function(val, meta, theRecord){
return '';
}
}
]
});
// This function update tax column for all rows
function updateTaxForAllRows(){
for (var i = 0; i < store.getCount(); i++){
var theRecord = store.getAt(i);
if (theRecord.data.isGstApplied){
if (theRecord.isUserModifiedTax == null || theRecord.isUserModifiedTax == false)
theRecord.set('invoiceDetailTax', roundNumber((theRecord.data.invoiceDetailCost * theRecord.data.stockQty * CTB.init.expenseTax.percentage)/100, 2));
}
/*else if (theRecord.data.invoiceDetailTax != 0){
theRecord.set('invoiceDetailTax', roundNumber((theRecord.data.invoiceDetailCost * theRecord.data.stockQty * Global_GSTPercentage)/100, 2));
}*/
}
}
function updateTheTax(theRecord){
if (theRecord.data.isGstApplied){
if (theRecord.isUserModifiedTax == null || theRecord.isUserModifiedTax == false)
theRecord.set('invoiceDetailTax', roundNumber((theRecord.data.invoiceDetailCost * theRecord.data.stockQty * CTB.init.expenseTax.percentage)/100, 2));
}
}
// This function update the subtotal for individual record
function updateTheSubtotal(theRecord){
updateTheTax(theRecord);
var theSubTotal = theRecord.get('invoiceDetailTax') + theRecord.get('invoiceDetailCost')*theRecord.get('stockQty');
// Minus the individual discount
theSubTotal = theSubTotal - (theSubTotal * theRecord.get('discountPercentage') / 100);
theSubTotal = roundNumber(theSubTotal, Global_Money_RoundUpTo);
theRecord.set('invoiceDetailSubtotal', theSubTotal);
if (theThis.parentWindowContainer != null && theThis.isCalculateParentField) {
theThis.parentWindowContainer.refreshCalculatingField();
}
}
// ***************************************************************************************************
// Paging toolbar
// ***************************************************************************************************
theThis.pt_InvoiceDetail = new Ext.CTBPagingToolbar({
store: store,
pageSize: theThis.pageSize,
displayInfo: true,
emptyMsg: "No stocks to display",
hidden : theThis.isForCreditNoteRequest
});
// ***************************************************************************************************
// Grid
// ***************************************************************************************************
var grid = new Ext.grid.EditorGridPanel({
region: 'center',
margins : '10 10 0 10',
store: store,
frame: false,
sm : sm,
plugins: [new Ext.ux.grid.GridHeaderFilters()],
updateTheSubtotal : function(theRecord){
updateTheSubtotal(theRecord);
},
tbar : [
theThis.btn_Add = new Ext.Button({
iconCls : 'icon-add', scale : 'large',
text : 'New',
handler : function(){
theThis.StockBrowserDialog.Global_StockBrowser_CallbackFunction = function(selectedRecords){
theThis.addNewRecord(selectedRecords);
};
if (theThis.parentWindowContainer != null)
theThis.StockBrowserDialog.Global_StockBrowser_AssignedSupplierId = theThis.parentWindowContainer.cmbSupplier.getValue();
//theThis.StockBrowserDialog.items.get('tab_StockBrowser_AllTabs').setActiveTab(1);
theThis.StockBrowserDialog.show();
}
}),
theThis.btn_Delete = new Ext.Button({
iconCls : 'icon-delete', scale : 'large',
text : 'Delete',
handler : function(){
var selectedItems = theThis.getGrid().getSelectionModel().getSelections();
if (selectedItems.length > 0)
{
Ext.Msg.show({
title:'Confirm',
msg: 'Are you sure you want to delete the item(s) ?',
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.QUESTION,
fn : function(btn) {
if (btn == "yes") {
var deletedItemIds = new Array(); // Actual deleted item
var modifiedRecords = store.getModifiedRecords();
var modifiedInfo = new Array(); // Store the modifed record for recovering from deleting
// This loop save the changes
for (var i = 0; i < modifiedRecords.length; i++){
modifiedInfo[i] = {
invoiceDetailId : modifiedRecords[i].data.invoiceDetailId,
stockQty : modifiedRecords[i].data.stockQty
};
}
// This loop insert deleted item to the array
for (var i = 0, j = 0; i < selectedItems.length; i++) {
var theId = selectedItems[i].get("invoiceDetailId");
if (theId >= 0){ // Only delete existing detail
deletedItemIds[j] = theId;
j++;
}
theThis.getGrid().getStore().remove(selectedItems[i]);
}
store.commitChanges(); // This is the reason we use modifiedInfo, when we commit, every changes disappear
// Recovering the changes
// If the item not be deleted
for (var i = 0; i < modifiedInfo.length; i++){
var invoiceDetailId = modifiedInfo[i].invoiceDetailId;
if (store.getById(invoiceDetailId) != null){
var stockQty = modifiedInfo[i].stockQty;
store.getById(invoiceDetailId).set('stockQty', 0); // Make changing mark appearing
store.getById(invoiceDetailId).set('stockQty', stockQty); // Recovering the real value
}
}
// Refresh the total
if (theThis.parentWindowContainer != null && theThis.isCalculateParentField)
theThis.parentWindowContainer.refreshCalculatingField();
// Calling delete
if (theThis.selectedInvoiceId != -1 && deletedItemIds.length > 0){ // Only send request when the invoice exist
theThis.loadMask.show();
Ext.Ajax.request({
method: 'POST',
url: '/Invoice/DeleteStockFromInvoice',
params:
{
invoiceId : theThis.selectedInvoiceId,
invoiceDetailIds : Ext.util.JSON.encode(deletedItemIds)
},
success : function(result, request) {
theThis.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
//grid_Invoice.getStore().load();
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.loadMask.hide();
}
}); // End ajax
}
else if (theThis.parentWindowContainer.selectedProformaInvoiceId != -1 && deletedItemIds.length > 0) { // Delete from proforma invoice
theThis.loadMask.show();
Ext.Ajax.request({
method: 'POST',
url: '/ProformaInvoice/DeleteStockFromProformaInvoice',
params:
{
proformaInvoiceId : theThis.parentWindowContainer.selectedProformaInvoiceId,
proformaInvoiceDetailIds : Ext.util.JSON.encode(deletedItemIds)
},
success : function(result, request) {
theThis.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
//grid_Invoice.getStore().load();
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.loadMask.hide();
}
}); // End ajax
} // End if
}
}
});
}
else {
Ext.Msg.show({
title:'Notice',
msg: 'Please select item(s) to delete!',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
}// End if
}// End Handler
}), // End delete button
theThis.btn_QuickKey = new Ext.Button({
iconCls : 'icon-activate', scale : 'large',
text : 'Quick key',
handler : function(){
if (theThis.dlg_QuickKey == null)
{
theThis.dlg_QuickKey = new Ext.CTBStockQuickKey({
callback_QuickAdd : function(stockCode, quantity){
theThis.insertStockSupplierRecordBySupplierStockCode(stockCode, quantity);
}
});
} // End if
theThis.dlg_QuickKey.show();
} // End handler
})
],
listeners : {
rowclick : function ( p_this, p_rowIndex, p_eventObject ) {
var selectedRow = p_this.getView().getRow(p_rowIndex);
Ext.get(selectedRow).highlight();
if (theThis.parentWindowContainer != null && theThis.isCalculateParentField) {
theThis.parentWindowContainer.pnl_InvoiceDetail_NumberPad.callback_Assign = function(value){
theThis.getGrid().stopEditing();
var selectedRecords = theThis.getGrid().getSelectionModel().getSelections();
if (selectedRecords.length > 0){
for (var i = 0; i < selectedRecords.length; i++){
selectedRecords[i].set('stockQty', value);
updateTheSubtotal(selectedRecords[i]);
}
}
};
}
//theThis.getGrid().startEditing(p_rowIndex, 7);
// Only stop editing if user's using iPad
// We don't want them to see the default keyboard in iPad
if (Global_IsiPad)
theThis.getGrid().stopEditing();
},
// p_EditedObject INCLUDES :
// grid - This grid
// record - The record being edited
// field - The field name being edited
// value - The value being set
// originalValue - The original value for the field, before the edit.
// row - The grid row index
// column - The grid column index
afteredit : function( p_EditedObject ) {
updateTheSubtotal(p_EditedObject.record);
setUpWarningWhenClosePage();
},
beforeedit : function (p_Event) {
if (theThis.parentWindowContainer != null && theThis.isCalculateParentField) {
theThis.parentWindowContainer.pnl_InvoiceDetail_NumberPad.callback_Next = function(theNumberPad){
try{
if (theNumberPad.isHavingChanges == true){
theNumberPad.operatorClick('=');
}
theThis.getGrid().getSelectionModel().selectRow(p_Event.row + 1);
theThis.getGrid().startEditing(p_Event.row + 1, 7);
theThis.getGrid().stopEditing();
}catch(e){
var activePage = 1;
var totalCount = theThis.getGrid().getStore().getTotalCount();
if ((activePage+1) <= Math.ceil(totalCount / theThis.pt_InvoiceDetail.pageSize))
{
theThis.pt_InvoiceDetail.moveNext();
}
else {
showErrorNotification('Notice', 'End of invoice details.');
}
}
};
}
}
},
cm: cm,
width: 780,
height: 400,
autoHeight: false,
clicksToEdit: 1,
loadMask: true,
bbar : theThis.pt_InvoiceDetail,
viewConfig:
{
enableRowBody: true,
forceFit: true // IMPORTANT (USE THIS ATTRIBUTE TO USE PERCENTAGE IN COLUMN MODEL)
}
});
return grid;
},
insertStockSupplierRecordBySupplierStockCode : function(supplierStockCode, quantity){
var theThis = this;
theThis.promptedStockQuantity = quantity;
if (theThis.storeTemporaryStockSupplier == null){
theThis.recordTypeTemporaryStockSupplier = Ext.data.Record.create([
{ name: 'stockSupplierId', type: 'number' },
{ name: 'supplierStockCode', type: 'string' },
{ name: 'supplierCost', type: 'number' },
{ name: 'supplierId', type: 'number' },
{ name: 'supplierName', type: 'string' },
{ name: 'stockId', type: 'number' },
{ name: 'stockCode', type: 'string' },
{ name: 'stockDesc', type: 'string' },
{ name: 'stockUnit', type: 'number' },
{ name: 'unitOfMeasurementId', type: 'number' },
{ name: 'isGstApplied', type: 'boolean' }
]);
theThis.storeTemporaryStockSupplier = new Ext.data.JsonStore({
baseParams : {keyword : supplierStockCode, searchType : 7, supplierId : -1}, // Search type = 1 is for supplier stock code
autoLoad : false,
proxy: new Ext.data.HttpProxy({
url: '/Stock/GetStockBySupplier',
dataType: 'json',
method: 'POST'
}),
fields: theThis.recordTypeTemporaryStockSupplier,
root: 'data',
idProperty: 'stockSupplierId',
listeners : {
beforeload : function(){
theThis.loadMask.show();
},
load : function(){
// theThis.storeTemporaryStockSupplier.getRange(0, theThis.storeTemporaryStockSupplier.getCount());
if (theThis.storeTemporaryStockSupplier.getCount() > 0)
theThis.addNewRecord(theThis.storeTemporaryStockSupplier.getRange(0, theThis.storeTemporaryStockSupplier.getCount() - 1), theThis.promptedStockQuantity);
theThis.loadMask.hide();
},
loadexception : function(){
showStoreLoadingErrorMessage(store);
theThis.loadMask.hide();
}
}
});
}
theThis.storeTemporaryStockSupplier.baseParams.keyword = supplierStockCode;
theThis.storeTemporaryStockSupplier.baseParams.supplierId = theThis.parentWindowContainer.cmbSupplier.getValue();
theThis.storeTemporaryStockSupplier.reload();
},
addNewRecord : function(selectedRecords, quantity){
var theThis = this;
var insertedDetail = new Array();
if (quantity == null) quantity = 0;
for(var i = 0; i 0)
{
Ext.Msg.show({
title:'Save?',
msg: "You have made some changes. Do you want to save ?",
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.QUESTION,
fn : function(btn){
if (btn == "yes"){
theThis.btn_InvoiceDetail_Save.handler.call(theThis.btn_InvoiceDetail_Save.scope);
}
else {
// Disable the warning when close the page
disableWarningWhenClosePage();
store.commitChanges();
theThis.hide();
}
}
});
return false;
}
},
hide : function(theThis){
theThis.selectedExistingStockId = -1;
theThis.assignedSupplierId = -1;
//theThis.selectedProformaInvoiceId = -1;
//theThis.creditNoteProformaInvoiceId = -1;
},
beforeshow : function(theThis){
// Fit this window to the client browser screen with 90%
fitWindowSize(theThis, 90);
if (theThis.selectedInvoiceId != -1){
// Fill the detail
// Get the selected invoice record
var selectedInvoiceRecord = theThis.selectedInvoiceRecord;
var invoiceId = selectedInvoiceRecord.data.invoiceId;
var invoiceDate = selectedInvoiceRecord.data.invoiceDate;
var invoiceNo = selectedInvoiceRecord.data.invoiceNo;
theThis.lastInvoiceNo = invoiceNo; // Save the last invoice number to the dialog
var supplierList = selectedInvoiceRecord.data.supplierList;
var totalTax = selectedInvoiceRecord.data.totalTax;
var discount = selectedInvoiceRecord.data.discount;
var freightIncludeGST = selectedInvoiceRecord.data.freightIncludeGST;
var isReturned = selectedInvoiceRecord.data.isReturned;
var supplierId = selectedInvoiceRecord.data.supplierId;
var totalAmount = isReturned? -selectedInvoiceRecord.data.totalAmount : selectedInvoiceRecord.data.totalAmount;
totalAmount = roundNumber(totalAmount, 2);
// Fill the detail
theThis.cmbSupplier.doQuery("", true);
/*if (supplierId != -1)
{
cmbSupplier.setValue(supplierId);
}
else cmbSupplier.setValue(cmbSupplier.getStore().getAt(0).get('supId'));*/
theThis.txt_TopDetail_Date.setValue(invoiceDate);
theThis.txt_TopDetail_InvoiceNo.setValue(invoiceNo);
theThis.cmb_TopDetail_InvoiceType.setValue(isReturned);
theThis.txt_BottomDetail_TotalTax.setValue(totalTax);
theThis.txt_BottomDetail_Discount.setValue(discount);
theThis.txt_BottomDetail_FreightIncludeGST.setValue(freightIncludeGST);
theThis.txt_TopDetail_Total.setValue(totalAmount);
theThis.txt_BottomDetail_Total.setValue(totalAmount);
if (isReturned) {
theThis.txt_TopDetail_Total.setPrefixSign('-');
theThis.txt_BottomDetail_Total.setPrefixSign('-');
}
else {
theThis.txt_TopDetail_Total.setPrefixSign('');
theThis.txt_BottomDetail_Total.setPrefixSign('');
}
// Enable or Disable the Add Payment Button
if (selectedInvoiceRecord.data.status == "UNPAID" || selectedInvoiceRecord.data.status == "PAID"){
theThis.btn_Invoice_AddPaymentConfirmation.setVisible(true);
}
else {
theThis.btn_Invoice_AddPaymentConfirmation.setVisible(false);
}
}
// Clear everything
else {
// Only reset the combobox if user didn't select any supplier before
theThis.cmbSupplier.doQuery("", true);
theThis.txt_TopDetail_InvoiceNo.setValue('');
theThis.lastInvoiceNo = null;
theThis.cmb_TopDetail_InvoiceType.setValue(0);
theThis.txt_BottomDetail_TotalTax.setValue(0);
theThis.txt_BottomDetail_Discount.setValue(0);
theThis.txt_BottomDetail_FreightIncludeGST.setValue(0);
theThis.txt_TopDetail_Total.setValue(0);
theThis.txt_BottomDetail_Total.setValue(0);
theThis.txt_TopDetail_Total.setPrefixSign('');
theThis.txt_BottomDetail_Total.setPrefixSign('');
theThis.cmb_TopDetail_InvoiceType.setValue(false);
}
},
show : function(theThis){
var store = theThis.grid_InvoiceDetail.getGrid().getStore();
if (theThis.selectedInvoiceId != -1){
// Load the data
store.commitChanges();
store.baseParams = {invoiceId : theThis.selectedInvoiceId};
store.load();
theThis.btn_RequestCreditNote.setVisible(true);
}
else {
store.baseParams = {invoiceId : -1};
store.removeAll();
store.commitChanges();
if (theThis.callback_AfterShow != null){
theThis.callback_AfterShow();
}
theThis.btn_RequestCreditNote.setVisible(false);
}
if (theThis.instructionText != null) theThis.grid_InvoiceDetail.redrawInstruction();
// Credit note
if (theThis.grid_CreditNoteDetail != null) {
var creditNoteStore = theThis.grid_CreditNoteDetail.getGrid().getStore();
if (theThis.selectedInvoiceId != -1){
if (theThis.creditNoteProformaInvoiceId == -1) {
// Load the data
creditNoteStore.commitChanges();
creditNoteStore.baseParams = {invoiceId : theThis.selectedInvoiceId};
creditNoteStore.load();
theThis.btn_InvoiceDetail_CreditNoteRequest.setVisible(true);
theThis.btn_TurnCreditNoteIntoReturnInvoice.setVisible(false);
}
else {
creditNoteStore.commitChanges();
creditNoteStore.removeAll();
theThis.getCreditNoteDetailFromProformaInvoice(theThis.creditNoteProformaInvoiceId);
theThis.btn_InvoiceDetail_CreditNoteRequest.setVisible(true);
theThis.btn_TurnCreditNoteIntoReturnInvoice.setVisible(true);
}
}
else {
creditNoteStore.baseParams = { invoiceId : -1 };
creditNoteStore.removeAll();
creditNoteStore.commitChanges();
}
theThis.btn_RequestCreditNote.setVisible(false);
}
}
},
initComponent : function(){
var theThis = this;
if (document.URL.indexOf('web.cookingthebooks.com.au') != -1) {
theThis.isHideDevelopmentButtons = true;
}
else theThis.isHideDevelopmentButtons = false;
// MAIN GRID
theThis.dlg_AddPaymentDetail = theThis.getDialog_AddPaymentDetail();
theThis.dlg_StockExistingOrder = theThis.getStockExistingOrderDialog();
theThis.grid_InvoiceDetail = new Ext.CTBInvoiceDetailGrid({
region : 'center',
parentWindowContainer : theThis,
hideInstruction : theThis.instructionText == null ? !theThis.isForCreditNoteRequest : false, // If the whole window for credit note request, don't hide instruction
instructionText : theThis.instructionText
});
theThis.pnl_TopDetail = theThis.getPanel_TopDetail();
theThis.pnl_BottomDetail = theThis.getPanel_BottomDetail();
theThis.pnl_InvoiceDetailCenterWrapper = new Ext.Panel({
layout : 'border',
region : 'center',
items : [
theThis.grid_InvoiceDetail, theThis.pnl_BottomDetail
]
});
theThis.pnl_InvoiceDetail_NumberPad = new Ext.CTBNumberPad({
region : 'east',
collapsible : true,
collapsed : false,
isShowWarningSelectRow : false,
width : 477,
hidden : theThis.isForCreditNoteRequest
});
// Credit note layout
if (theThis.isForCreditNoteRequest) {
theThis.grid_CreditNoteDetail = new Ext.CTBInvoiceDetailGrid({
region : 'east',
width : 400,
parentWindowContainer : theThis,
isForCreditNoteRequest : theThis.isForCreditNoteRequest,
isCalculateParentField : false,
instructionText : 'Enter what you actually receive',
instructionBackgroundColor : '#00bce2',
hideInstruction : false
});
theThis.items = [
theThis.grid_InvoiceDetail,
theThis.pnl_TopDetail,
//theThis.pnl_BottomDetail,
theThis.grid_CreditNoteDetail
];
}
// Normal invoice input layout
else {
theThis.items = [
theThis.pnl_InvoiceDetailCenterWrapper,
//theThis.grid_InvoiceDetail,
theThis.pnl_TopDetail,
//theThis.pnl_BottomDetail,
theThis.pnl_InvoiceDetail_NumberPad
];
}
// BUTTONS
var myButtons = theThis.initButtons();
this.buttons = myButtons;
this.initTools();
Ext.CTBInvoiceDetailWindow.superclass.initComponent.call(this);
},
clearSelections : function(){
var theThis = this;
if (theThis.grid_InvoiceDetail.rendered)
theThis.grid_InvoiceDetail.clearSelections();
},
initButtons : function(){
var theThis = this;
var buttons = [
theThis.btn_InvoiceDetail_CreditNoteRequest = new Ext.Button({
text : 'Send request',
hidden : !theThis.isForCreditNoteRequest,
tooltip : 'Send the credit note request to supplier',
iconCls : 'icon-send-large', scale : 'large',
handler : function(){
theThis.saveCreditNoteRequest(function(){
theThis.sendCreditNoteRequest();
});
} // End send request handler button
}),
theThis.btn_TurnCreditNoteIntoReturnInvoice = new Ext.Button({
text : 'Turn credit note to return invoice',
hidden : !theThis.isForCreditNoteRequest,
tooltip : 'Turn the credit note to return invoice',
iconCls : 'icon-send-large', scale : 'large',
handler : function(){
if (theThis.dlg_InvoiceDetail == null) {
theThis.dlg_InvoiceDetail = new Ext.CTBInvoiceDetailWindow({
isIgnoreWarningMarkingStockOrderAsInvoice : true,
HideShowExistingStockOrdersButton : true,
instructionText : 'Please make the change to make it match with the paper credit note.',
//saveInvoiceURL : '/ProformaInvoice/SaveProformaInvoiceFromRealInvoiceData',
isUsingProformaInvoiceId : false
});
}
theThis.dlg_InvoiceDetail.setSelectedInvoiceRecord(null);
theThis.dlg_InvoiceDetail.assignedSupplierId = theThis.selectedInvoiceRecord.data.supplierId;
theThis.dlg_InvoiceDetail.callback_AfterCancel = function(){
/*if (!theThis.selectedProformaInvoiceRecord.data.isFromNormalOrder)
theThis.pnl_Container.goToStep(1);
else {
theThis.pnl_Container.finishAndExit();
}*/
}
theThis.dlg_InvoiceDetail.callback_AfterShow = function(){
if (theThis.creditNoteProformaInvoiceId != -1) { // Check if this is used to turn proforma invoice to stored invoice or not
theThis.dlg_InvoiceDetail.selectedProformaInvoiceId = theThis.creditNoteProformaInvoiceId;
theThis.dlg_InvoiceDetail.getInvoiceDetailFromProformaInvoice(null, true); // No call back function
}
}
theThis.dlg_InvoiceDetail.callback_AfterSave = function(returnNewProformInvoice){
theThis.markCreditNoteAsProcessed(theThis.creditNoteProformaInvoiceId);
theThis.dlg_InvoiceDetail.hide();
}
theThis.dlg_InvoiceDetail.show();
} // End send request handler button
}),
theThis.btn_InvoiceDetail_Save = new Ext.Button({
cls : 'ctb-btn-red',
text : 'Save',
hidden : theThis.isForCreditNoteRequest,
iconCls : 'icon-save-large', scale : 'large',
handler : function(){
// Wrap data and send saving request
theThis.grid_InvoiceDetail.getGrid().stopEditing();
if (!theThis.validateBeforeSave())
{
return;
}
// First checking existence of the invoice number
// Only check invoice number if it's in adding mode
var invoiceNo = theThis.txt_TopDetail_InvoiceNo.getValue();
if (theThis.lastInvoiceNo == null || theThis.lastInvoiceNo != invoiceNo) // Adding mode or Changeing invoice number in editing moed
{
Ext.Ajax.request({
method: "POST",
url: '/Invoice/SearchInvoicesByInvoiceNumberAndSupplier',
params:
{
invoiceNumber : invoiceNo,
supplierId : theThis.cmbSupplier.getValue()
},
success : function(result, request) {
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
if (jsonData.totalCount > 0){
showToolTip(theThis.txt_TopDetail_InvoiceNo.getId(), 'This invoice number has been used before. Please make sure you are not doubling up invoice data.', false, null, null);
}
else {
theThis.saveData();
}
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
//loadMask.hide();
}
}); // End ajax
}
else {
theThis.saveData();
}
} // End save handler button
}),
/*theThis.btn_ShowExistingStockOrders = new Ext.Button({
text : 'Show electronic orders',
tooltip : 'Show electronic orders from the selected Supplier. You can choose from the list to populate the invoice automatically.',
iconCls: 'icon-daily-order', scale: 'large',
hidden : theThis.HideShowExistingStockOrdersButton,
handler : function(){
theThis.grid_StockExistingOrder.getStore().baseParams = {keyword : theThis.cmbSupplier.getValue(), searchType : 2, start : 0, limit : theThis.pageSize, isRequestFromExistingOrder : true};
theThis.grid_StockExistingOrder.getStore().load();
}
}),*/
theThis.btn_RequestCreditNote = new Ext.Button({
text : 'Request credit note',
tooltip : 'Request credit note',
iconCls: 'icon-daily-order', scale: 'large',
hidden : true,
handler : function(){
if (theThis.selectedInvoiceRecord != null && theThis.selectedInvoiceRecord.data.creditNoteProformaInvoiceId != null)
{
if (theThis.dlg_CreditNoteDetail == null) {
theThis.dlg_CreditNoteDetail = new Ext.CTBInvoiceDetailWindow({
title : 'Credit note',
isIgnoreWarningMarkingStockOrderAsInvoice : true,
instructionText : 'This is the invoice',
isForCreditNoteRequest : true,
isUsingProformaInvoiceId : false
});
}
theThis.dlg_CreditNoteDetail.setSelectedInvoiceRecord(theThis.selectedInvoiceRecord);
theThis.dlg_CreditNoteDetail.assignedSupplierId = theThis.selectedInvoiceRecord.data.supplierId;
// Assign the credit note
theThis.dlg_CreditNoteDetail.creditNoteProformaInvoiceId = theThis.selectedInvoiceRecord.data.creditNoteProformaInvoiceId;
theThis.dlg_CreditNoteDetail.callback_AfterShow = function(){
}
theThis.dlg_CreditNoteDetail.show();
}
}
}),
theThis.btn_Invoice_AddPaymentConfirmation = new Ext.Button({
text : 'Add Payment',
hidden : true,
tooltip : 'Add Payment Detail for this invoice',
iconCls: 'icon-money', scale: 'large',
handler : function(){
var selectedInvoiceRecord = theThis.selectedInvoiceRecord; //grid_Invoice.getStore().getById(theThis.selectedInvoiceId);
theThis.dlg_AddPaymentDetail.setSelectedInvoiceRecord(selectedInvoiceRecord);
theThis.dlg_AddPaymentDetail.show();
}
}),
theThis.btn_More = new Ext.Button({
iconCls : 'icon-v3-dropdown-more',
text : 'More',
iconAlign : 'right',
handler: function (button, e) {
if (theThis.menu_MoreOptions == null) {
theThis.menu_MoreOptions = new Ext.menu.Menu({
items:
[
theThis.btn_ShowExistingStockOrders = new Ext.menu.Item({
text : 'Show electronic orders',
tooltip : 'Show electronic orders from the selected Supplier. You can choose from the list to populate the invoice automatically.',
iconCls: 'icon-daily-order', scale: 'large',
hidden : theThis.HideShowExistingStockOrdersButton,
handler : function(){
theThis.grid_StockExistingOrder.getStore().baseParams = {keyword : theThis.cmbSupplier.getValue(), searchType : 2, start : 0, limit : theThis.pageSize, isRequestFromExistingOrder : true};
theThis.grid_StockExistingOrder.getStore().load();
}
}),
theThis.btn_DownloadInvoiceXML = new Ext.menu.Item({
text : 'Download XML',
//hidden : false,
hidden : theThis.isHideDevelopmentButtons,
tooltip : 'Download the invoice in XML format.',
scale : 'large',
iconCls : 'icon-xml-document',
handler : function(){
var selectedInvoiceRecord = theThis.selectedInvoiceRecord; //grid_Invoice.getStore().getById(theThis.selectedInvoiceId);
if (selectedInvoiceRecord.data.invoiceId > 0) {
window.location = String.format('/Invoice/DownloadPROACTISInvoiceXML?invoiceId={0}', selectedInvoiceRecord.data.invoiceId);
}
}
}),
theThis.btn_SendInvoiceXMLToFTPServer = new Ext.menu.Item({
text : 'Send XML to FTP',
hidden : theThis.isHideDevelopmentButtons,
tooltip : 'Send Invoice XML to FTP Server.',
scale : 'large',
iconCls : 'icon-xml-document',
handler : function(){
var selectedInvoiceRecord = theThis.selectedInvoiceRecord; //grid_Invoice.getStore().getById(theThis.selectedInvoiceId);
if (selectedInvoiceRecord.data.invoiceId > 0) {
theThis.loadMask.show();
// Calling delete
Ext.Ajax.request({
method: 'POST',
url: '/Invoice/SendPROACTISInvoiceXMLToFTP',
timeout : 1800000,
params:
{
invoiceId : selectedInvoiceRecord.data.invoiceId
},
success : function(result, request) {
theThis.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.loadMask.hide();
}
}); // End ajax
}
}
}),
theThis.btn_SendOrderXMLToFTPServer = new Ext.menu.Item({
text : 'Send order XML to FTP',
hidden : theThis.isHideDevelopmentButtons,
tooltip : 'Send related order XML to FTP Server.',
scale : 'large',
iconCls : 'icon-xml-document',
handler : function(){
var selectedInvoiceRecord = theThis.selectedInvoiceRecord; //grid_Invoice.getStore().getById(theThis.selectedInvoiceId);
if (selectedInvoiceRecord.data.invoiceId > 0) {
theThis.loadMask.show();
// Calling delete
Ext.Ajax.request({
method: 'POST',
url: '/Invoice/SendPROACTISRelatedOrderXMLToFTP',
timeout : 1800000,
params:
{
invoiceId : selectedInvoiceRecord.data.invoiceId
},
success : function(result, request) {
theThis.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.loadMask.hide();
}
}); // End ajax
}
}
})
] // menu items
}); // End menu declaration
} // End "if" checking menu existence
// Show the menu
theThis.menu_MoreOptions.show(e.getTarget());
} // End "More" button handler
}),
theThis.btn_Cancel = new Ext.Button({
text : 'Cancel',
iconCls: 'icon-cancel-large', scale: 'large',
handler : function(){
theThis.hide();
if (theThis.callback_AfterCancel != null) {
theThis.callback_AfterCancel();
}
}
})
];
return buttons;
},
saveData : function(){
var theThis = this;
var invoiceDate = theThis.txt_TopDetail_Date.getValue();
var invoiceNo = theThis.txt_TopDetail_InvoiceNo.getValue();
var invoiceType = theThis.cmb_TopDetail_InvoiceType.getValue();
var discount = theThis.txt_BottomDetail_Discount.getValue();
var freightIncludeGST = theThis.txt_BottomDetail_FreightIncludeGST.getValue();
var invoiceDetail = new Array();
var modifiedRecords = theThis.grid_InvoiceDetail.getGrid().getStore().getModifiedRecords();
for (var i = 0;i < modifiedRecords.length; i++)
{
var theRecord = modifiedRecords[i];
var modifiedDetail = {
invoiceDetailId : theRecord.get('invoiceDetailId'),
stockQty : theRecord.get('stockQty'),
invoiceDetailCost : theRecord.get('invoiceDetailCost'),
invoiceDetailTax : theRecord.get('invoiceDetailTax'),
stockSupplierId : theRecord.get('stockSupplierId'),
stockId : theRecord.get('stockId'),
discountPercentage : theRecord.get('discountPercentage')
}
invoiceDetail[i] = modifiedDetail;
}
var invoiceObject = {
invoiceId : theThis.isUsingProformaInvoiceId == true ? theThis.selectedProformaInvoiceId : theThis.selectedInvoiceId,
invoiceDate : invoiceDate,
invoiceNo : invoiceNo,
isReturned : invoiceType,
discount : isNaN(discount) ? 0 : discount,
freightIncludeGST : isNaN(freightIncludeGST) ? 0 : freightIncludeGST,
invoiceDetail : invoiceDetail,
supplierId : theThis.cmbSupplier.getValue(),
businessDepartmentId : theThis.cmbBusinessDepartment.getValue()
}
var invoiceJsonData = Ext.util.JSON.encode(invoiceObject);
theThis.loadMask.show();
// Sending ajax request
Ext.Ajax.request({
method: "POST",
url: theThis.saveInvoiceURL,
params:
{
invoiceData : invoiceJsonData
},
success : function(result, request) {
theThis.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
/* Reload Invoice Detail */
theThis.grid_InvoiceDetail.getGrid().getStore().commitChanges();
theThis.hide();
theThis.selectedInvoiceId = jsonData.data.newId;
if (theThis.selectedExistingStockOrderId != -1 && theThis.selectedProformaInvoiceId == -1){ // Not going to do this if the proforma invoice has been set for this dialog
//if (!theThis.isIgnoreWarningMarkingStockOrderAsInvoice) {
//showConfirmMessage('Do you want to hide the existing order ?', function(){
theThis.markStockOrderAsInvoice(theThis.selectedExistingStockOrderId, theThis.selectedInvoiceId, theThis.callback_AfterSave);
theThis.selectedExistingStockOrderId = -1;
//});
//}
//else {
//theThis.markStockOrderAsInvoice(theThis.selectedExistingStockOrderId, theThis.selectedInvoiceId, theThis.callback_AfterSave);
//theThis.selectedExistingStockOrderId = -1;
//}
}
else {
//if (theThis.selectedProformaInvoiceId != -1){
//theThis.markProformaInvoiceAsTransfered(theThis.callback_AfterSave);
//}
//else {
/* Reload Invoice */
if (theThis.callback_AfterSave != null){
theThis.callback_AfterSave(jsonData.data);
//grid_Invoice.getStore().reload(); **********
//theThis.callback_AfterSave = null;
}
//}
}
if (jsonData.data != null && jsonData.data.newId != null) {
// Silently calling for checking over limit when changing stock price
// This function is in global.js
checkingOverLimitWhenChangingStockPrice(theThis.selectedInvoiceId);
}
// Disable the warning when close the page
disableWarningWhenClosePage();
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
showErrorMessage("Server is unavailable. Please try again in a few seconds.");
theThis.loadMask.hide();
}
}); // End ajax
},
saveCreditNoteRequest : function(callback_Function){
var theThis = this;
theThis.grid_CreditNoteDetail.getGrid().stopEditing();
var creditNoteProformaInvoiceId = theThis.creditNoteProformaInvoiceId;
var invoiceDate = theThis.txt_TopDetail_Date.getValue();
var invoiceNo = theThis.txt_TopDetail_InvoiceNo.getValue();
var invoiceId = theThis.selectedInvoiceRecord.data.invoiceId;
var supplierId = theThis.selectedInvoiceRecord.data.supplierId;
var creditNoteDetails = new Array();
for (var i = 0; i < theThis.grid_CreditNoteDetail.getGrid().getStore().getCount(); i++) {
var theRecord = theThis.grid_CreditNoteDetail.getGrid().getStore().getAt(i);
creditNoteDetails[i] = {
stockId : theRecord.data.stockId,
receivedQty : theRecord.data.stockQty
}
}
var creditNoteWrapper = {
creditNoteProformaInvoiceId : creditNoteProformaInvoiceId,
invoiceId : invoiceId,
invoiceNo : invoiceNo,
invoiceDate : invoiceDate,
supplierId : supplierId,
creditNoteDetails : creditNoteDetails
}
theThis.grid_CreditNoteDetail.loadMask.show();
// Calling delete
Ext.Ajax.request({
method: 'POST',
url: '/ProformaInvoice/SaveCreditNoteRequest',
params:
{
creditNoteData : Ext.util.JSON.encode(creditNoteWrapper)
},
success : function(result, request) {
theThis.grid_CreditNoteDetail.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
theThis.creditNoteProformaInvoiceId = jsonData.data.creditNoteProformaInvoiceId;
theThis.selectedInvoiceRecord.data.creditNoteProformaInvoiceId = theThis.creditNoteProformaInvoiceId;
theThis.grid_CreditNoteDetail.getGrid().getStore().commitChanges();
if (callback_Function != null)
callback_Function();
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.grid_CreditNoteDetail.loadMask.hide();
}
}); // End ajax
},
markCreditNoteAsProcessed : function(creditNoteProformaInvoiceId){
var theThis = this;
theThis.loadMask.show();
// Calling delete
Ext.Ajax.request({
method: 'POST',
url: '/ProformaInvoice/UpdateProformaInvoiceStatus',
params:
{
proformaInvoiceId : creditNoteProformaInvoiceId,
status : PROFORMA_INVOICE_STATUS.CREDIT_NOTE_TURNED_TO_RETURN_INVOICE
},
success : function(result, request) {
theThis.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
//showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.loadMask.hide();
}
}); // End ajax
},
sendCreditNoteRequest : function(callback_Function){
var theThis = this;
if (theThis.creditNoteProformaInvoiceId == -1){
showErrorNotification('Notice', 'Please save the credit note first');
}
else {
Global_ContactBrowser_CallbackFunction = function(selectedRecords)
{
var recipients = "";
for(var i = 0;iDiscount / Adjustment',
xtype : 'moneyfield',
listeners : {
'spin' : function(p_field, p_down, p_alternative){
var totalValue = roundNumber(theThis.grid_InvoiceDetail.getGrid().getStore().sum('invoiceDetailSubtotal'), 2);
theThis.txt_BottomDetail_Total.setValue(totalValue - this.getValue());
}
},
onBlur : function(p_field){
if (isNaN(this.getValue()))
{
this.setValue(0);
}
var totalValue = roundNumber(theThis.grid_InvoiceDetail.getGrid().getStore().sum('invoiceDetailSubtotal'), 2);
theThis.txt_BottomDetail_Total.setValue(totalValue - this.getValue());
},
precision: true,
decimalPrecision: 2,
width : 200
}),
theThis.txt_BottomDetail_FreightIncludeGST = new Ext.form.MoneyField({
fieldLabel: 'Freight (Include GST)',
xtype : 'moneyfield',
minValue : 0,
listeners : {
'spin' : function(p_field, p_down, p_alternative){
theThis.refreshCalculatingField();
}
},
onBlur : function(p_field){
if (isNaN(this.getValue()))
{
this.setValue(0);
}
theThis.refreshCalculatingField();
},
precision: true,
decimalPrecision: 2,
width : 200
}),
theThis.txt_BottomDetail_Total = new Ext.form.MoneyField({
fieldLabel: 'Total [Actual]',
xtype : 'moneyfield',
disabledSpinner : true,
readOnly : true,
precision: true,
decimalPrecision: 2,
width : 200
})]
});
var pnl_BottomDetail = new Ext.Panel({
region : 'south',
layout : 'border',
height : 120,
items : [{xtype : 'panel', region : 'center'},frm_RightForm],
frame: true,
loadMask: true,
viewConfig:
{
enableRowBody: true,
forceFit: true // IMPORTANT (USE THIS ATTRIBUTE TO USE PERCENTAGE IN COLUMN MODEL)
}
});
return pnl_BottomDetail;
},
getCombobox_Supplier : function(){
var theThis = this;
var store = new Ext.data.JsonStore({
baseParams : {isFromImportDatabase : false},
proxy: new Ext.data.HttpProxy({
url: '/Supplier/GetAllSuppliers',
dataType: 'json',
method: 'POST'
}),
fields: [
{ name: 'supId' , type: 'number' },
{ name: 'supName' , type: 'string' },
{ name: 'supFolderId' , type: 'number' },
{ name: 'abnNo' , type: 'string' },
{ name: 'accNo' , type: 'string' },
{ name: 'paymentTerm' , type: 'string' },
{ name: 'website' , type: 'string' },
{ name: 'defaultStockCategoryId', type: 'number' }
],
autoLoad : false,
root: 'data',
idProperty : 'supId',
listeners : {
'loadexception' : function(){
showStoreLoadingErrorMessage(store);
},
load : function(){
if ((theThis.cmbSupplier.lastQuery == null || theThis.cmbSupplier.lastQuery == "")){
if (theThis.selectedInvoiceId != -1){
var selectedInvoiceRecord = theThis.selectedInvoiceRecord;
var supplierId = selectedInvoiceRecord.data.supplierId;
if (supplierId != -1){
theThis.cmbSupplier.setValue(supplierId);
}
else theThis.cmbSupplier.setValue(store.getAt(0).get('supId'));
}
else if (theThis.assignedSupplierId != -1 && store.getCount() > 0){
theThis.cmbSupplier.setValue(theThis.assignedSupplierId);
}
else if (theThis.selectedInvoiceId == -1 && store.getCount() > 0){
theThis.cmbSupplier.setValue(store.getAt(0).get('supId'));
}
}
theThis.cmbBusinessDepartment.getStore().load();
}
}
});
var cmbSupplier = new Ext.form.ComboBox({
store: store,
displayField: 'supName',
valueField: 'supId',
typeAhead: true,
triggerAction: 'all',
minChars: 1,
lazyRender: true,
editable: true,
forceSelection: true,
emptyText: 'Select a Supplier...',
//valueNotFoundText: 'Select a Supplier...',
fieldLabel : 'Supplier',
width: 200,
//style: { fontSize: '11px' },
mode : 'remote',
listeners : {
beforequery: function(qe){
delete qe.combo.lastQuery; // Reload every click
},
beforeselect : function( p_combo, p_record, p_index ){
var oldValue = theThis.cmbSupplier.getValue();
if (theThis.grid_InvoiceDetail.getGrid().getStore().getCount() > 0){
Ext.Msg.show({
title:'Confirm',
msg: 'Are you sure you want to change supplier ? All detail will be cleared ! ',
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.QUESTION,
fn : function(btn) {
if (btn == "yes") {
// Only run ajax request if the invoice exist
if (theThis.selectedInvoiceId != -1){
theThis.loadMask.show();
// Calling delete
Ext.Ajax.request({
method: 'POST',
url: '/Invoice/DeleteAllInvoiceDetailByInvoiceId',
params:
{
invoiceId : theThis.selectedInvoiceId
},
success : function(result, request) {
theThis.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
//grid_Invoice.getStore().load();
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.loadMask.hide();
}
}); // End ajax
} // End if
else {
theThis.grid_InvoiceDetail.getGrid().getStore().removeAll();
}
} // End if
else {
theThis.cmbSupplier.doQuery("", true);
return false;
} // End else
}
}); // End show message
} // End if
}
}
});
return cmbSupplier;
},
getCombobox_BusinessDepartment : function(){
var theThis = this;
var store = new Ext.data.JsonStore({
baseParams : {supplierId : -1},
proxy: new Ext.data.HttpProxy({
url: '/BusinessDepartment/GetBusinessDepartmentsBySupplierId',
dataType: 'json',
method: 'POST'
}),
fields: [
{ name: 'businessDepartmentId' , type: 'number' },
{ name: 'businessDepartmentName' , type: 'string' }
],
autoLoad : false,
root: 'data',
idProperty : 'businessDepartmentId',
listeners : {
'loadexception' : function(){
showStoreLoadingErrorMessage(store);
},
beforeload : function(){
theThis.cmbBusinessDepartment.getStore().baseParams = {supplierId : theThis.cmbSupplier.getValue()};
//theThis.cmbBusinessDepartment.getStore().load();
},
load : function(){
if ((theThis.cmbBusinessDepartment.lastQuery == null || theThis.cmbBusinessDepartment.lastQuery == "")){
if (theThis.selectedInvoiceId != -1){
var selectedInvoiceRecord = theThis.selectedInvoiceRecord;
var businessDepartmentId = selectedInvoiceRecord.data.businessDepartmentId;
if (businessDepartmentId != -1){
theThis.cmbBusinessDepartment.setValue(businessDepartmentId);
}
else theThis.cmbBusinessDepartment.setValue(store.getAt(0).get('businessDepartmentId'));
}
/*else if (theThis.assignedSupplierId != -1 && store.getCount() > 0){
theThis.cmbBusinessDepartment.setValue(theThis.assignedSupplierId);
}*/
else if (theThis.selectedInvoiceId == -1 && store.getCount() > 0){
theThis.cmbBusinessDepartment.setValue(store.getAt(0).get('businessDepartmentId'));
}
}
}
}
});
var cmbBusinessDepartment = new Ext.form.ComboBox({
store: store,
displayField: 'businessDepartmentName',
valueField: 'businessDepartmentId',
typeAhead: true,
triggerAction: 'all',
minChars: 1,
lazyRender: true,
editable: true,
forceSelection: true,
emptyText: 'Select a business department...',
fieldLabel : 'Business department',
width: 200,
//style: { fontSize: '11px' },
mode : 'remote',
listeners : {
beforequery: function(qe){
delete qe.combo.lastQuery; // Reload every click
},
beforeselect : function( p_combo, p_record, p_index ){
}
}
});
return cmbBusinessDepartment;
},
// This function validate all the field in the invoice detail before it's being saved
validateBeforeSave : function()
{
var theThis = this;
var validateFields = new Array();
validateFields[0] = {
ID : theThis.txt_TopDetail_InvoiceNo.id,
VALIDATION_TYPE : VALIDATION_CONSTANTS.EMPTY
};
validateFields[1] = {
ID : theThis.txt_TopDetail_Date.id,
VALIDATION_TYPE : VALIDATION_CONSTANTS.DATE
};
validateFields[2] = {
ID : theThis.txt_TopDetail_Total.id,
CUSTOM_FUNCTION : function(){
var userTotal = theThis.txt_TopDetail_Total.getValue();
var actualTotal = theThis.txt_BottomDetail_Total.getValue();
if (userTotal != actualTotal){
return false;
}
return true;
},
CUSTOM_MESSAGE : 'The total from invoice doesn\'t match with the actual total Please check the detail to make sure your input is right!',
VALIDATION_TYPE : VALIDATION_CONSTANTS.CUSTOM
};
validateFields[3] = {
ID : theThis.txt_BottomDetail_Discount.id,
CUSTOM_FUNCTION : function(){
var discountValue = theThis.txt_BottomDetail_Discount.getValue();
if (discountValue < 0)
{
return true;
}
return true;
},
CUSTOM_MESSAGE : 'Discount is negative by default. You don\'t need to specify negative sign for the discount value!',
VALIDATION_TYPE : VALIDATION_CONSTANTS.CUSTOM
};
validateFields[4] = {
ID : theThis.cmbSupplier.id,
VALIDATION_TYPE : VALIDATION_CONSTANTS.EMPTY
};
// Call global validate field group
return validateFieldGroup(validateFields);
},
markStockOrderAsInvoice : function(stockOrderId, invoiceId, callback_Function){
var theThis = this;
theThis.loadMask.show();
Ext.Ajax.request({
method: 'POST',
url: '/StockOrder/MarkStockOrderAsInvoice',
params:
{
stockOrderId : stockOrderId,
invoiceId : invoiceId
},
success : function(result, request) {
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
if (callback_Function != null) callback_Function();
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
theThis.loadMask.hide();
},
failure : function(result, request) {
theThis.loadMask.hide();
}
}); // End ajax
},
getDialog_AddPaymentDetail : function(){
var theThis = this;
var frm_Input = new Ext.form.FormPanel({
url: '',
frame : true,
region : 'center',
labelWidth : 150,
defaults: {
width: 225,
msgTarget: 'side'
},
listeners : {
afterrender : function(p_this){
},
beforeaction : function(p_This, p_Action){
},
actioncomplete : function(p_This, p_Action){
},
actionfailed : function(p_This, p_Action){
}
},
items : [
theThis.txt_Invoice_Payment_PaymentDate = new Ext.form.DateField({
xtype : 'datefield',
format : "j/n/Y",
altFormats : 'j/n/y',
name : 'paymentDate',
value : new Date(),
fieldLabel : 'Payment date',
allowBlank : false
}),
theThis.txt_Invoice_Payment_BankReferenceID = new Ext.form.TextField({
xtype : 'textfield',
name : 'paidAmount',
value : '',
allowBlank: false,
fieldLabel : 'Bank Reference Number',
onFocus: function (txt, e) {
this.getEl().dom.select();
}
}),
theThis.txt_Invoice_Payment_PaidAmount = new Ext.form.NumberField({
xtype : 'numberfield',
name : 'paidAmount',
value : 0,
allowBlank: false,
allowNegative: false,
minValue : 0,
allowDecimals : true,
decimalPrecision: 2,
fieldLabel : 'Paid Amount($)',
onFocus: function (txt, e) {
this.getEl().dom.select();
}
}),
theThis.txt_Invoice_Payment_SurchargeAmount = new Ext.form.NumberField({
xtype : 'numberfield',
name : 'surchargeAmount',
value : 0,
allowBlank: false,
allowNegative: false,
minValue : 0,
allowDecimals : true,
decimalPrecision: 2,
fieldLabel : 'Surcharge Amount($)',
onFocus: function (txt, e) {
this.getEl().dom.select();
}
})
]
});
var dlg_AddPaymentDetail = new Ext.Window({
closeAction : 'hide',
width : 425,
height : 200,
frame : true,
modal : true,
title : 'Add Payment Detail',
layout : 'border',
selectedInvoiceRecord : null,
setSelectedInvoiceRecord : function(invoiceRecord){
dlg_AddPaymentDetail.selectedInvoiceRecord = invoiceRecord;
// Editing the title
theThis.setTitle(String.format('Add Payment Detail for Invoice No : {0}', dlg_AddPaymentDetail.selectedInvoiceRecord.data.invoiceNo));
theThis.txt_Invoice_Payment_PaymentDate.setValue(new Date());
theThis.txt_Invoice_Payment_BankReferenceID.setValue('');
theThis.txt_Invoice_Payment_PaidAmount.setValue(dlg_AddPaymentDetail.selectedInvoiceRecord.data.totalAmount);
theThis.txt_Invoice_Payment_SurchargeAmount.setValue(0);
},
items : [
frm_Input
],
buttons : [
{
xtype : 'button',
iconCls : 'icon-money',
scale : 'large',
text : 'Submit',
handler : function(){
if (!theThis.txt_Invoice_Payment_PaymentDate.isValid()) return;
if (!theThis.txt_Invoice_Payment_BankReferenceID.isValid()) return;
if (!theThis.txt_Invoice_Payment_PaidAmount.isValid()) return;
if (!theThis.txt_Invoice_Payment_SurchargeAmount.isValid()) return;
theThis.loadMask.show();
// Calling ajax request to save payment detail
Ext.Ajax.request({
method: 'POST',
url: '/Invoice/AddPaymentDetail',
timeout: 1800000,
params:
{
invoiceId : theThis.dlg_AddPaymentDetail.selectedInvoiceRecord.data.invoiceId,
paymentDate : theThis.txt_Invoice_Payment_PaymentDate.getValue(),
bankReferenceID : theThis.txt_Invoice_Payment_BankReferenceID.getValue(),
paidAmount : theThis.txt_Invoice_Payment_PaidAmount.getValue(),
surchargeAmount : theThis.txt_Invoice_Payment_SurchargeAmount.getValue()
},
success : function(result, request) {
theThis.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
theThis.dlg_AddPaymentDetail.hide();
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.loadMask.hide();
}
}); // End ajax
}
},{
xtype : 'button',
iconCls : 'icon-cancel-large',
scale : 'large',
text : 'Cancel',
handler : function(){
theThis.dlg_AddPaymentDetail.hide();
}
}
]
});
return dlg_AddPaymentDetail;
},
// This function return a dialog that allow user choose a order as a invoice
// By a specific supplier
getStockExistingOrderDialog : function(){
var theThis = this;
// ***************************************************************************************************
// Data Fields
// ***************************************************************************************************
var record = Ext.data.Record.create([
{ name: 'stockOrderId' , type: 'number' },
{ name: 'stockOrderDate' , type: 'date'},
{ name: 'stockOrderNo' , type: 'string'},
{ name: 'supplierName' , type: 'string' },
{ name: 'supplierId' , type: 'number' },
{ name: 'stockOrderTotal' , type: 'number' }
]);
// ***************************************************************************************************
// Stores
// ***************************************************************************************************
var store = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy({
url: '/StockOrder/SearchStockOrders',
dataType: 'json',
method: 'POST'
}),
autoLoad : false,
fields: record,
root: 'data',
idProperty: 'stockOrderId',
totalProperty: 'totalCount',
listeners : {
load : function(){
if (store.getCount() > 0){
// If there's some stock order that need invoice from a specific supplier
// Show the dialog to let user choose that order as a invoice
theThis.dlg_StockExistingOrder.show();
}
else {
showSuccessNotification('You don\'t have any stock orders from this supplier.', NOTIFICATION.ICON_INFORMATION);
theThis.dlg_StockExistingOrder.hide();
}
},
'loadexception' : function(){
showStoreLoadingErrorMessage(store);
}
}
});
// ****************************************************************************************************
// Selection Models
// ****************************************************************************************************
var sm = new Ext.grid.CheckboxSelectionModel({
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
// Do nothing at the moment
},
beforerowselect: function(o, rowIndex, keepExisting, record) {
}
}
});
// ****************************************************************************************************
// Column Models
// ****************************************************************************************************
var cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults: {
sortable: true // columns are not sortable by default
},
columns: [ sm,
{ header: 'stockOrderId', dataIndex: 'stockOrderId', hidden: true },
{ header: 'Date', dataIndex: 'stockOrderDate', width: 40,
renderer : function(val){
return Ext.util.Format.date(val, 'd/m/Y');
}
},
{ header: 'Supplier(s)', dataIndex: 'stockOrderId', width: 50,
renderer : function(val){
var supplierId = store.getById(val).get('supplierId');
var supplierName = store.getById(val).get('supplierName');
if (supplierId != -1){
return ''+supplierName+' ';
}
else {
if (supplierName != ""){
var suppliers = supplierName.split(";");
var result = '';
for (var i = 0;i'+suppliers[i]+' ';
}
result += ' ';
return result;
}
else {
return '[None] ';
}
}
}
},
{ header: 'Total', dataIndex: 'stockOrderTotal', width: 10,
renderer : Ext.util.Format.usMoney
}
]
});
/****************************/
/* Grid */
/****************************/
var grid = new Ext.grid.EditorGridPanel({
store: store,
title: 'Stock orders',
region : 'center',
frame: true,
listeners : {
rowclick : function ( p_this, p_rowIndex, p_eventObject ) {
var selectedStockOrderId = p_this.getStore().getAt(p_rowIndex).get("stockOrderId");
theThis.selectedExistingStockOrderId = selectedStockOrderId;
// Hightlight the selected row
var selectedRow = p_this.getView().getRow(p_rowIndex);
Ext.get(selectedRow).highlight();
},
rowdblclick : function( p_this, p_rowIndex, p_eventObject) {
theThis.btn_Invoice_StockExistingOrder.handler.call(theThis.btn_Invoice_StockExistingOrder.scope);
}
},
tbar : [
theThis.btn_StockExistingOrder_Delele = new Ext.Button({
tooltip : 'Mark the selected order so they will not appear in the list as suggestions anymore.',
iconCls: 'icon-delete',
text: 'Delete',
scale : 'large',
handler : function(){
var selectedRecords = grid.getSelectionModel().getSelections();
if (selectedRecords.length > 0){
showConfirmMessage('Are you sure you want to hide these stock orders from suggestion window ? ', function(){
var listOfIds = new Array();
for (var i = 0; i < selectedRecords.length; i++){
listOfIds[i] = selectedRecords[i].data.stockOrderId;
}
var wrapperObject = {listOfNumbers : listOfIds}
grid.loadMask.show();
Ext.Ajax.request({
method: 'POST',
url: '/StockOrder/HideSuggestionStockOrdersInInvoice',
params:
{
listOfStockOrderIds : Ext.util.JSON.encode(wrapperObject)
},
success : function(result, request) {
grid.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
grid.getStore().reload();
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
grid.loadMask.hide();
}
}); // End ajax
});
}
else {
showErrorNotification('Notice', 'Please choose item to delele !');
}
}
})
],
cm: cm,
sm: sm,
autoHeight: false,
clicksToEdit: 1,
loadMask: true,
bbar: new Ext.PagingToolbar({
store: store,
pageSize: theThis.pageSize,
displayInfo: true,
displayMsg: 'Displaying results {0} - {1} of {2}',
emptyMsg: "No orders to display"
}),
viewConfig:
{
enableRowBody: true,
forceFit: true // IMPORTANT (USE THIS ATTRIBUTE TO USE PERCENTAGE IN COLUMN MODEL)
}
});
theThis.grid_StockExistingOrder = grid;
var dialog = new Ext.Window({
title: 'Stock - Existing Order',
layout: 'border',
closeAction: 'hide',
iconCls : 'icon-stock',
expandOnShow : true,
closable: true,
resizable: true,
modal: true,
plain: true,
minimizable : true,
maximizable : true,
monitorResize : true,
//maximized : true,
width:800,
height:500,
defaults: {
split: true,
animFloat: false,
autoHide: false,
useSplitTips: true
},
buttons: [
theThis.btn_Invoice_StockExistingOrder = new Ext.Button({
text: 'Select',
iconCls : 'icon-ok-large', scale : 'large',
handler : function(){
var selectedRecords = grid.getSelectionModel().getSelections();
if (selectedRecords.length == 0){
showErrorNotification('Notice', 'Please choose an order from the list to fill the invoice !');
}
else if (selectedRecords.length != 1){
showErrorNotification('Notice', 'Please select only one order from the list !');
}
else {
theThis.getInvoiceDetailFromExistingOrder(function(){
dialog.hide();
});
}
/*if (Global_SelectedExistingStockOrderId != -1){
}
else {
Ext.Msg.show({
title:'Notice',
msg: 'Please choose an order from the list to fill the invoice !',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
} */
}
}),
theThis.btn_Cancel = new Ext.Button({
text: 'Cancel',
iconCls : 'icon-cancel-large', scale : 'large',
handler : function(){
dialog.hide();
}
})],
items : [grid],
listeners : {
'beforeshow' : function(p_This){
// Fit this window to the client browser screen with 60%
fitWindowSize(p_This, 60);
},
'beforehide' : function(){
}
}
});
return dialog;
},
getInvoiceDetailFromExistingOrder : function(callback_Function){
var theThis = this;
theThis.loadMask.show();
Ext.Ajax.request({
method: 'POST',
url: '/Invoice/GetInvoiceDetailFromExistingOrder',
params:
{
stockOrderId : theThis.selectedExistingStockOrderId
},
success : function(result, request) {
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification('Existing order populated', NOTIFICATION.ICON_INFORMATION);
for(var i = 0; i < jsonData.data.length; i++)
{
var newInvoiceDetailId = -getRandomNumber(); // Negative for new entry
var invoiceDetailTax = jsonData.data[i].isGstApplied == false ? 0 : roundNumber((jsonData.data[i].supplierCost * jsonData.data[i].stockQty * CTB.init.expenseTax.percentage)/100, 2);
var store = theThis.grid_InvoiceDetail.getGrid().getStore();
var aNewDetail = new store.recordType({
invoiceDetailId : newInvoiceDetailId, // Negative for new entry
invoiceId : theThis.selectedInvoiceId,
supplierStockCode : jsonData.data[i].supplierStockCode,
stockDesc : jsonData.data[i].stockDesc,
stockUnit : jsonData.data[i].stockUnit,
stockUnitOfMeasurementId : jsonData.data[i].stockUnitOfMeasurementId,
stockQty : 0, // Change later, look at below code
stockId : jsonData.data[i].stockId,
stockSupplierId : jsonData.data[i].stockSupplierId,
invoiceDetailCost : jsonData.data[i].supplierCost,
invoiceDetailTax : invoiceDetailTax,
isGstApplied : jsonData.data[i].isGstApplied,
invoiceDetailSubtotal : roundNumber(jsonData.data[i].stockQty * jsonData.data[i].supplierCost + invoiceDetailTax, 2), // Quantity = 1, then subtotal = cost
discountPercentage : jsonData.data[i].discountPercentage
}, newInvoiceDetailId);
theThis.grid_InvoiceDetail.getGrid().getStore().insert(theThis.grid_InvoiceDetail.getGrid().getStore().getCount(), aNewDetail);
theThis.grid_InvoiceDetail.getGrid().getStore().getById(newInvoiceDetailId).set('stockQty', jsonData.data[i].stockQty);
theThis.grid_InvoiceDetail.updateTheSubtotal(theThis.grid_InvoiceDetail.getGrid().getStore().getById(newInvoiceDetailId));
if (theThis.grid_CreditNoteDetail != null && theThis.isForCreditNoteRequest){
theThis.grid_CreditNoteDetail.getGrid().getStore().insert(theThis.grid_CreditNoteDetail.getGrid().getStore().getCount(), aNewDetail);
theThis.grid_CreditNoteDetail.getGrid().getStore().getById(newInvoiceDetailId).set('stockQty', jsonData.data[i].stockQty);
theThis.grid_CreditNoteDetail.updateTheSubtotal(theThis.grid_CreditNoteDetail.getGrid().getStore().getById(newInvoiceDetailId));
}
}
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
//Global_SelectedExistingStockOrderId = -1;
theThis.loadMask.hide();
if (callback_Function != null)
callback_Function();
//dialog.hide();
},
failure : function(result, request) {
theThis.loadMask.hide();
}
}); // End ajax
},
getInvoiceDetailFromProformaInvoice : function(callback_Function, isFromCreditNoteProformaInvoice){
var theThis = this;
if (isFromCreditNoteProformaInvoice == null) isFromCreditNoteProformaInvoice = false;
theThis.loadMask.show();
Ext.Ajax.request({
method: 'POST',
url: isFromCreditNoteProformaInvoice == false ? '/Invoice/GetInvoiceDetailFromProformaInvoice' : '/Invoice/GetInvoiceDetailFromCreditNoteProformaInvoice',
params:
{
proformaInvoiceId : theThis.selectedProformaInvoiceId
},
success : function(result, request) {
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification('Purchase Order Populated', NOTIFICATION.ICON_INFORMATION);
var isSetTheTotalDiscount = false;
var isSetTheTotalFreight = false;
var isSetTheInvoiceNumber = false;
var isSetTheInvoiceDate = false;
var isSetTheInvoiceType = false;
for(var i = 0; i < jsonData.data.length; i++)
{
var newInvoiceDetailId = -getRandomNumber(); // Negative for new entry
var invoiceDetailId = theThis.isUsingProformaInvoiceId == false ? newInvoiceDetailId : jsonData.data[i].proformaInvoiceDetailId;
//var invoiceDetailTax = jsonData.data[i].isGstApplied == false ? 0 : roundNumber((jsonData.data[i].supplierCost * jsonData.data[i].stockQty * Global_GSTPercentage)/100, 2);
var store = theThis.grid_InvoiceDetail.getGrid().getStore();
var aNewDetail = new store.recordType({
invoiceDetailId : invoiceDetailId, // Negative for new entry
invoiceId : theThis.isUsingProformaInvoiceId == false ? theThis.selectedInvoiceId : jsonData.data[i].proformaInvoiceId,
supplierStockCode : jsonData.data[i].supplierStockCode,
stockDesc : jsonData.data[i].stockDesc,
stockUnit : jsonData.data[i].stockUnit,
stockUnitOfMeasurementId : jsonData.data[i].stockUnitOfMeasurementId,
stockQty : 0, // Change later, look at below code
stockId : jsonData.data[i].stockId,
stockSupplierId : jsonData.data[i].stockSupplierId,
invoiceDetailCost : jsonData.data[i].supplierCost,
invoiceDetailTax : jsonData.data[i].invoiceDetailTax,
isGstApplied : jsonData.data[i].isGstApplied,
invoiceDetailSubtotal : roundNumber(jsonData.data[i].stockQty * jsonData.data[i].supplierCost + jsonData.data[i].invoiceDetailTax, 2), // Quantity = 1, then subtotal = cost
discountPercentage : jsonData.data[i].discountPercentage
}, invoiceDetailId);
theThis.grid_InvoiceDetail.getGrid().getStore().insert(theThis.grid_InvoiceDetail.getGrid().getStore().getCount(), aNewDetail);
theThis.grid_InvoiceDetail.getGrid().getStore().getById(invoiceDetailId).set('stockQty', jsonData.data[i].stockQty);
var theRecord = theThis.grid_InvoiceDetail.getGrid().getStore().getById(invoiceDetailId);
if (jsonData.data[i].invoiceDetailTax != 0) theRecord.isModified = true;
// Set the total discount (rounding, adjustment, etc, ...)
if (jsonData.data[i].totalDiscount != null && !isSetTheTotalDiscount){
isSetTheTotalDiscount = true;
theThis.txt_BottomDetail_Discount.setValue(jsonData.data[i].totalDiscount);
}
// Set the total freight
if (jsonData.data[i].totalFreight != null && !isSetTheTotalFreight){
isSetTheTotalFreight = true;
theThis.txt_BottomDetail_FreightIncludeGST.setValue(jsonData.data[i].totalFreight);
}
// Set the invoice number
if (jsonData.data[i].invoiceNo != null && !isSetTheInvoiceNumber){
isSetTheInvoiceNumber = true;
theThis.txt_TopDetail_InvoiceNo.setValue(jsonData.data[i].invoiceNo);
}
// Set the invoice date
if (jsonData.data[i].invoiceDate != null && !isSetTheInvoiceDate){
isSetTheInvoiceDate = true;
theThis.txt_TopDetail_Date.setValue(new Date(jsonData.data[i].invoiceDate));
}
// Set the invoice type
if (jsonData.data[i].isReturned != null && !isSetTheInvoiceType){
isSetTheInvoiceType = true;
theThis.cmb_TopDetail_InvoiceType.setValue(jsonData.data[i].isReturned);
}
// Update the line subtotal
theThis.grid_InvoiceDetail.updateTheSubtotal(theRecord);
if (theThis.grid_CreditNoteDetail != null && theThis.isForCreditNoteRequest){
theThis.grid_CreditNoteDetail.getGrid().getStore().insert(theThis.grid_CreditNoteDetail.getGrid().getStore().getCount(), aNewDetail);
theThis.grid_CreditNoteDetail.getGrid().getStore().getById(invoiceDetailId).set('stockQty', jsonData.data[i].stockQty);
theThis.grid_CreditNoteDetail.updateTheSubtotal(theThis.grid_CreditNoteDetail.getGrid().getStore().getById(invoiceDetailId));
}
}
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
//Global_SelectedExistingStockOrderId = -1;
theThis.loadMask.hide();
if (callback_Function != null)
callback_Function();
//dialog.hide();
},
failure : function(result, request) {
theThis.loadMask.hide();
}
}); // End ajax
},
getCreditNoteDetailFromProformaInvoice : function(proformaInvoiceId, callback_Function){
var theThis = this;
theThis.grid_CreditNoteDetail.loadMask.show();
Ext.Ajax.request({
method: 'POST',
url: '/Invoice/GetInvoiceDetailFromProformaInvoice',
params:
{
proformaInvoiceId : proformaInvoiceId
},
success : function(result, request) {
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
//showSuccessNotification('Credit note populated', NOTIFICATION.ICON_INFORMATION);
for(var i = 0; i < jsonData.data.length; i++)
{
var newInvoiceDetailId = -getRandomNumber(); // Negative for new entry
var invoiceDetailId = theThis.isUsingProformaInvoiceId == false ? newInvoiceDetailId : jsonData.data[i].proformaInvoiceDetailId;
//var invoiceDetailTax = jsonData.data[i].isGstApplied == false ? 0 : roundNumber((jsonData.data[i].supplierCost * jsonData.data[i].stockQty * Global_GSTPercentage)/100, 2);
var store = theThis.grid_CreditNoteDetail.getGrid().getStore();
var aNewDetail = new store.recordType({
invoiceDetailId : invoiceDetailId, // Negative for new entry
invoiceId : theThis.isUsingProformaInvoiceId == false ? theThis.selectedInvoiceId : jsonData.data[i].proformaInvoiceId,
supplierStockCode : jsonData.data[i].supplierStockCode,
stockDesc : jsonData.data[i].stockDesc,
stockUnit : jsonData.data[i].stockUnit,
stockUnitOfMeasurementId : jsonData.data[i].stockUnitOfMeasurementId,
stockQty : jsonData.data[i].stockQty, // Change later, look at below code
stockId : jsonData.data[i].stockId,
stockSupplierId : jsonData.data[i].stockSupplierId,
invoiceDetailCost : jsonData.data[i].supplierCost,
invoiceDetailTax : jsonData.data[i].invoiceDetailTax,
isGstApplied : jsonData.data[i].isGstApplied,
invoiceDetailSubtotal : roundNumber(jsonData.data[i].stockQty * jsonData.data[i].supplierCost + jsonData.data[i].invoiceDetailTax, 2), // Quantity = 1, then subtotal = cost
discountPercentage : jsonData.data[i].discountPercentage
}, invoiceDetailId);
if (theThis.grid_CreditNoteDetail != null && theThis.isForCreditNoteRequest){
theThis.grid_CreditNoteDetail.getGrid().getStore().insert(theThis.grid_CreditNoteDetail.getGrid().getStore().getCount(), aNewDetail);
theThis.grid_CreditNoteDetail.getGrid().getStore().getById(invoiceDetailId).set('stockQty', jsonData.data[i].stockQty);
theThis.grid_CreditNoteDetail.updateTheSubtotal(theThis.grid_CreditNoteDetail.getGrid().getStore().getById(invoiceDetailId));
}
}
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
theThis.grid_CreditNoteDetail.loadMask.hide();
if (callback_Function != null)
callback_Function();
},
failure : function(result, request) {
theThis.grid_CreditNoteDetail.loadMask.hide();
}
}); // End ajax
},
markProformaInvoiceAsTransfered : function(callback_Function){
var theThis = this;
theThis.loadMask.msg = 'Transfering proforma invoice...';
theThis.loadMask.show();
Ext.Ajax.request({
method: 'POST',
url: '/ProformaInvoice/MarkProformaInvoiceAsTransfered',
params:
{
proformaInvoiceId : theThis.selectedProformaInvoiceId,
invoiceId : theThis.selectedInvoiceId
},
success : function(result, request) {
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
//Global_SelectedExistingStockOrderId = -1;
theThis.loadMask.hide();
theThis.loadMask.msg = 'Loading...';
if (callback_Function != null)
callback_Function();
},
failure : function(result, request) {
theThis.loadMask.hide();
theThis.loadMask.msg = 'Loading...';
}
}); // End ajax
}
});
Ext.reg('CTBInvoiceDetailWindow', Ext.CTBInvoiceDetailWindow);
Ext.CTBTrialDetailPanel = Ext.extend(Ext.Panel, {
layout : 'border',
loadMask: null,
pageSize: 100,
recordObject : null,
selectedInvoiceRecord : null,
isForCreditNoteRequest : false,
hideInstruction : true,
isCalculateParentField : true,
setSelectedInvoiceRecord : function(theRecord){
var theThis = this;
theThis.selectedInvoiceRecord = theRecord;
if (theRecord != null)
theThis.selectedInvoiceId = theRecord.data.invoiceId;
else
theThis.selectedInvoiceId = -1;
},
parentWindowContainer : null,
listeners : {
afterrender : function(theThis){
// Init loadMask
theThis.loadMask = new Ext.LoadMask(this.getEl(), {msg:"Please wait..."});
},
show : function(theThis){
theThis.modifiedRecords = null;
}
},
instructionText : 'Physical Invoice',
instructionBackgroundColor : '#66c010',
initComponent: function(){
var theThis = this;
theThis.StockBrowserDialog = Ext.getCmp('dlg_StockBrowser');
theThis.grid_InvoiceDetail = theThis.getGrid_ReceivingOrder();
theThis.pnl_Instruction = new Ext.Panel({
frame : true,
region : 'north',
height : 70,
hidden : theThis.hideInstruction,
html :
''+
'
'+
''+
''+
''+theThis.instructionText+' '+
' '+
' '+
'
'+
'
'
});
theThis.items = [theThis.grid_InvoiceDetail, theThis.pnl_Instruction];
// Call super class to initialize componenets
Ext.CTBTrialDetailPanel.superclass.initComponent.call(this);
},
updateTheSubtotal : function(theRecord){
var theThis = this;
theThis.getGrid().updateTheSubtotal(theRecord);
},
clearSelections : function(){
var theThis = this;
theThis.getGrid().getStore().commitChanges();
theThis.getGrid().getSelectionModel().clearSelections();
},
getGrid: function(){
var theThis = this;
return theThis.grid_InvoiceDetail;
},
getPagingToolbar: function(){
var theThis = this;
return theThis.pt_InvoiceDetail;
},
getSelectedRecords: function(){
var theThis = this;
return theThis.getGrid().getSelectionModel().getSelections();
},
loadData: function(){
var theThis = this;
theThis.getGrid().getStore().commitChanges();
theThis.getGrid().getStore().baseParams = {invoiceId : theThis.selectedInvoiceRecord.data.invoiceId, start : 0, limit : theThis.getPagingToolbar().pageSize};
theThis.getGrid().getStore().load();
},
getCombobox_UnitOfMeasurement : function(callbackfunction)
{
var cmbGridUOM = new Ext.form.ComboBox({
store: Global_UnitOfMeasurement_Store,
displayField: 'UOMName',
valueField: 'UOMId',
typeAhead: true,
triggerAction: 'all',
lazyRender: true,
mode: 'local'
});
return cmbGridUOM;
},
getGrid_ReceivingOrder: function(){
var theThis = this;
// shorthand alias
var fm = Ext.form;
var cmbGridUOM = theThis.getCombobox_UnitOfMeasurement();
// ***************************************************************************************************
// Data Fields
// ***************************************************************************************************
theThis.recordObject = Ext.data.Record.create([
{ name: 'invoiceDetailId', type: 'number' },
{ name: 'invoiceId', type: 'number' },
{ name: 'supplierStockCode', type: 'string' },
{ name: 'stockDesc', type: 'string' },
{ name: 'stockUnit', type: 'number' },
{ name: 'stockUnitOfMeasurementId', type: 'number' },
{ name: 'stockQty', type: 'number' },
{ name: 'stockId', type: 'number' },
{ name: 'stockSupplierId', type: 'number' },
{ name: 'invoiceDetailCost', type : 'number'},
{ name: 'invoiceDetailTax', type: 'number' },
{ name: 'invoiceDetailSubtotal', type: 'number' },
{ name: 'isGstApplied', type: 'boolean' },
{ name: 'discountPercentage', type: 'number' }
]);
// ***************************************************************************************************
// Stores
// ***************************************************************************************************
var store = new Ext.data.JsonStore({
autoLoad : false,
proxy: new Ext.data.HttpProxy({
url: '/Invoice/GetInvoiceDetailByInvoiceId',
dataType: 'json',
method: 'POST'
}),
//reader: new Ext.data.JsonReader({
fields: theThis.recordObject,
root: 'data',
idProperty: 'invoiceDetailId',
listeners : {
'load' : function(){
},
'loadexception' : function(){
showStoreLoadingErrorMessage(store);
}
}
//})
});
// ***************************************************************************************************
// Selection model
// ***************************************************************************************************
var sm = new Ext.grid.CheckboxSelectionModel({
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
}
}
});
// ***************************************************************************************************
// Column model
// ***************************************************************************************************
// Column Models
var cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults: {
sortable: true // columns are not sortable by default
},
columns: [
sm,
{
header: 'invoiceDetailId', dataIndex: 'invoiceDetailId', hidden: true
},
{
header: 'invoiceId', dataIndex: 'invoiceId', hidden: true
},
{
header: 'Stock Code', dataIndex: 'supplierStockCode', width: 10, hidden : theThis.isForCreditNoteRequest
},
{
header: 'Description', dataIndex: 'stockDesc', width: 30
},
{
header: 'Unit', dataIndex: 'stockUnit', width: 15, hidden : theThis.isForCreditNoteRequest
},
{
header: 'Measurement', dataIndex: 'stockUnitOfMeasurementId', width: 15, hidden : theThis.isForCreditNoteRequest,
renderer: Ext.util.Format.comboRenderer(cmbGridUOM)
},
{
header: 'Quantity' + CTB_SYMBOL.EDIT, dataIndex: 'stockQty', width: 15,
editor: new Ext.grid.GridEditor(
new Ext.form.SpinnerField({
xtype: 'spinnerfield',
allowBlank: false,
allowNegative: false,
minValue : 0,
allowDecimals : true,
decimalPrecision: 3,
onFocus: function (txt, e) {
this.getEl().dom.select();
}
}),
{
listeners: {
beforestartedit: function(editor) {
editor.field.currentRecord = editor.record;
},
complete : function(p_This, p_Value, p_StartValue){
// Value has been changed by user
if (p_Value != p_StartValue){
//updateTheSubtotal(p_This.record);
}
}
}
}
)
},
{
header: 'Cost/Unit', dataIndex: 'invoiceDetailCost', width: 15, hidden : theThis.isForCreditNoteRequest,
editor: new Ext.grid.GridEditor(
new Ext.form.SpinnerField({
xtype: 'spinnerfield',
allowBlank: false,
allowNegative: false,
minValue : 0,
allowDecimals : true,
decimalPrecision: 3,
onFocus: function (txt, e) {
this.getEl().dom.select();
}
}),
{
listeners: {
beforestartedit: function(editor) {
editor.field.currentRecord = editor.record;
},
complete : function(p_This, p_Value, p_StartValue){
// Value has been changed by user
if (p_Value != p_StartValue){
//updateTheSubtotal(p_This.record);
}
}
}
}
),
renderer: Ext.util.Format.usMoney
},
{
header: 'DISC %' + CTB_SYMBOL.EDIT, dataIndex: 'discountPercentage', width: 15, hidden : theThis.isForCreditNoteRequest,
editor: new Ext.grid.GridEditor(
new Ext.form.NumberField({
allowBlank: false,
allowNegative: false,
minValue : 0,
allowDecimals : true,
decimalPrecision: 2,
onFocus: function (txt, e) {
this.getEl().dom.select();
}
}),
{
listeners: {
beforestartedit: function(editor) {
editor.field.currentRecord = editor.record;
},
complete : function(p_This, p_Value, p_StartValue){
// Value has been changed by user
if (p_Value != p_StartValue){
//updateTheSubtotal(p_This.record);
}
}
}
}
),
renderer: function(val){
return Ext.util.Format.percentage(val);
}
},
{
header: 'Tax' + CTB_SYMBOL.EDIT, dataIndex: 'invoiceDetailTax', width: 15, hidden : theThis.isForCreditNoteRequest,
editor: new Ext.grid.GridEditor(
new Ext.form.SpinnerField({
xtype: 'spinnerfield',
moneySign : '',
allowBlank: false,
allowNegative: false,
minValue : 0,
allowDecimals : true,
decimalPrecision: 3,
onFocus: function (txt, e) {
this.getEl().dom.select();
}
}),
{
listeners: {
beforestartedit: function(editor) {
editor.field.currentRecord = editor.record;
},
complete : function(p_This, p_Value, p_StartValue){
// Value has been changed by user
if (p_Value != p_StartValue){
// Mark the record as modified
p_This.record.isMofified = true;
}
}
}
}
),
renderer: Ext.util.Format.usMoney
},
{
header: 'Subtotal', dataIndex: 'invoiceDetailSubtotal', width: 15, hidden : theThis.isForCreditNoteRequest,
renderer: Ext.util.Format.usMoney
}
]
});
// This function update tax column for all rows
function updateTaxForAllRows(){
for (var i = 0; i < store.getCount(); i++){
var theRecord = store.getAt(i);
if (theRecord.data.isGstApplied){
if (theRecord.isMofified == null || theRecord.isMofified == false)
theRecord.set('invoiceDetailTax', roundNumber((theRecord.data.invoiceDetailCost * theRecord.data.stockQty * Global_GSTPercentage)/100, 2));
}
/*else if (theRecord.data.invoiceDetailTax != 0){
theRecord.set('invoiceDetailTax', roundNumber((theRecord.data.invoiceDetailCost * theRecord.data.stockQty * Global_GSTPercentage)/100, 2));
}*/
}
}
function updateTheTax(theRecord){
if (theRecord.data.isGstApplied){
if (theRecord.isMofified == null || theRecord.isMofified == false)
theRecord.set('invoiceDetailTax', roundNumber((theRecord.data.invoiceDetailCost * theRecord.data.stockQty * Global_GSTPercentage)/100, 2));
}
}
// This function update the subtotal for individual record
function updateTheSubtotal(theRecord){
updateTheTax(theRecord);
var theSubTotal = theRecord.get('invoiceDetailTax') + theRecord.get('invoiceDetailCost')*theRecord.get('stockQty');
// Minus the individual discount
theSubTotal = theSubTotal - (theSubTotal * theRecord.get('discountPercentage') / 100);
theSubTotal = roundNumber(theSubTotal, Global_Money_RoundUpTo);
theRecord.set('invoiceDetailSubtotal', theSubTotal);
if (theThis.parentWindowContainer != null && theThis.isCalculateParentField) {
theThis.parentWindowContainer.refreshCalculatingField();
}
}
// ***************************************************************************************************
// Paging toolbar
// ***************************************************************************************************
theThis.pt_InvoiceDetail = new Ext.CTBPagingToolbar({
store: store,
pageSize: theThis.pageSize,
displayInfo: true,
emptyMsg: "No stocks to display",
hidden : theThis.isForCreditNoteRequest
});
// ***************************************************************************************************
// Grid
// ***************************************************************************************************
var grid = new Ext.grid.EditorGridPanel({
updateTheSubtotal : function(theRecord){
updateTheSubtotal(theRecord);
},
tbar : [
theThis.btn_Add = new Ext.Button({
iconCls : 'icon-add', scale : 'large',
text : 'Add',
handler : function(){
theThis.StockBrowserDialog.Global_StockBrowser_CallbackFunction = function(selectedRecords)
{
var insertedDetail = new Array();
for(var i = 0; i 0)
{
Ext.Msg.show({
title:'Confirm',
msg: 'Are you sure you want to delete the item(s) ?',
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.QUESTION,
fn : function(btn) {
if (btn == "yes") {
var deletedItemIds = new Array(); // Actual deleted item
var modifiedRecords = store.getModifiedRecords();
var modifiedInfo = new Array(); // Store the modifed record for recovering from deleting
// This loop save the changes
for (var i = 0; i < modifiedRecords.length; i++){
modifiedInfo[i] = {
invoiceDetailId : modifiedRecords[i].data.invoiceDetailId,
stockQty : modifiedRecords[i].data.stockQty
}
}
// This loop insert deleted item to the array
for (var i = 0, j = 0; i < selectedItems.length; i++) {
var theId = selectedItems[i].get("invoiceDetailId");
if (theId >= 0){ // Only delete existing detail
deletedItemIds[j] = theId;
j++;
}
theThis.getGrid().getStore().remove(selectedItems[i]);
}
store.commitChanges(); // This is the reason we use modifiedInfo, when we commit, every changes disappear
// Recovering the changes
// If the item not be deleted
for (var i = 0; i < modifiedInfo.length; i++){
var invoiceDetailId = modifiedInfo[i].invoiceDetailId;
if (store.getById(invoiceDetailId) != null){
var stockQty = modifiedInfo[i].stockQty;
store.getById(invoiceDetailId).set('stockQty', 0); // Make changing mark appearing
store.getById(invoiceDetailId).set('stockQty', stockQty); // Recovering the real value
}
}
// Refresh the total
if (theThis.parentWindowContainer != null && theThis.isCalculateParentField)
theThis.parentWindowContainer.refreshCalculatingField();
// Calling delete
if (theThis.selectedInvoiceId != -1 && deletedItemIds.length > 0){ // Only send request when the invoice exist
theThis.loadMask.show();
Ext.Ajax.request({
method: 'POST',
url: '/Invoice/DeleteStockFromInvoice',
params:
{
invoiceId : theThis.selectedInvoiceId,
invoiceDetailIds : Ext.util.JSON.encode(deletedItemIds)
},
success : function(result, request) {
theThis.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
showSuccessNotification(jsonData.message.Info, NOTIFICATION.ICON_INFORMATION);
//grid_Invoice.getStore().load();
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.loadMask.hide();
}
}); // End ajax
} // End if
}
}
});
}
else {
Ext.Msg.show({
title:'Notice',
msg: 'Please select item(s) to delete!',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING
});
}// End if
}// End Handler
}) // End delete button
],
region: 'center',
store: store,
frame: true,
sm : sm,
listeners : {
rowclick : function ( p_this, p_rowIndex, p_eventObject ) {
var selectedRow = p_this.getView().getRow(p_rowIndex);
Ext.get(selectedRow).highlight();
if (theThis.parentWindowContainer != null && theThis.isCalculateParentField) {
theThis.parentWindowContainer.pnl_InvoiceDetail_NumberPad.callback_Assign = function(value){
theThis.getGrid().stopEditing();
var selectedRecords = theThis.getGrid().getSelectionModel().getSelections();
if (selectedRecords.length > 0){
for (var i = 0; i < selectedRecords.length; i++){
selectedRecords[i].set('stockQty', value);
updateTheSubtotal(selectedRecords[i]);
}
}
}
}
//theThis.getGrid().startEditing(p_rowIndex, 7);
// Only stop editing if user's using iPad
// We don't want them to see the default keyboard in iPad
if (Global_IsiPad)
theThis.getGrid().stopEditing();
},
// p_EditedObject INCLUDES :
// grid - This grid
// record - The record being edited
// field - The field name being edited
// value - The value being set
// originalValue - The original value for the field, before the edit.
// row - The grid row index
// column - The grid column index
afteredit : function( p_EditedObject ) {
updateTheSubtotal(p_EditedObject.record);
},
beforeedit : function (p_Event) {
if (theThis.parentWindowContainer != null && theThis.isCalculateParentField) {
theThis.parentWindowContainer.pnl_InvoiceDetail_NumberPad.callback_Next = function(theNumberPad){
try{
if (theNumberPad.isHavingChanges == true){
theNumberPad.operatorClick('=');
}
theThis.getGrid().getSelectionModel().selectRow(p_Event.row + 1);
theThis.getGrid().startEditing(p_Event.row + 1, 7);
theThis.getGrid().stopEditing();
}catch(e){
var activePage = 1;
var totalCount = theThis.getGrid().getStore().getTotalCount();
if ((activePage+1) <= Math.ceil(totalCount / theThis.pt_InvoiceDetail.pageSize))
{
theThis.pt_InvoiceDetail.moveNext();
}
else {
showErrorNotification('Notice', 'End of invoice details.');
}
}
}
}
}
},
cm: cm,
width: 780,
height: 400,
autoHeight: false,
clicksToEdit: 1,
loadMask: true,
bbar : theThis.pt_InvoiceDetail,
viewConfig:
{
enableRowBody: true,
forceFit: true // IMPORTANT (USE THIS ATTRIBUTE TO USE PERCENTAGE IN COLUMN MODEL)
}
});
return grid;
}
});
Ext.reg('CTBTrialDetailPanel', Ext.CTBTrialDetailPanel);
Ext.CTBTrialWindow = Ext.extend(Ext.Window, {
title: 'TRIAL PROGRAM A FEW QUICK QUESTIONS',
layout: 'border',
closeAction: 'hide',
expandOnShow : true,
closable: true,
resizable: true,
modal: true,
plain: true,
minimizable : true,
maximizable : true,
monitorResize : true,
width:720,
height:350,
defaults: {
split: true,
animFloat: false,
autoHide: false,
useSplitTips: true
},
listeners : {
scope : this,
afterrender : function(theThis){
theThis.loadMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
},
beforehide : function(theThis){
},
hide : function(theThis){
},
beforeshow : function(theThis){
},
show : function(theThis){
}
},
initComponent : function(){
var theThis = this;
theThis.pnl_TopDetail = theThis.getPanel_TopDetail();
theThis.items = [
theThis.pnl_TopDetail
];
// BUTTONS
var myButtons = theThis.initButtons();
this.buttons = myButtons;
this.initTools();
Ext.CTBTrialWindow.superclass.initComponent.call(this);
},
initButtons : function(){
var theThis = this;
var buttons = [
theThis.btn_TRYNOW = new Ext.Button({
text : 'TRY NOW',
scale : 'large',
handler : function(){
if (theThis.validateBeforeSave()){
var title = theThis.cmbTitle.getValue();
var name = theThis.txt_Name.getValue();
theThis.loadMask.show();
// Calling delete
Ext.Ajax.request({
method: 'POST',
url: '/Invoice/DeleteInvoices',
params:
{
title : title,
name : name
},
success : function(result, request) {
theThis.loadMask.hide();
},
failure : function(result, request) {
theThis.loadMask.hide();
}
}); // End ajax
}
} // End send request handler button
}),
theThis.btn_CANCEL = new Ext.Button({
text : 'CANCEL',
scale : 'large',
handler : function(){
theThis.hide();
} // End save handler button
})
];
return buttons;
},
validateBeforeSave : function()
{
var theThis = this;
var validateFields = new Array();
validateFields[0] = {
ID : theThis.txt_Name.id,
VALIDATION_TYPE : VALIDATION_CONSTANTS.EMPTY
};
// Call global validate field group
return validateFieldGroup(validateFields);
},
getPanel_TopDetail : function(){
var theThis = this;
theThis.cmbTitle = theThis.getCombobox_Title();
var frm_LeftForm = new Ext.form.FormPanel({
baseCls: 'x-plain',
labelWidth: 100,
defaultType: 'textfield',
items: [
theThis.cmbTitle,
/*theThis.txt_TopDetail_Date = new Ext.form.DateField({
fieldLabel: 'Date',
xtype : 'datefield',
name: 'datefield',
value : new Date(),
format : "j/n/Y",
altFormats : 'j/n/y',
width : 200
}),*/
theThis.txt_Name = new Ext.form.TextField({
fieldLabel: 'NAME',
name: 'name',
width : 200
}),
theThis.rg_RegistrationType = new Ext.form.RadioGroup({
fieldLabel: 'TYPE',
vertical: false,
//hideLabel : true,
itemCls: 'x-check-group-alt',
columns: 2,
listeners : {
change : function(p_this, p_radio){
}
},
items: [
{boxLabel: 'Business', name: 'rg_RegistrationType', inputValue: 'business', checked:true},
{boxLabel: 'Student', name: 'rg_RegistrationType', inputValue: 'student'}
]
}),
theThis.txt_Company = new Ext.form.TextField({
fieldLabel: 'COMPANY*',
name: 'name',
width : 200
}),
theThis.txt_Address = new Ext.form.TextArea({
fieldLabel: 'ADDRESS*',
name: 'address',
width : 200
}),
theThis.txt_Telephone = new Ext.form.TextField({
fieldLabel: 'TELEPHONE*',
name: 'telephone',
width : 200
}),
theThis.txt_Email = new Ext.form.TextField({
fieldLabel: 'EMAIL*',
name: 'email',
width : 200
})
]
});
theThis.cmbHeardFrom = theThis.getCombobox_HeardFrom();
var frm_RightForm = new Ext.form.FormPanel({
baseCls: 'x-plain',
labelWidth: 150,
//columnWidth : .50,
defaultType: 'textfield',
items: [
theThis.lbl_WhereDidYouHearAboutUs = new Ext.form.Label({
text : 'WHERE DID YOU HEAR ABOUT US?'
}),
theThis.cmbHeardFrom,
theThis.lbl_WhereDidYouHearAboutUs = new Ext.form.Label({
text : 'CAN WE CONTACT YOU ?'
}),
theThis.rg_Contact = new Ext.form.RadioGroup({
fieldLabel: 'Can we contact you ?',
vertical: false,
hideLabel : true,
itemCls: 'x-check-group-alt',
columns: 2,
listeners : {
change : function(p_this, p_radio){
}
},
items: [
{boxLabel: 'Yes', name: 'rg_Contact', inputValue: 'Yes', checked:true},
{boxLabel: 'No', name: 'rg_Contact', inputValue: 'No'},
]
})
]
});
var pnl_TopDetail = new Ext.Panel({
region: 'center',
layout : 'hbox',
layoutConfig: {
defaultMargins : '5 5 5 5'
},
height : 105,
items : [
frm_LeftForm,
new Ext.Panel({
width : 50
}),
frm_RightForm],
frame: true,
loadMask: true,
viewConfig:
{
enableRowBody: true,
forceFit: true // IMPORTANT (USE THIS ATTRIBUTE TO USE PERCENTAGE IN COLUMN MODEL)
}
});
return pnl_TopDetail;
},
getCombobox_Title : function(){
var data = [
['Mr', 'Mr'],
['Mrs', 'Mrs' ]
];
var cmbTitle = new Ext.form.ComboBox({
fieldLabel: 'TITLE',
width : 100,
store: new Ext.data.ArrayStore({
fields: [
{name: 'name' , type : 'string'},
{name: 'value', type: 'boolean'}
],
data : data
}),
displayField: 'name',
valueField: 'value',
editable: false,
typeAhead: true,
triggerAction: 'all',
lazyRender: true,
mode: 'local',
emptyText: 'Choose title ...',
listeners : {
select : function( p_combo, p_record, p_index){
}
}
});
return cmbTitle;
},
getCombobox_HeardFrom : function(){
var data = [
['MAGAZINE ADVERTISING', 'MAGAZINE ADVERTISING']
];
var cmbHeardFrom = new Ext.form.ComboBox({
fieldLabel: 'Title',
hideLabel : true,
width : 300,
store: new Ext.data.ArrayStore({
fields: [
{name: 'name' , type : 'string'},
{name: 'value', type: 'boolean'}
],
data : data
}),
displayField: 'name',
valueField: 'value',
editable: false,
typeAhead: true,
triggerAction: 'all',
lazyRender: true,
mode: 'local',
emptyText: 'Heard from ...',
listeners : {
select : function( p_combo, p_record, p_index){
}
}
});
return cmbHeardFrom;
}
});
Ext.reg('CTBTrialWindow', Ext.CTBTrialWindow);
var Enable_Stock_Invoice = true;
Ext.onReady(function () {
var loadMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
var fm = Ext.form;
// Get the Business department tab
var pnl_Invoice = Ext.getCmp('pnl_Invoice');
if(!pnl_Invoice) return;
var grid_Invoice = new Ext.CTBXeroTransferInvoice({
region : 'center',
margins : '10 15 10 15',
border : false
});
var pnl_InvoiceLayout = new Ext.Panel({
layout: 'border',
bodyCssClass : 'x-panel-whitebgcolor',
border : false,
defaults: {
split: true,
animFloat: false,
autoHide: false,
useSplitTips: true
},
items : [grid_Invoice]
});
pnl_Invoice.add(pnl_InvoiceLayout);
pnl_Invoice.doLayout();
}); // End Ext.Ready
Ext.CTBXeroSupplierTransferingLogGrid = Ext.extend(Ext.Panel, {
layout : 'border',
loadMask: null,
pageSize: CTB.init.itemPerPage || 100,
recordObject : null,
instructionText : 'Transfering suppliers in progress, please wait ...',
instructionBackgroundColor : '#fd4242',
callback_ContinueButtonClick : null,
dlg_Parent : null,
isCancelled : false,
MYOBHistoryTransactionRecord : null,
totalProcessedRecord : 0,
listeners : {
afterrender : function(theThis){
// Init loadMask
theThis.loadMask = new Ext.LoadMask(this.getEl(), {msg:"Please wait..."});
},
show : function(theThis){
theThis.totalProcessedRecord = 0;
}
},
initComponent: function(){
var theThis = this;
theThis.tpl_Instruction = new Ext.XTemplate(
'',
'',
'
',
'',
'',
'{instructionText} ',
' ',
' ',
'
',
'
',
' '
);
theThis.pnl_Instruction = new Ext.Panel({
frame : true,
region : 'north',
height : 70,
tpl : theThis.tpl_Instruction,
listeners : {
afterrender : function(p_This){
p_This.update({instructionBackgroundColor : theThis.instructionBackgroundColor, instructionText : theThis.instructionText});
}
}
});
theThis.grid_SupplierTransferingLogs = theThis.getGrid_SupplierTransferingLogs();
theThis.items = [theThis.grid_SupplierTransferingLogs, theThis.pnl_Instruction];
// Call super class to initialize componenets
Ext.CTBXeroSupplierTransferingLogGrid.superclass.initComponent.call(this);
},
clearSelections : function(){
var theThis = this;
theThis.getGrid().getSelectionModel().clearSelections();
},
getGrid: function(){
var theThis = this;
return theThis.grid_SupplierTransferingLogs;
},
getPagingToolbar: function(){
var theThis = this;
return theThis.pt_SupplierTransferingLog;
},
getSelectedRecords: function(){
var theThis = this;
return theThis.getGrid().getSelectionModel().getSelections();
},
loadData: function(){
var theThis = this;
theThis.isCancelled = false;
theThis.getGrid().getStore().removeAll();
theThis.instructionText = "Transfering suppliers in progress, please wait ...";
theThis.pnl_Instruction.update({instructionBackgroundColor : theThis.instructionBackgroundColor, instructionText : theThis.instructionText});
theThis.btn_Continue.setVisible(false);
theThis.getXeroHistoryTransaction(function(){
theThis.transferAllSuppliersFromCTBToXero();
});
/*theThis.getGrid().getStore().commitChanges();
theThis.getGrid().getStore().baseParams = {start : 0, limit : theThis.pageSize};
theThis.getGrid().getStore().load();*/
},
getGrid_SupplierTransferingLogs: function(){
var theThis = this;
// shorthand alias
var fm = Ext.form;
// ***************************************************************************************************
// Data Fields
// ***************************************************************************************************
theThis.supplierTransferingLogRecord = Ext.data.Record.create([
{ name: 'supplierTransferingLogID' , type: 'string' },
{ name: 'xeroSupplierId' , type: 'string' },
{ name: 'supplierId' , type: 'number' },
{ name: 'supplierName' , type: 'string' },
{ name: 'abnNo' , type: 'string' },
{ name: 'paymentTerm' , type: 'string' },
{ name: 'accountNo' , type: 'string' },
{ name: 'isActive' , type: 'boolean' },
{ name: 'website' , type: 'string' },
{ name: 'address' , type: 'object' },
{ name: 'contact' , type: 'object' },
{ name: 'xeroProcessingStatus' , type: 'string' },
{ name: 'xeroTransferingMessage' , type: 'string' }
]);
// ***************************************************************************************************
// Stores
// ***************************************************************************************************
theThis.store_SupplierTransferingLog = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy({
url: '/Xero/SearchSupplierTransferingLogs',
dataType: 'json',
method: 'POST'
}),
fields: theThis.supplierTransferingLogRecord,
root: 'data',
idProperty: 'supplierTransferingLogID',
totalProperty : 'totalCount',
autoLoad : false,
listeners : {
'load' : function(){
},
'loadexception' : function(){
showStoreLoadingErrorMessage(theThis.store_SupplierTransferingLog, function(){
theThis.dlg_Parent.connectToXero(function(){
theThis.store_SupplierTransferingLog.load();
});
});
}
}
//})
});
// ***************************************************************************************************
// Grid
// ***************************************************************************************************
//-------------------------------------------------------------------
// Selection model
//-------------------------------------------------------------------
var sm = new Ext.grid.CheckboxSelectionModel({
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
// Do nothing at the moment
}
}
});
var supplierTransferingLogSm = new Ext.grid.CheckboxSelectionModel({
singleSelect : true,
listeners: {
// On selection change, set enabled state of the removeButton
// which was placed into the GridPanel using the ref config
selectionchange: function(sm) {
}
}
});
// Column Models
var stockCM = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults: {
sortable: true // columns are not sortable by default
},
columns: [ supplierTransferingLogSm,
{ header: 'supplierTransferingLogID', dataIndex: 'supplierTransferingLogID', hidden: true },
{
header: 'supplierId', dataIndex: 'supplierId', hidden: true
},
{
header: 'Supplier Name', dataIndex: 'supplierName', width: 45
},
{ header: 'Message', dataIndex: 'xeroTransferingMessage', width: 50,
renderer: function(val, meta, theRecord)
{
if (theRecord.data.xeroProcessingStatus == XERO_PROCESSING_STATUS.PROCESSING) return 'Processing...';
else return val;
}
},
{ header: 'Status', dataIndex: 'xeroProcessingStatus', width: 5,
renderer: function(val)
{
if (val == XERO_PROCESSING_STATUS.PROCESSING) return ' ';
else if (val == XERO_PROCESSING_STATUS.SUCCEED) return ' ';
else if (val == XERO_PROCESSING_STATUS.FAILED) return ' ';
}
}
]
});
/********************************************************************************************/
// SupplierTransferingLog grid
var grid_SupplierTransferingLog = new Ext.grid.EditorGridPanel({
store : theThis.store_SupplierTransferingLog,
frame : true,
region : 'center',
sm : supplierTransferingLogSm,
buttons : [
theThis.btn_Continue = new Ext.Button({
text: 'Finish',
iconCls : 'icon-ok-large', scale : 'large',
hidden : true,
handler : function(){
if (theThis.callback_ContinueButtonClick != null) theThis.callback_ContinueButtonClick();
}
}),
theThis.btn_Cancel = new Ext.Button({
text: 'Cancel',
iconCls : 'icon-cancel-large', scale : 'large',
handler : function(){
theThis.isCancelled = true;
if (theThis.dlg_Parent != null)
theThis.dlg_Parent.hide();
}
})
],
listeners : {
rowclick : function ( p_this, p_rowIndex, p_eventObject ) {
// Hightlight the selected row
var selectedRow = p_this.getView().getRow(p_rowIndex);
Ext.get(selectedRow).highlight();
},
rowdblclick : function ( p_this, p_rowIndex, p_eventObject ) {
},
afterrender : function(){
/*theThis.store_SupplierTransferingLog.baseParams = {keyword: "", start: 0, limit: theThis.pageSize},
theThis.store_SupplierTransferingLog.load();*/
}
},
cm: stockCM,
width: 780,
height: 400,
autoHeight: false,
clicksToEdit: 1,
loadMask: true,
/*bbar:
theThis.pt_SupplierTransferingLog = new Ext.CTBPagingToolbar({
store: theThis.store_SupplierTransferingLog,
pageSize: theThis.pageSize,
displayInfo: true,
emptyMsg: "No logs to display"
}),*/
viewConfig:
{
enableRowBody: true,
forceFit: true // IMPORTANT (USE THIS ATTRIBUTE TO USE PERCENTAGE IN COLUMN MODEL)
}
});
return grid_SupplierTransferingLog;
}, // End generateGrid_Databases
transferAllSuppliersFromCTBToXero : function(){
var theThis = this;
theThis.totalProcessedRecord = 0;
theThis.transferSuppliersInBatch();
//theThis.startProcessingIndex = 0;
//theThis.loopTransferSupplier();
},
getXeroHistoryTransaction : function(callback_Function){
var theThis = this;
theThis.loadMask.show();
Ext.Ajax.request({
method: 'POST',
url: '/Kounta/GetNewMYOBHistoryTransaction',
params:
{
},
success : function(result, request) {
theThis.loadMask.hide();
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
theThis.MYOBHistoryTransactionRecord = jsonData.data;
if (callback_Function != null) callback_Function();
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
theThis.loadMask.hide();
}
}); // End ajax
},
loopTransferSupplier : function(){
var theThis = this;
if (theThis.isCancelled) return false;
var selectedSupplierRecords = theThis.dlg_Parent.selectedSupplierRecords;
if (theThis.startProcessingIndex < selectedSupplierRecords.length) {
var theNewRecord = theThis.addNewRecord(selectedSupplierRecords[theThis.startProcessingIndex]);
theThis.startProcessingIndex++;
function transferSupplierNow(){
Ext.Ajax.request({
method: 'POST',
url: '/Xero/TransferSupplierFromCTBtoXero',
params:
{
supplierId : theNewRecord.data.supplierId,
MYOBHistoryId : theThis.MYOBHistoryTransactionRecord.MYOBHistoryId
},
success : function(result, request) {
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
theThis.updateSupplierTransferingStatus(theNewRecord.data.supplierTransferingLogID, XERO_PROCESSING_STATUS.SUCCEED, jsonData.message.Info);
theThis.loopTransferSupplier();
}
else {
if (jsonData.message.Info == XERO_MESSAGE.ACCESS_TOKEN_EXPIRED || jsonData.message.Info == XERO_MESSAGE.INVALID_ACCESS_TOKEN) {
// Reconnect
theThis.dlg_Parent.connectToXero(transferSupplierNow);
}
else {
theThis.updateSupplierTransferingStatus(theNewRecord.data.supplierTransferingLogID, XERO_PROCESSING_STATUS.FAILED, jsonData.message.Info);
theThis.loopTransferSupplier();
// showErrorMessageWithEmailNotify(jsonData.message.Info);
}
}
},
failure : function(result, request) {
theThis.updateSupplierTransferingStatus(theNewRecord.data.supplierTransferingLogID, XERO_PROCESSING_STATUS.FAILED, "Server unavailable!");
}
}); // End ajax
}
transferSupplierNow();
return true;
}
else {
theThis.instructionText = "Transfering progress completed";
theThis.pnl_Instruction.update({instructionBackgroundColor : theThis.instructionBackgroundColor, instructionText : theThis.instructionText});
theThis.btn_Continue.setVisible(true);
return false;
}
},
transferSuppliersInBatch : function(){
var theThis = this;
if (theThis.isCancelled) return false;
var selectedSupplierRecords = theThis.dlg_Parent.selectedSupplierRecords;
var MYOBSupplierSupplierLinks = new Array();
var supplierIds = new Array();
var lastTotalProcessedRecords = theThis.totalProcessedRecord;
var countBatch = 0;
for (var i = lastTotalProcessedRecords; i < selectedSupplierRecords.length; i++){
var theNewRecord = theThis.addNewRecord(selectedSupplierRecords[i]);
supplierIds[i] = theNewRecord.data.supplierId;
theThis.totalProcessedRecord++; // Increase processed record
countBatch++;
if (countBatch == 10) // 10 item in each batch
break; // No need to continue, wait for next batch
}
if (countBatch == 0) { // End the batch, no more item to process
theThis.instructionText = "Transfering progress completed";
theThis.instructionBackgroundColor = "#01DF01";
theThis.pnl_Instruction.update({instructionBackgroundColor : theThis.instructionBackgroundColor, instructionText : theThis.instructionText});
theThis.btn_Continue.setVisible(true);
return false;
}
else if (theThis.totalProcessedRecord <= selectedSupplierRecords.length) {
function transferSupplierNow(){
Ext.Ajax.request({
method: 'POST',
url: '/Kounta/TransferSupplierBatchFromCTBtoMYOB',
timeout: 1800000,
params:
{
CTBSupplierIds : Ext.util.JSON.encode(supplierIds),
MYOBHistoryId : theThis.MYOBHistoryTransactionRecord.MYOBHistoryId
},
success : function(result, request) {
var jsonData = Ext.util.JSON.decode(result.responseText);
if (jsonData.message.IsSuccess)
{
if (jsonData.data.length > 0) {
for (var i = 0; i < jsonData.data.length; i++) {
var returnBatchMessage = jsonData.data[i];
if (returnBatchMessage.isSuccess)
theThis.updateSupplierTransferingStatusBySupplierId(returnBatchMessage.supplierId, XERO_PROCESSING_STATUS.SUCCEED, returnBatchMessage.message);
else
theThis.updateSupplierTransferingStatusBySupplierId(returnBatchMessage.supplierId, XERO_PROCESSING_STATUS.FAILED, returnBatchMessage.message);
}
}
theThis.transferSuppliersInBatch(); // Continue another batch (if have)
}
else {
showErrorMessageWithEmailNotify(jsonData.message.Info);
}
},
failure : function(result, request) {
showErrorNotification('Notice', 'Server unavailable!');
//theThis.updateSupplierTransferingStatus(theNewRecord.data.invoiceTransferingLogID, XERO_PROCESSING_STATUS.FAILED, "Server unavailable!");
}
}); // End ajax
}
transferSupplierNow();
return true;
}
},
updateSupplierTransferingStatus : function(supplierTransferingLogID, theStatus, xeroTransferingMessage) {
var theThis = this;
theThis.getGrid().getStore().getById(supplierTransferingLogID).set('xeroProcessingStatus', theStatus);
theThis.getGrid().getStore().getById(supplierTransferingLogID).set('xeroTransferingMessage', xeroTransferingMessage);
},
updateSupplierTransferingStatusBySupplierId : function(supplierId, theStatus, xeroTransferingMessage) {
var theThis = this;
for (var i = 0; i < theThis.getGrid().getStore().getCount(); i++) {
var theRecord = theThis.getGrid().getStore().getAt(i);
if (theRecord.data.supplierId == supplierId) {
theRecord.set('xeroProcessingStatus', theStatus);
theRecord.set('xeroTransferingMessage', xeroTransferingMessage);
break;
}
}
},
addNewRecord : function(supplierRecord, quantity){
var theThis = this;
var theStore = theThis.getGrid().getStore();
var newId = theStore.getCount();
var aNewRecord = new theThis.supplierTransferingLogRecord({
supplierTransferingLogID : newId,
xeroSupplierId : '',
supplierId : supplierRecord.data.supplierId,
supplierName : supplierRecord.data.supplierName,
abnNo : supplierRecord.data.abnNo,
paymentTerm : supplierRecord.data.paymentTerm,
accountNo : supplierRecord.data.accountNo,
isActive : supplierRecord.data.isActive,
website : supplierRecord.data.website,
address : supplierRecord.data.address,
contact : supplierRecord.data.contact,
xeroProcessingStatus : XERO_PROCESSING_STATUS.PROCESSING
}, newId);
theStore.insert(theThis.getGrid().getStore().getCount(), aNewRecord);
return aNewRecord;
}
});
Ext.reg('CTBXeroSupplierTransferingLogGrid', Ext.CTBXeroSupplierTransferingLogGrid);
Ext.CTBXeroTransferSupplierWindow = Ext.extend(Ext.Window, {
title: 'Export suppliers to Xero',
layout: 'card',
closeAction: 'hide',
iconCls: 'icon-stock',
expandOnShow: true,
closable: true,
resizable: true,
modal: true,
plain: true,
minimizable: true,
maximizable: true,
monitorResize: true,
width: 800,
height: 500,
activeItem : 0,
defaults: {
split: true,
animFloat: false,
autoHide: false,
useSplitTips: true
},
pageSize: CTB.init.itemPerPage || 100,
accountCode : '',
selectedSupplierRecords : null,
callback_AfterHide : null,
setSelectedSupplierRecords : function(selectedSupplierRecords){
var theThis = this;
theThis.selectedSupplierRecords = selectedSupplierRecords;
},
listeners: {
scope : this,
'beforehide': function(theThis){
},
'beforeshow': function(theThis){
// Fit this window to the client browser screen with 90%
fitWindowSize(theThis, 90);
},
'show': function(theThis){
theThis.layout.setActiveItem(theThis.pnl_XeroSupplierTransferingLogGrid);
theThis.pnl_XeroSupplierTransferingLogGrid.loadData();
},
'hide': function(theThis){
if (theThis.callback_AfterHide != null) {
theThis.callback_AfterHide();
}
}
},
initComponent : function(){
var theThis = this;
theThis.pnl_XeroSupplierTransferingLogGrid = new Ext.CTBXeroSupplierTransferingLogGrid({
dlg_Parent : theThis,
callback_ContinueButtonClick : function(theStore) {
// Reload the supplier grid
theThis.hide();
}
});
theThis.items = [
theThis.pnl_XeroSupplierTransferingLogGrid
];
// BUTTONS
var myButtons = theThis.initButtons();
this.buttons = myButtons;
this.initTools();
Ext.CTBXeroTransferSupplierWindow.superclass.initComponent.call(this);
},
initButtons : function(){
var theThis = this;
var buttons = [
/*theThis.btn_Cancel = new Ext.Button({
text: 'Cancel',
iconCls : 'icon-cancel-large', scale : 'large',
handler : function(){
theThis.hide();
}
})*/
];
return buttons;
},
connectToXero : function(callbackFunction, customMessage){
var theThis = this;
if (customMessage == null) customMessage = "Your access to Xero has been expired. Please reconnect.";
if (theThis.dlg_ConnectToXero == null) {
theThis.dlg_ConnectToXero = new Ext.CTBXeroConnectWindow({
callback_ContinueButtonClick : function() { // Continue the process if only there is a valid connection established
theThis.dlg_ConnectToXero.hide();
if (callbackFunction != null) callbackFunction();
}
});
}
theThis.dlg_ConnectToXero.customMessage = customMessage;
theThis.dlg_ConnectToXero.show();
}
});
Ext.reg('CTBXeroTransferSupplierWindow', Ext.CTBXeroTransferSupplierWindow);
var Enable_Xero_Supplier = true;
Ext.onReady(function () {
var loadMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
var fm = Ext.form;
// Get the Business department tab
var pnl_Supplier = Ext.getCmp('pnl_Supplier');
var grid_Supplier = new Ext.CTBSupplierBrowserGrid({
region : 'center',
title : 'Suppliers',
margins : '10 15 10 15',
border : false,
readOnly : true,
isFromImportDatabase : false,
hideXeroTransferSuppliers : false,
hideXeroShowExportedSuppliers : false,
listeners : {
afterrender : function(theThis){
theThis.loadData();
}
}
});
var pnl_SupplierLayout = new Ext.Panel({
layout: 'border',
bodyCssClass : 'x-panel-whitebgcolor',
border : false,
defaults: {
split: true,
animFloat: false,
autoHide: false,
useSplitTips: true
},
items : [grid_Supplier]
});
pnl_Supplier.add(pnl_SupplierLayout);
pnl_Supplier.doLayout();
}); // End Ext.Ready
/*
* show a window for the user to conduct exporting
* Created: 09 April 2015 by Andy C
*/
Ext.CTBRecipeMenuTransferPanel = Ext.extend(Ext.Panel, {
//title: 'Select Recipe Menu to Export',
width: 500,
height: 300,
layout: 'border',
initComponent: function() {
this.recipeMenuGrid = this.getRecipeMenuPanel();
this.items = this.recipeMenuGrid;
this.ctbCountaSelectSitesWindow = new Ext.CTBKountaSelectSiteWindow();
//this.bbar = this.getButtons();
Ext.CTBRecipeMenuTransferPanel.superclass.initComponent.call(this);
},
listeners: {
afterrender: function() {
this.loadMask = new Ext.LoadMask(this.getEl(), {msg:"Please wait..."});
this.recipeMenuGrid.loadData();
}
},
getRecipeMenuPanel: function() {
var theThis = this;
var recipeRecord = new Ext.data.Record.create([
{ name: 'recipeId', type: 'number' },
{ name: 'recipeName', type: 'string' },
{ name: 'menuSellingPrice', type: 'number' },
{ name: 'recipeMenuId', type: 'number' },
{ name: 'recipeMenuName', type: 'string' },
{ name: 'menuHeading', type: 'string' },
{ name: 'recipeMediaId', type: 'number' },
{ name: 'isRecipeActive', type: 'boolean' },
//below two fields are used to show the result
{ name: 'result', type: 'boolean'},
{ name: 'message', type: 'string' }
]);
var store = new Ext.data.GroupingStore({
proxy: new Ext.data.HttpProxy({
url: '/RecipeMenu/GetRecipeMenuDetailsFromCTB',
dataType: 'json',
method: 'POST'
}),
reader: new Ext.data.JsonReader({
fields: recipeRecord,
root: 'data',
idProperty: 'recipeId',
totalProperty : 'totalCount'
}),
autoLoad : false,
groupField : 'recipeMenuId',
listeners : {
'load' : function(store, records, options){
if(theThis.loadMask) theThis.loadMask.hide();
//console.log('data loaded.');
//for(var i=0; iDELETED';
else return '';
}
},
{ header: 'Price', width: 30, dataIndex: 'menuSellingPrice' },
{ header: 'Menu Heading', width: 30, dataIndex: 'menuHeading' },
{
header: 'Recipe Menu',
dataIndex: 'recipeMenuId',
width: 30,
renderer: function(value, metaData, record) {
return record ? record.data.recipeMenuName : value;
}
},
{
header: 'Export Status', width: 30, dataIndex: 'result',
renderer: function(value) {
if(value) return 'Exported';
else return null;
}
},
{ header: 'Export Message', width: 200, dataIndex: 'message'}
]
});
var btnExport = new Ext.Button({
text: 'Export to Kounta',
handler: function(btn) {
if(!theThis.recipeMenuGrid) return;
var resetStatus = true;
var selected = theThis.recipeMenuGrid.getSelectedItems(resetStatus);
//console.log('selected:' + selected);
if(!selected.length) {
showErrorNotification('Error','You have not selected any recipes to export.');
return;
}
else {
//show a window to let the user select a site
//this function is performed when signing in Kounta
//theThis.showSelectSiteWindow(function(siteId) {
theThis.ctbCountaSelectSitesWindow.showSelectSiteWindow(function(siteId, siteName) {
var selectedrecipes = theThis.recipeMenuGrid.getSelectedItems(false);
var data = Ext.encode(selectedrecipes);
theThis.loadMask.show();
Ext.Ajax.request({
url: '/RecipeMenu/ExportRecipeMenuToKounta',
method: 'POST',
timeout: 1000 * 60 * 30, //30 minutes
params: {data: data, siteId: siteId},
//params: {data: data},
success: function(response, request) {
theThis.loadMask.hide();
//theThis.recipeMenuGrid.clearSelections();
//console.log(response.responseText);
var jsonData = Ext.decode(response.responseText);
if(jsonData.message.IsSuccess) {
showSuccessNotification(jsonData.totalCount + ' recipe(s) have been exported to Kounta.');
if(jsonData.data.length > 0) {
var store = theThis.recipeMenuGrid.getStore();
var data = jsonData.data;
for(var i=0; i 1 ? "Items" : "Item"]})'
}),
viewConfig: { forceFit: true},
loadData: function() {
if(theThis.loadMask) theThis.loadMask.show();
store.load();
}
});
grid.getSelectedItems = function(resetStatus) {
var result = [];
var selected = this.getSelectionModel().getSelections();
if(selected.length > 0) {
for(var i=0; i