I'm working on an app to retrieve data from a library catalog from a Dialogflow chat. I'm not getting any errors, and I have a billing account attached to the service. The intent code is here:
const {WebhookClient} = require('dialogflow-fulfillment');
const function = require('firebase-functions');
const agent = new WebhookClient({ request: request, response: response });
const catalogSearch = require("rss-to-json");
exports.libraryChat = functions.https.onRequest(request, response) => {
function catalog_search(agent) {
var itemSubject = agent.parameters["item-subject"] ? "+" + agent.parameters["item-subject"] : "";
var itemTitle = agent.parameters["item-title"] ? "+" + agent.parameters["item-title"] : "";
var chatResponse = "";
var itemList = new Array();
if (agent.parameters["author-name"]) {
var authorName = agent.parameters["author-name"]["name"] ? "+" + agent.parameters["author-name"]["name"] + " " + agent.parameters["author-name"]["last-name"] : "+" + agent.parameters["author-name"]["last-name"];
}
var searchString = "";
if (itemSubject.length > 0) { searchString = searchString + itemSubject; }
if (itemTitle.length > 0 ) { searchString = searchString + itemTitle; }
if (authorName.length > 0) { searchString = searchString + authorName; }
var url = "https://gapines.org/opac/extras/opensearch/1.1/-/rss2-full?searchTerms=site(GCHR-CCO)" + searchString + "&searchClass=keyword";
console.log(url);
catalogSearch.load(url, (err, jsonResponse) => {
if (!err) {
itemList = jsonResponse.items;
chatResponse = "The first ten items returned for your search are: ";
}
else {
chatResponse = "I'm sorry! I've encountered an error while retrieving that data!";
}
});
itemList.forEach( (title, index) => {
chatResponse = chatResponse + (index + 1).toString() + title.title;
});
agent.add(chatResponse);
}
let intentMap = new Map();
intentMap.set("Catalog Search", catalog_search);
}
The JSON response from the intent is:
{
"responseId": "958f0d66-13ba-4bf5-bed8-83480da4c37e",
"queryResult": {
"queryText": "Do you have any books about goats?",
"parameters": {
"item-subject": "goats",
"item-title": "",
"author-name": ""
},
"allRequiredParamsPresent": true,
"fulfillmentMessages": [
{
"text": {
"text": [
""
]
}
}
],
"intent": {
"name": "projects/library-chatbot/agent/intents/a5f8ad9b-ff73-49f7-a8c0-351da3bf4802",
"displayName": "Catalog Search"
},
"intentDetectionConfidence": 1,
"diagnosticInfo": {
"webhook_latency_ms": 3591
},
"languageCode": "en"
},
"webhookStatus": {
"message": "Webhook execution successful"
}
}
I've verified through a separate function that the Opensearch call works and produces a list of titles, however when accessed through the Dialogflow intent nothing comes back. I thought it might be due to the free account limitations, but the error continues after adding billing information and upgrading.
Or, rather, the lack of error with no response generated. Is there something I'm missing in here?
Your third line:
const agent = new WebhookClient({ request: request, response: response });
Is trying to instantiate the new agent, but request and response aren't defined in that scope. Try moving that line inside your libraryChat function body.
The issue: The DialogFlow agent was returning a response before the Opensearch results had been processed.
Solution: First, route the chat intents without using the built in .handleRequest method for the intent which makes a call to Opensearch, returning a promise.
function chooseHandler(agent) {
var intentRoute = "";
switch (agent.intent) {
case "Default Welcome Intent":
intentRoute = "welcome";
break;
case "Default Fallback Intent":
intentRoute = "fallback";
break;
case "Catalog Search":
intentRoute = "catalog";
break;
}
return new Promise ((resolve, reject) => {
if (intentRoute.length > 0) {
resolve(intentRoute);
}
else {
reject(Error("Route Not Found"));
}
});
}
function assignResponse(intentRoute, agent) {
switch (intentRoute) {
case "welcome":
agent.handleRequest(welcome);
break;
case "fallback":
agent.handleRequest(fallback);
break;
case "catalog":
catalog_response();
break;
default:
Error("Intent not found");
}
}
Next, retrieve the data from the OpenSearch API, returning a promise.
function catalog_search(agent) {
var itemSubject = agent.parameters["item-subject"] ? "+" + agent.parameters["item-subject"] : "";
var itemTitle = agent.parameters["item-title"] ? "+" + agent.parameters["item-title"] : "";
var itemType = agent.parameters["item-type"] ? "+" + agent.parameters["item-type"] : "";
var authorName = "";
if (agent.parameters["author-name"]) {
authorName = agent.parameters["author-name"]["name"] ? "+" + agent.parameters["author-name"]["name"] + " " + agent.parameters["author-name"]["last-name"] : "+" + agent.parameters["author-name"]["last-name"];
}
var searchString = "";
if (itemSubject.length > 0) { searchString += itemSubject; }
if (itemTitle.length > 0 ) { searchString += itemTitle; }
if (authorName.length > 0) { searchString += authorName; }
if (itemType.length > 0) { searchString += itemType; }
var url = "https://gapines.org/opac/extras/opensearch/1.1/-/rss2-full?searchTerms=site(GCHR-CCO)" + encodeURIComponent(searchString) + "&searchClass=keyword";
console.log(url);
console.log(encodeURIComponent(searchString));
var itemList = [];
var chatResponse = "this was untouched";
return new Promise((resolve, reject) => {
catalogSearch.load(url, (err, rss) => {
if (err) {
reject(Error("url failed!"));
}
else {
itemList = rss;
if (itemList.items.length > 0) {
if (itemList.items.length === 1) {
chatResponse = "The only item found for that search is ";
}
else if (itemList.items.length < 10) {
chatResponse = "The first few items in your search are ";
}
else {
chatResponse = "The first ten items in your search are ";
}
itemList.items.forEach( (item, index) => {
chatResponse = chatResponse + item.title.replace(/\//g, "").trim();
if (index + 1 < itemList.items.length) {
chatResponse += ", ";
} else {
chatResponse += ".";
}
});
}
else {
chatResponse = "We're sorry, there are no items matching that search at our library!";
}
console.log(rss);
resolve(chatResponse);
}
});
});
}
Create a properly-formatted JSON response to the intent, and send it back.
function catalog_response() {
catalog_search(agent).then((response) => {
res.json({ "fulfillmentText": response });
res.status(200).send();
return 1;
}), (error) => {
console.log("failed", error);
};
}
I am creating a Shipment using Screen based Web Service call in Acumatica. The Program executes without errors and gives error Sales Order # does not exist (even if it does exist).
The program goes till the end and for some orders create a Shipment ! How do I check only specific Lines be included in the shipment in this code ??
` PSOrders.Current = psorderrec;
if (psorderrec.Status == PSOrderStatus.Hold)
{
throw new PXException(String.Format(
"Preshipment(0) is On Hold and cannot be generated.",
psorderrec.PSOrderNbr));
}
else if (psorderrec.Status != PSOrderStatus.Open)
{
throw new PXException(String.Format(
"Vendor {0} is already Processed.", psorderrec.PSOrderNbr));
}
so302000.Screen scr = new so302000.Screen();
scr.CookieContainer = new System.Net.CookieContainer();
so302000.LoginResult lr = scr.Login("USERNAME#COMPANYNAME:BRANCHNAME", "Password");
if (lr != null && lr.Code == so302000.ErrorCode.OK)
{
so302000.Content schema = scr.GetSchema();
var selectSOWithCommit = schema.Actions.SelectSO;
selectSOWithCommit.Commit = true;
var addSOWithCommit = schema.Actions.AddSO;
addSOWithCommit.Commit = true;
List<so302000.Command> commands = new List<so302000.Command>();
commands.Add(schema.Actions.Insert);
commands.Add(new so302000.Value
{
LinkedCommand = schema.ShipmentSummary.Customer,
Value = psorderrec.CustomerCD
});
commands.Add(new so302000.Value
{
LinkedCommand = schema.ShipmentSummary.Location,
Value = psorderrec.Location
});
commands.Add(new so302000.Value
{
LinkedCommand = schema.ShipmentSummary.WarehouseID,
Value = psorderrec.Warehouse
});
commands.Add(new so302000.Value
{
LinkedCommand = schema.ShipmentSummary.NoteText,
Value = psorderrec.PSOrderType+ "/" + psorderrec.PSOrderNbr
});
commands.Add(new so302000.Value
{
LinkedCommand = schema.ShipmentSummary.ControlQuantity,
Value = psorderrec.ControlQty.ToString()
});
commands.Add(new so302000.Value
{
LinkedCommand = schema.ShipmentSummary.Operation,
Value = "Issue"
});
commands.Add(new so302000.Value
{
Value = "OK",
LinkedCommand =
schema.AddSalesOrderOperation.ServiceCommands.DialogAnswer,
Commit = true
});
string pstype = psorderrec.PSOrderType;
string psordernbr = psorderrec.PSOrderNbr;
foreach (PSLine pslinerec in
PXSelect<PSLine,
Where<PSLine.pSOrderType, Equal<Required<PSLine.pSOrderType>>,
And<PSLine.pSOrderNbr, Equal<Required<PSLine.pSOrderNbr>>>>>.Select(this, pstype, psordernbr))
{
commands.Add(addSOWithCommit);
commands.Add(new so302000.Value
{
Value = pslinerec.SOOrderType,
LinkedCommand = schema.AddSalesOrderOperation.OrderType
});
commands.Add(new so302000.Value
{
Value = pslinerec.SOOrderNbr,
LinkedCommand = schema.AddSalesOrderOperation.OrderNbr
});
commands.Add(new so302000.Value
{
Value = "True",
LinkedCommand = schema.AddSalesOrder.Selected
});
commands.Add(schema.AddSalesOrder.InventoryID);
commands.Add(schema.AddSalesOrder.Quantity);
commands.Add(schema.AddSalesOrder.LineDescription);
var soLines = scr.Submit(commands.ToArray());
// List commandList = new List();
for (int index = 0; index < soLines.Length; index++)
{
commands.Add(addSOWithCommit);
commands.Add(new so302000.Value
{
Value = index.ToString(),
LinkedCommand =
schema.AddSalesOrder.ServiceCommands.RowNumber
});
commands.Add(new so302000.Value
{
Value = "True",
LinkedCommand = schema.AddSalesOrder.Selected,
Commit = index < soLines.Length - 1
});
}
}
commands.Add(schema.Actions.Save);
// commandList.Add(schema.Actions.Save);
scr.Submit(commands.ToArray());
scr.Logout();`
Below is a code sample that will create a shipment using Screen-Based API.
It's a bit more verbose that your example - but I think you will see some similarities to your example as well. This code starts just after the Login.
There is a section that Adds the SO, and then iterates through each line in the SO in order to update the values.
I hope this helps!
var schema = shipScreen.GetSchema();
var SelectSO = schema.Actions.SelectSO;
SelectSO.Commit = true;
var AddSO = schema.Actions.AddSO;
AddSO.Commit = true;
var Allocation = schema.Actions.LSSOShipLineBinLotSerial;
Allocation.Commit = true;
var commands = new Command[] {
//first specify keys
new Value { Value = "Shipment", LinkedCommand = schema.ShipmentSummary.Type },
new Value { Value = OrderID.Trim(), LinkedCommand = schema.ShipmentSummary.ShipmentNbr },
//header
new Value { Value = CustID, LinkedCommand = schema.ShipmentSummary.Customer },
new Value { Value = ShipName, LinkedCommand = schema.ShipmentSummary.Location },
new Value { Value = SiteID, LinkedCommand = schema.ShipmentSummary.WarehouseID },
new Value { Value = ShipDate.ToString(), LinkedCommand = schema.ShipmentSummary.ShipmentDate },
new Value { Value = "False", LinkedCommand = schema.ShipmentSummary.Hold },
//Add sales order
new Value { Value = "OK", LinkedCommand = schema.AddSalesOrderOperation.ServiceCommands.DialogAnswer, Commit = true }, SelectSO,
new Value { Value = OrderType, LinkedCommand = schema.AddSalesOrderOperation.OrderType }, // setting filter
new Value { Value = OrderID, LinkedCommand = schema.AddSalesOrderOperation.OrderNbr }, schema.AddSalesOrder.InventoryID
};
var soLines = shipScreen.Submit(commands.ToArray()); // get list of SO lines
List<Command> cmdList = new List<Command>();
for (int i = 0; i < soLines.Length; i++) // select each line
{
cmdList.Add(new Value { Value = i.ToString(), LinkedCommand = schema.AddSalesOrder.ServiceCommands.RowNumber });
cmdList.Add(new Value { Value = "True", LinkedCommand = schema.AddSalesOrder.Selected, Commit = true });
}
cmdList.Add(AddSO); //add selected lines to shipment
shipScreen.Submit(cmdList.ToArray());
//dt is the datatable with the fields that need to be entered - from the outside (non-acumatica) database
//There is one row in dt for each line needed in the shipment.
LineCounter = 0;
foreach (DataRow dr in dt.Rows)
{
ProductID = dr.Field<string>("ProductID").Trim();
LotNumber = dr.Field<string>("LotNumber").Trim();
LineNum = dr.Field<int>("LineNumber").ToString();
LinePickQty = dr.Field<Int32>("PickQty").ToString();
SiteID = dr.Field<string>("SiteID").Trim();
LocationID = dr.Field<string>("LocationID").Trim();
UOM = dr.Field<string>("UOM").Trim();
LotPickQty = dr.Field<Int32>("LotQty").ToString();
if (LineCounter == 0)
{
cmdList.Clear();
}
cmdList.Add(new Key { Value = "='" + LineNum + "'", FieldName = schema.DocumentDetails.OrderLineNbr.FieldName, ObjectName = schema.DocumentDetails.OrderLineNbr.ObjectName });
cmdList.Add(new Value { Value = SiteID, LinkedCommand = schema.DocumentDetails.Warehouse });
cmdList.Add(new Value { Value = LocationID, LinkedCommand = schema.DocumentDetails.Location });
cmdList.Add(new Value { Value = UOM, LinkedCommand = schema.DocumentDetails.UOM });
cmdList.Add(new Value { Value = LinePickQty, LinkedCommand = schema.DocumentDetails.ShippedQty, Commit = true });
cmdList.Add(new Value { Value = LinePickQty, LinkedCommand = schema.Allocations.Quantity });
cmdList.Add(new Value { Value = "OK", LinkedCommand = schema.Allocations.ServiceCommands.DialogAnswer, Commit = true });
LineCounter = LineCounter + 1;
}
//Save
cmdList.Add(schema.Actions.Save);
cmdList.Add(schema.ShipmentSummary.ShipmentNbr);
var shipment = shipScreen.Submit(cmdList.ToArray());
Im working on react and node project. Im new to both technologies, and i developed a system for my internship. But I feel like, I didn't handle the server side (Node part) properly. This is my server side file. It container almost 700 lines. Do I have to break this page in to several pages? If so, how exactly I should do it? Can someone give me a suggestion please. The application is working as expected. I just want to clean the code in the server side. I used express framework with node.
var express = require('express');
var mysql = require('mysql');
var _ = require('underscore');
var crypto = require('crypto');
var app = express();
var connections = [];
var title = 'Fishery Logistics';
var flds = [];
var currentFld = '';
var fldDetails = [];
var lfrSaved = false;
var userSiteInfoSaved = false;
var userList = [];
var userTypes = [];
var validUserName = false;
var fldNumbers = [];
var productCodes = [];
var containerTypes = [];
var areaCodes = [];
var fldRows = 0;
var fldInfo = {};
var productInfo = {};
var weighInList = {};
var weighInSaved = false;
var weighInNumbers = [];
var weighInWeights = [];
var fldHeaderInfo = [];
var weighInHeaderInfo = [];
var fldWeights = [];
var userDeleted = false;
// From where express should access our files
app.use(express.static('./public'));
app.use(express.static('./node_modules/bootstrap/dist'));
var server = app.listen(process.env.PORT || 3000);
// Creating a socket server which is also listeing to localhost:<port>
var io = require('socket.io').listen(server);
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: '',
database: 'fish_landing'
});
io.sockets.on('connection', function(socket) {
// Load fld list relevant to a LFR
socket.on('lfrFldListLoad', function(payload) {
var lfr_id = payload.lfrId;
var sql_lfr_fld_list = 'SELECT F.fld_id, F.fld_number, DATE_FORMAT(F.landed_date, "%Y-%m-%d") AS "landed_date", F.vessel_name, F.port_name, F.transport_company_name, F.driver_name, truck_number, FS.status ' +
'FROM fld F, fld_status FS, lfr L ' +
'WHERE F.status_id = FS.status_id ' +
'AND F.lfr_id = L.lfr_id ' +
'AND L.lfr_id = ' + lfr_id +
' ORDER BY F.fld_id DESC';
connection.query(sql_lfr_fld_list, function(error, result) {
if (error) {
console.log(error);
}
if (result.length !== 0) {
flds = result;
io.sockets.emit('lfrFldListLoaded', flds);
} else {
console.log('No Records Found')
}
});
});
// Load fld with all the details
socket.on('fldViewLoad', function(payload) {
var fld_id = payload.fldId;
var sql_fld_by_id =
'SELECT F.fld_id, F.fld_number, DATE_FORMAT(F.landed_date, "%Y-%m-%d") AS "landed_date", DATE_FORMAT(F.landed_date, "%T") AS "landed_time", ' +
'F.port_name, F.vessel_name, F.skipper_name, F.transport_company_name, F.truck_number, F.driver_name, F.driver_license, F.vehicle_clean, ' +
'F.vehicle_refrigerated, F.containers_clean, F.containers_iced, F.skipper_signature, F.supervisor_signature, F.lfr_staff_signature, ' +
'F.skipper_signature_time, F.supervisor_signature_time, F.lfr_staff_signature_time, F.comment, FS.status, CONCAT(U.first_name, " ", U.last_name) AS "full_name", ' +
'DATE_FORMAT(F.fld_created_time, "%Y-%m-%d") AS "fld_created_date", DATE_FORMAT(F.fld_created_time, "%T") AS "fld_created_time" ' +
'FROM fld F, fld_status FS, user_personal_info U ' +
'WHERE F.status_id = FS.status_id ' +
'AND F.fld_created_user_id = U.user_id ' +
'AND F.fld_id = "' + fld_id + '"';
var sql_fld_detail_list =
'SELECT FD.fld_detail_id, SP.species, PS.state, C.container, FD.no_of_containers, FD.fld_id ' +
'FROM fld_details FD, species SP, processed_state PS, container C, fld F ' +
'WHERE F.fld_id = FD.fld_id ' +
'AND SP.species_id = FD.species_id ' +
'AND PS.state_id = FD.state_id ' +
'AND C.container_id = FD.container_id ' +
'AND F.fld_id = "' + fld_id + '"';
connection.query(sql_fld_by_id, function(errorFld, resultFld) {
if (errorFld) {
console.log(errorFld);
}
if (resultFld.length !== 0) {
currentFld = resultFld;
connection.query(sql_fld_detail_list, function(errorFldDetails, resultFldDetails) {
if (errorFldDetails) {
console.log(errorFldDetails);
} else {
fldDetails = resultFldDetails;
io.sockets.emit('fldViewLoaded', currentFld, fldDetails);
}
});
} else {
console.log('Fld Length Error')
}
});
});
// Save company info
socket.on('saveCompanyInfo', function(payload) {
var companyName = payload.companyName;
var registrationNo = payload.registrationNo;
var landlineNo = payload.landlineNo;
var mobileNo = payload.mobileNo;
var emailAddress = payload.emailAddress;
var companyLogo = payload.companyLogo;
var jsonFile = payload.jsonFile;
var sql_save_company_info =
`INSERT INTO lfr (lfr_name, registration_number, landline_number, mobile_number, email_address, lfr_logo, json_file)
VALUES ('${companyName}', '${registrationNo}', '${landlineNo}', '${mobileNo}', '${emailAddress}', '${companyLogo}', '${jsonFile}')`;
connection.query(sql_save_company_info, function(errorLfrInfo, resultLfrInfo) {
if (errorLfrInfo) {
lfrSaved = false;
console.log(errorLfrInfo);
}
if (resultLfrInfo) {
lfrSaved = true;
} else {
lfrSaved = false;
}
io.sockets.emit('companyInfoSaved', lfrSaved);
});
});
// Load user list for lfr
socket.on('userListLoad', function(payload) {
var lfrId = payload.lfrId;
var load_user_list =
`SELECT USI.user_id, USI.user_name, UT.user_type, USI.email_address, USI.passcord, US.status_type
FROM user_site_info USI, user_types UT, user_status US
WHERE USI.user_type_id = UT.user_type_id
AND USI.user_status_id = US.user_status_id
AND lfr_id = ${lfrId}`;
connection.query(load_user_list, function(errorUserList, resultUserList) {
if (errorUserList) {
console.log(errorUserList);
} else {
userList = resultUserList;
io.sockets.emit('userListLoaded', userList);
}
});
});
// Load organization form
socket.on('loadOrganization', function() {
io.sockets.emit('organizationLoaded');
});
// Load main form
socket.on('loadMain', function() {
io.sockets.emit('mainLoaded');
});
// Delete user
socket.on('deleteUser', function(payload) {
var lfrId = payload.lfrId;
var userId = payload.userId;
var delete_user =
`UPDATE user_site_info
SET user_status_id = '2'
WHERE user_id = ${userId}`;
var load_user_list =
`SELECT USI.user_id, USI.user_name, UT.user_type, USI.email_address, USI.passcord, US.status_type
FROM user_site_info USI, user_types UT, user_status US
WHERE USI.user_type_id = UT.user_type_id
AND USI.user_status_id = US.user_status_id
AND lfr_id = ${lfrId}`;
connection.query(delete_user, function(error, result) {
if (error) {
console.log(error);
}
if (result) {
connection.query(load_user_list, function(errorUserList, resultUserList) {
if (errorUserList) {
console.log(errorUserList);
} else {
userDeleted = true;
userList = resultUserList;
io.sockets.emit('userDeleted', userDeleted, userList);
}
});
} else {
userDeleted = false;
}
});
});
// Delete weigh in
socket.on('deleteWeighIn', function(payload) {
var weighInId = payload.weighInId;
var sql_delete_weigh_in =
`DELETE FROM weigh_in
WHERE weigh_in_id = ${weighInId}`;
var sql_delete_weigh_in_details =
`DELETE FROM weigh_in_details
WHERE weigh_in_id = ${weighInId}`;
connection.query(sql_delete_weigh_in, function(errorDeleteWightIn, resultDeleteWightIn) {
if (errorDeleteWightIn) {
console.log(errorDeleteWightIn);
}
connection.query(sql_delete_weigh_in_details, function(errorDeleteWightInDetails, resultDeleteWightInDetails) {
if (errorDeleteWightInDetails) {
console.log(errorDeleteWightInDetails);
}
if (resultDeleteWightInDetails) {
io.sockets.emit('weighInDeleted');
} else {
console.log('Weigh-In Deletion Error');
}
});
});
});
// Reset weigh-in list
socket.on('resetWeighInList', function() {
io.sockets.emit('weighInListReset');
});
// Save user site info
socket.on('saveUserSiteInfo', function(payload) {
var userName = payload.userName;
var userTypeId = payload.userType;
var emailAddress = payload.emailAddress;
var passcord = crypto.createHash('sha1').update(payload.passcord).digest("hex");
var userStatusId = 1;
var lfrId = payload.lfrId;
var sql_user_site_info =
`INSERT INTO user_site_info (user_name, user_type_id, email_address, passcord, user_status_id, lfr_id)
VALUES ('${userName}','${userTypeId}', '${emailAddress}', '${(passcord)}','${userStatusId}', '${lfrId}')`;
var load_user_list =
`SELECT USI.user_id, USI.user_name, UT.user_type, USI.email_address, USI.passcord, US.status_type
FROM user_site_info USI, user_types UT, user_status US
WHERE USI.user_type_id = UT.user_type_id
AND USI.user_status_id = US.user_status_id
AND lfr_id = ${lfrId}`;
connection.query(sql_user_site_info, function(errorUserInfo, resultUserInfo) {
if (errorUserInfo) {
userSiteInfoSaved = false;
console.log(errorUserInfo);
}
if (resultUserInfo) {
userSiteInfoSaved = true;
connection.query(load_user_list, function(errorUserList, resultUserList) {
if (errorUserList) {
console.log(errorUserList);
} else {
userList = resultUserList;
io.sockets.emit('userSiteInfoSaved', userSiteInfoSaved, userList);
}
});
} else {
console.log('User Info Saving Error')
}
});
});
// Save weigh in info
socket.on('saveWeighInRecord', function(payload) {
var fldId = payload.fldId;
var weighInId = payload.fldId;
var productId = payload.productId;
var containerId = payload.containerId;
var amount = payload.amount;
var netWeight = payload.netWeight;
var areaId = payload.areaId;
var userId = payload.userId;
// Check if the record is the first of the weigh in id,
var sql_check_weigh_in =
`SELECT * FROM weigh_in
WHERE weigh_in_id = '${weighInId}'`;
connection.query(sql_check_weigh_in, function(errorCheck, resultCheck) {
if (errorCheck) {
console.log(errorCheck);
}
// If there is no recrod related to weigh in id, create the weigh in id
if (resultCheck.length === 0) {
var sql_weigh_in_header =
`INSERT INTO weigh_in (weigh_in_id, fld_id, logged_user_id, created_time)
VALUES('${weighInId}', '${fldId}', '${userId}', NOW())`;
connection.query(sql_weigh_in_header, function(errorHeader, resultHeader) {
if (errorHeader) {
console.log(errorHeader);
}
});
}
});
var sql_weigh_in_record =
`INSERT INTO weigh_in_details (product_id, container_id, number_of_containers, net_weight, area_id, weigh_in_id)
VALUES ('${productId}', '${containerId}','${amount}','${netWeight}','${areaId}','${weighInId}')`;
var sql_load_records =
`SELECT P.product_code, C.container, WD.number_of_containers, WD.net_weight, S.species_code, PS.state_code, G.grade, A.area_code
FROM product P, container C, species S, processed_state PS, grade G, area A, weigh_in_details WD
WHERE WD.product_id = P.product_id
AND WD.container_id = C.container_id
AND WD.area_id = A.area_id
AND P.species_id = S.species_id
AND P.state_id = PS.state_id
AND P.grade_id = G.grade_id
AND weigh_in_id = '${weighInId}'
ORDER BY weigh_in_detail_id ASC`;
connection.query(sql_weigh_in_record, function(errorRecord, resultRecord) {
if (errorRecord) {
console.log(errorRecord);
}
if (resultRecord) {
connection.query(sql_load_records, function(errorList, resultList) {
if (errorList) {
console.log(errorList);
} else {
weighInList = resultList;
io.sockets.emit('weighInRecordSaved', weighInList);
}
});
} else {
console.log('Weigh In Saving Error')
}
});
});
// Load user types
socket.on('loadUserTypes', function() {
var sql_user_types =
`SELECT user_type_id, user_type FROM user_types
ORDER BY user_type ASC`;
connection.query(sql_user_types, function(error, result) {
if (error) {
console.log(error);
}
if (result.length !== 0) {
userTypes = result;
io.sockets.emit('userTypesLoaded', userTypes);
} else {
console.log('User Type Error')
}
});
});
// Load weigh-in numbers
socket.on('loadWeighInNumbers', function(payload) {
var lfrId = payload.lfrId
var sql_load_weigh_in =
`SELECT W.weigh_in_id
FROM weigh_in W, fld F
WHERE W.weigh_in_id = F.fld_id
AND F.lfr_id = ${lfrId}`;
connection.query(sql_load_weigh_in, function(error, result) {
if (error) {
console.log(error);
}
if (result.length !== 0) {
weighInNumbers = result;
io.sockets.emit('weighInNumbersLoaded', weighInNumbers);
} else {
console.log('Weigh-In Error')
}
});
});
// Load fld, weigh-in weights
socket.on('loadWeighInWeights', function(payload) {
// weigh_in table weigh_in_id and fld table fld_id are same
var weighInId = payload.weighInId;
var sql_load_fld_weights =
`SELECT S.species, S.species_code, SUM(FD.no_of_containers * C.content_weight) AS 'fld_weight'
FROM fld_details FD, species S, container C
WHERE S.species_id = FD.species_id
AND FD.container_id = C.container_id
AND FD.fld_id = '${weighInId}'
GROUP BY S.species_code, 'fld_weight'
ORDER BY S.species_code`;
var sql_load_weigh_in_weights =
`SELECT S.species, S.species_code, SUM(WD.net_weight) AS 'weigh_in_weight'
FROM weigh_in_details WD, species S, product P, container C
WHERE P.species_id = S.species_id
AND WD.product_id = P.product_id
AND WD.container_id = C.container_id
AND WD.weigh_in_id = '${weighInId}'
GROUP BY S.species_code, 'weigh_in_weight'
ORDER BY S.species_code`;
var sql_load_fld_info =
`SELECT DATE_FORMAT(F.fld_created_time, "%Y-%m-%d") AS "fld_created_date", CONCAT(U.first_name, " ", U.last_name) AS "fld_created_by", COUNT(FD.fld_id) AS "fld_records"
FROM fld F, user_personal_info U, fld_details FD
WHERE F.fld_created_user_id = U.user_id
AND F.fld_id = FD.fld_id
AND F.fld_id = '${weighInId}'`;
var sql_load_weigh_info =
`SELECT DATE_FORMAT(created_time, "%Y-%m-%d") AS "weigh_in_created_date", CONCAT(U.first_name, " ", U.last_name) AS "weigh_in_created_by", COUNT(WD.weigh_in_id) AS "weigh_in_records"
FROM weigh_in W, user_personal_info U, weigh_in_details WD
WHERE W.logged_user_id = U.user_id
AND W.weigh_in_id = WD.weigh_in_id
AND W.weigh_in_id = '${weighInId}'`;
connection.query(sql_load_fld_weights, function(errorFldWeights, resultFldWeights) {
if (errorFldWeights) {
console.log(errorFldWeights);
}
if (resultFldWeights.length !== 0) {
connection.query(sql_load_weigh_in_weights, function(errorweighInWeights, resultWeighInWeights) {
if (errorweighInWeights) {
console.log(errorweighInWeights);
}
if (resultWeighInWeights.length !== 0) {
connection.query(sql_load_fld_info, function(errorFldInfo, resultFldInfo) {
connection.query(sql_load_weigh_info, function(errorWeighInInfo, resultWeighInInfo) {
fldWeights = resultFldWeights;
weighInWeights = resultWeighInWeights;
fldHeaderInfo = resultFldInfo;
weighInHeaderInfo = resultWeighInInfo;
io.sockets.emit('weighInWeightsLoaded', fldWeights, weighInWeights, fldHeaderInfo, weighInHeaderInfo);
});
});
} else {
console.log('Weigh-In Weights Error')
}
});
}
});
});
// Load weigh in combo boxes
socket.on('loadWeighInComboBoxes', function(payload) {
var lfr_id = payload.lfr_id;
var sql_load_fld_numbers = `
SELECT fld_id, fld_number FROM fld WHERE lfr_id = '${lfr_id}'
ORDER BY fld_number DESC `;
var sql_load_product_codes = `
SELECT product_id, product_code FROM product ORDER BY product_code ASC `;
var sql_load_containers = `
SELECT container_id, container FROM container WHERE lfr_id = ${lfr_id} ORDER BY container ASC`;
var sql_load_area_codes = `
SELECT area_id, area_code FROM area ORDER BY area_code ASC `;
connection.query(sql_load_fld_numbers, function(errorFld, resultFld) {
if (errorFld) {
console.log(errorFld);
}
connection.query(sql_load_product_codes, function(errorProducts, resultProducts) {
if (errorProducts) {
console.log(errorProducts);
}
connection.query(sql_load_containers, function(errorContainer, resultContainer) {
if (errorContainer) {
console.log(errorContainer);
}
connection.query(sql_load_area_codes, function(errorArea, resultArea) {
if (errorArea) {
console.log(errorArea);
}
fldNumbers = resultFld;
productCodes = resultProducts;
containerTypes = resultContainer;
areaCodes = resultArea;
io.sockets.emit('weighInComboBoxesLoaded', fldNumbers, productCodes, containerTypes, areaCodes);
});
});
});
});
});
// Get fld info and weigh in records that are relavent to weighInId
socket.on('loadFldWeighInInfo', function(payload) {
var fldId = payload.fldId;
var weighInId = payload.fldId;
var sql_get_fld_count =
`SELECT COUNT( * ) AS 'fld_rows'
FROM fld_details WHERE fld_id = '${fldId}'`;
var sql_get_fld_info =
`SELECT DATE_FORMAT(F.fld_created_time, "%Y-%m-%d") AS "fld_created_date", DATE_FORMAT(F.fld_created_time, "%T") AS "fld_created_time", CONCAT(U.first_name, " ", U.last_name) AS "created_by"
FROM fld F, user_personal_info U
WHERE F.fld_created_user_id = U.user_id
AND F.fld_id = '${fldId}'`;
var sql_load_records =
`SELECT P.product_code, C.container, WD.number_of_containers, WD.net_weight, S.species_code, PS.state_code, G.grade, A.area_code
FROM product P, container C, species S, processed_state PS, grade G, area A, weigh_in_details WD
WHERE WD.product_id = P.product_id
AND WD.container_id = C.container_id
AND WD.area_id = A.area_id
AND P.species_id = S.species_id
AND P.state_id = PS.state_id
AND P.grade_id = G.grade_id
AND weigh_in_id = '${weighInId}'
ORDER BY weigh_in_detail_id ASC `;
connection.query(sql_get_fld_count, function(errorFldCount, resultFldCount) {
if (errorFldCount) {
console.log(errorFldCount);
}
connection.query(sql_get_fld_info, function(errorFldInfo, resultFldInfo) {
if (errorFldInfo) {
console.log(errorFldInfo);
}
connection.query(sql_load_records, function(errorList, resultList) {
if (errorList) {
console.log(errorList);
} else {
fldRows = resultFldCount;
fldInfo = resultFldInfo;
weighInList = resultList;
io.sockets.emit('fldWeighInInfoLoaded', fldRows, fldInfo, weighInList);
}
});
});
});
});
// Get product info
socket.on('loadProductInfo', function(payload) {
var productId = payload.productId;
var sql_get_product_info =
`SELECT P.product_code, S.species_code, PS.state_code, G.grade
FROM product P, species S, processed_state PS, grade G
WHERE P.species_id = S.species_id
AND P.state_id = PS.state_id
AND P.grade_id = G.grade_id
AND P.product_id = '${productId}'`;
connection.query(sql_get_product_info, function(error, result) {
if (error) {
console.log(error);
}
if (result.length !== 0) {
productInfo = result;
io.sockets.emit('productInfoLoaded', productInfo);
} else {
console.log('No Records Found')
}
});
});
// Load user types
socket.on('checkUserName', function(payload) {
var userName = payload.userName;
var sql_check_user_name =
`SELECT * from user_site_info
WHERE user_name = '${userName}'`;
connection.query(sql_check_user_name, function(error, result) {
if (error) {
console.log(error);
}
if (result.length !== 0) {
validUserName = false;
} else {
validUserName = true;
}
io.sockets.emit('userNameChecked', validUserName);
});
});
// socket.emit => emit events that are handled by the client
socket.emit('welcome', {
title: title,
flds: flds,
currentFld: currentFld,
fldDetails: fldDetails,
lfrSaved: lfrSaved,
userSiteInfoSaved: userSiteInfoSaved,
userList: userList,
userTypes: userTypes,
fldNumbers: fldNumbers,
productCodes: productCodes,
containerTypes: containerTypes,
areaCodes: areaCodes,
fldRows: fldRows,
fldInfo: fldInfo,
productInfo: productInfo,
weighInList: weighInList,
weighInNumbers: weighInNumbers,
weighInWeights: weighInWeights,
fldHeaderInfo: fldHeaderInfo,
weighInHeaderInfo: weighInHeaderInfo,
fldWeights: fldWeights,
userDeleted: userDeleted
});
connections.push(socket);
});
console.log(`Fishery Logistics is running at port ${ server.address().port }`);
You should definitely break this into several modules. Rule of thumb is to have controller modules and models.
Can anyone help me with the following code which is trying to enter a Shipment with a mix of Serial and Non-Serial items. The error I am receiving says "PX.Data.PXException: Error #246: Failed to commit splits row." which would have something to do with the Serial allocation but I can't point out where the issue is coming from.
SO302000Content SO302000 = oScreen.SO302000GetSchema();
oScreen.SO302000Clear();
SO302000.Actions.AddSO.Commit = true;
SO302000.AddSalesOrder.Selected.LinkedCommand = null;
SO302000.DocumentDetails.InventoryID.LinkedCommand = null;
List<Command> oCmds = new List<Command>();
//Create Header.
oCmds.Add(SO302000.Actions.Insert);
oCmds.Add(new Value { Value = sCardCode, LinkedCommand = SO302000.ShipmentSummary.Customer, Commit = true });
oCmds.Add(new Value { Value = sCardLocation, LinkedCommand = SO302000.ShipmentSummary.Location });
oCmds.Add(new Value { Value = sWhsCode, LinkedCommand = SO302000.ShipmentSummary.WarehouseID });
oCmds.Add(SO302000.Actions.Save);
//Create Lines.
foreach (DataRow dR in ds.Tables[0].Rows)
{
dPackQty = Convert.ToDouble(dR["QtyPacked"]);
if (sSONbr == dR["SONbr"].ToString() && sItemCode == dR["ItemCode"].ToString())
{
dCount = dCount + 1;
}
else
{
sSONbr = dR["SONbr"].ToString();
sItemCode = dR["ItemCode"].ToString().Trim();
dCount = 0;
//oCmds.Add(new Value { Value = "OK", LinkedCommand = SO302000.AddSalesOrderOperation.ServiceCommands.DialogAnswer, Commit = true });
oCmds.Add(new Value { Value = "SO", LinkedCommand = SO302000.AddSalesOrderOperation.OrderType });
oCmds.Add(new Value { Value = sSONbr, LinkedCommand = SO302000.AddSalesOrderOperation.OrderNbr });
oCmds.Add(new Value { Value = "OK", LinkedCommand = SO302000.AddSalesOrder.ServiceCommands.DialogAnswer, Commit = true });
oCmds.Add(new Key { Value = sItemCode, FieldName = SO302000.AddSalesOrder.InventoryID.FieldName, ObjectName = SO302000.AddSalesOrder.InventoryID.ObjectName });
oCmds.Add(new Value { Value = "True", LinkedCommand = SO302000.AddSalesOrder.Selected, Commit = true });
oCmds.Add(SO302000.Actions.AddSO);
oCmds.Add(new Key { Value = "='" + sSONbr + "'", FieldName = SO302000.DocumentDetails.OrderNbr.FieldName, ObjectName = SO302000.DocumentDetails.OrderNbr.ObjectName });
oCmds.Add(new Key { Value = "='" + sItemCode + "'", FieldName = SO302000.DocumentDetails.InventoryID.FieldName, ObjectName = SO302000.DocumentDetails.InventoryID.ObjectName });
oCmds.Add(new Value { Value = "0", LinkedCommand = SO302000.DocumentDetails.ShippedQty, Commit = true });
}
if (dR["IsSerial"].ToString() == "Y")
{
oCmds.Add(new Value { Value = "OK", LinkedCommand = SO302000.Allocations.ServiceCommands.DialogAnswer, Commit = true });
oCmds.Add(new Value { Value = dCount.ToString(), LinkedCommand = SO302000.Allocations.ServiceCommands.RowNumber, Commit = true });
oCmds.Add(new Value { Value = dR["Serial"].ToString(), LinkedCommand = SO302000.Allocations.LotSerialNbr, Commit = true });
oCmds.Add(new Value { Value = dPackQty.ToString(), LinkedCommand = SO302000.Allocations.Quantity, Commit = true });
}
else
{
oCmds.Add(new Value { Value = "OK", LinkedCommand = SO302000.Allocations.ServiceCommands.DialogAnswer, Commit = true });
oCmds.Add(new Value { Value = dPackQty.ToString(), LinkedCommand = SO302000.Allocations.Quantity, Commit = true });
}
}
oCmds.Add(SO302000.Actions.Save);
//oCmds.Add(PO302000.DocumentSummary.TotalQty);
//oCmds.Add(PO302000.DocumentSummary.TotalAmt);
oScreen.SO302000Submit(oCmds.ToArray());
While trying to change the code that handles Non Serial item to use SO302000.DocumentDetails.ShippedQty instead of SO302000.Allocations.Quantity, it returns another error:
"PX.Data.PXRowPersistingException: Error #4: 'LineType' may not be empty."
Not sure what this one means.
Help is greatly appreciated :)
G
Please take a look
Content SO302000 = context.GetSchema();
context.Clear();
Content[] result = context.Submit(
new Command[]
{
new Value { Value = "001043", LinkedCommand = SO302000.ShipmentSummary.ShipmentNbr, Commit = true },
new Value { Value = "000819", LinkedCommand = SO302000.DocumentDetails.OrderNbr, Commit = true},
new Value { Value = "OK", LinkedCommand = SO302000.BinLotSerialNumbers.ServiceCommands.DialogAnswer, Commit = true },
SO302000.BinLotSerialNumbers.ServiceCommands.NewRow,
new Value { Value = "0-_", LinkedCommand = SO302000.BinLotSerialNumbers.Subitem },
new Value { Value = "WR01", LinkedCommand = SO302000.BinLotSerialNumbers.Location },
new Value { Value = "17SNR000751", LinkedCommand = SO302000.BinLotSerialNumbers.LotSerialNbr },
SO302000.Actions.LSSOShipLineBinLotSerial,
SO302000.Actions.Save
}
);
Console.WriteLine();