I have two buttons in my expense manager: 'Add Income' and 'Add Expense' which allow the user to add their income and expenses but they don't work and I'm not sure why. I have onclick listeners for both of the 'add expense' and 'add income buttons. What do I need to change in my JS code to solve this?
const uuidv4 = require('uuid/v4')
// Read existing expenses from localStorage
const getSavedExpenses = () => {
const expensesJSON = localStorage.getItem('expenses')
try {
return expensesJSON ? JSON.parse(expensesJSON) : []
} catch (e) {
return []
}
}
const expenses = getSavedExpenses()
// Save expenses to localStorage
const saveExpenses = (expenses) => {
localStorage.setItem('expenses', JSON.stringify(expenses))
}
const displayExpenses = (title, expensesJSON) => {
let html = `<div class="text-expense">`
for (let i = 0; i < expensesJSON.length; i++) {
html += `<textarea type="text" id="description" name="description"></textarea>`
}
html += `</div>`
title.innerHTML = html;
}
// Create account
const account = {
name: 'aaa',
expenses: [],
income: [],
addExpense: function (description, amount) {
this.expenses.push({
description: description,
amount: amount
})
},
addIncome: function (description, amount) {
this.income.push({
description: description,
amount: amount
})
},
getAccountSummary: function () {
let totalExpenses = 0
let totalIncome = 0
let accountBalance = 0
this.expenses.forEach(function (expense) {
totalExpenses = totalExpenses + expense.amount
})
this.income.forEach(function (income) {
totalIncome = totalIncome + income.amount
})
accountBalance = totalIncome - totalExpenses
}
}
account.addExpense('Rent', 850)
account.addExpense('Food Shopping', 60)
console.log(account.getAccountSummary())
// Listen for new expense to be created
$('#add-expense').on('click', function() {
location.href = '/expense.html'
})
// Listen for expense to be submitted
$('#submit-expense').on('click', function() {
saveExpenses(expenses)
location.href = '/index.html'
})
$('#income').on('click', function() {
location.href = '/income.html'
})
$('#submit-income').on('click', function() {
location.href = '/index.html'
})
$('#add-expense').on('click', function () {
const id = uuidv4()
expenses.push({
id: id,
title: '',
body: ''
})
saveExpenses(expenses)
location.href = `/expense.html#${id}`
displayExpenses(targetElem, getSavedExpenses())
})
Make sure your onclick event handlers are wrapped inside a onload handler (or jQuery's $(document).ready), so that you are sure your buttons are loaded before $(some_selector) is called, something like:
onload = function() {
// Listen for new expense to be created
$('#add-expense').on('click', function() {
location.href = '/expense.html'
})
// Listen for expense to be submitted
$('#submit-expense').on('click', function() {
saveExpenses(expenses)
location.href = '/index.html'
})
$('#income').on('click', function() {
location.href = '/income.html'
})
$('#submit-income').on('click', function() {
location.href = '/index.html'
})
$('#add-expense').on('click', function () {
const id = uuidv4()
expenses.push({
id: id,
title: '',
body: ''
})
saveExpenses(expenses)
location.href = `/expense.html#${id}`
displayExpenses(targetElem, getSavedExpenses())
})
}
I am trying to create pdf file from each object in an array.
[
{
name: jack,
age: 20,
},
{
name: daniel,
age: 22,
}
];
first I try to catch each object.
var proceed = 0;
arrayObj.forEach((tasks, index) => {
if (index === proceed) {
tasks.forEach(task => {
$(this).tableRow(task)
})
$(this).singlePdf()
}
proceed++
})
dynamic table
$.fn.tableRow = function(task){
var row = "<tr><td"+task.name+"</td><td>"+task.age+"</td></tr>";
$("tbody").append(row);
};
pdf
$.fn.singlePdf = function(){
html2canvas(document.getElementById('a4'), {
onrendered: function (canvas) {
var data = canvas.toDataURL();
var docDefinition = {
content: [{
image: data,
width: 500
}]
};
pdfMake.createPdf(docDefinition).download("table.pdf");
}
});
}
the problem here. when I run it, I am creating multiple pdf file, but it's putting all objects to each pdf...
this part of code not running as I expected.
if (index === proceed) {
tasks.forEach(task => {
$(this).tableRow(task)
})
$(this).singlePdf()
}
proceed++
How can I fix this problem?
I m new in suitescripts. I have made a Suitelet Form script with 3 fields which will act as filters on the scheduled script. The scheduled script in sending the PDF file to a certain email after filtering the 3 values of suit let script from my saved search.
When I hit the button on suitelet form, after entering the fields, the scheduled script goes on processing for 1 hour and then gets failed.
I think I have placed the wrong filters in the loading of My saved search in my scheduled script.
The saved search (customsearch_mx_itemsearch) is without any filters or criteria.
Please help if anyone knows. Thank you
My Suitelet form Script:
define(['N/ui/serverWidget', 'N/search', 'N/render', 'N/runtime', 'N/file', 'N/task'],
function (ui, search, render, runtime, file, task) {
/**
* main function for suitelet
* #param {object} ctx
*/
function onRequest(ctx) {
var req = ctx.request;
var res = ctx.response;
var param = req.parameters;
/**
* create form is creating the UI for report generation
*/
if (req.method === 'GET') {
// createForm(req, res, param);
createForm(req, res, param);
} else {
generateReport(req, res, param);
}
}
// R E Q U E S T
function createForm(req, res, param) {
if (req.method === 'GET') {
var form = ui.createForm({
title: 'Generate Item Report'
});
var item = form.addField({
id: 'custpage_selectitem',
type: ui.FieldType.SELECT,
label: 'Select Item',
source: 'item'
});
item.isMandatory = true;
var gender = form.addField({
id: 'custpage_selectgender',
type: ui.FieldType.SELECT,
label: 'Select Gender',
source: 'customrecord6'
});
gender.isMandatory = true;
var fromDate = form.addField({
id: 'custpage_selectdate',
// type: ui.FieldType.DATETIME,
type: ui.FieldType.DATE,
label: 'Select Date/Time',
});
form.addSubmitButton({
label: 'Generate Report'
});
res.writePage(form);
}
}
// R E S P O N C E
function generateReport(req, res, param) {
var param = req.parameters;
log.debug('parameters', param);
var script = runtime.getCurrentScript();
var filters = {
'isgender': param.custpage_selectgender,
'isItem': param.custpage_selectitem,
'fromDate': param.custpage_selectdate
};
log.debug('filters', filters);
var scriptTask = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT });
// scriptTask.scriptId = 3920;
scriptTask.scriptId = 'customscript_mx_itemreport_ss';
scriptTask.deploymentId = 'customdeploy_mx_itemreport_ss';
scriptTask.params = {
custscript_searchfilter_report: JSON.stringify(filters)
};
log.debug('workingtillhere');
var scriptTaskId = scriptTask.submit();
res.write("Your report is being generated. It will be emailed to you shortly.")
}
return {
onRequest: onRequest
};
});
My Scheduled script:
define(['N/ui/serverWidget', 'N/search', 'N/render', 'N/runtime', 'N/file', 'N/email'],
function (ui, search, render, runtime, file, email) {
function execute() {
try {
generateReport();
}
catch (e) {
log.error('generateReport ERROR', e);
}
}
function generateReport(req, res, param) {
var slfilters = runtime.getCurrentScript().getParameter({ name: 'custscript_searchfilter_report' });
log.debug('slfilters', slfilters);
if (!!slfilters) {
slfilters = JSON.parse(slfilters);
}
log.debug('slfilters2', slfilters);
var getUser = runtime.getCurrentUser();
var gender = slfilters.isgender
log.debug('gender', gender)
var item = slfilters.isItem
log.debug('item', item)
var item = getItems(item, gender);
log.debug('items table', item)
var xmlTemplateFile = file.load(3918);
var template = script.getParameter({ name: 'custscript_template' });
var renderer = render.create();
renderer.templateContent = xmlTemplateFile.getContents();
var customSources = {
alias: 'searchdata',
format: render.DataSource.JSON,
data: JSON.stringify({
value: item,
})
};
renderer.addCustomDataSource(customSources);
var xml = renderer.renderAsString();
var pdf = render.xmlToPdf({
"xmlString": xml
});
email.send({
author: 317,
recipients: 'aniswtf#gmail.com',
subject: 'Item Report',
body: 'Report Generated: ',
attachments: [pdf]
});
}
//
// ─── GET RESULTS ───────────────────────────────────────────────────
//
const getResults = function (set) {
var results = [];
var i = 0;
while (true) {
var result = set.getRange({
"start": i,
"end": i + 1000
});
if (!result) break;
results = results.concat(result);
if (result.length < 1000) break;
i += 1000;
}
return results;
};
//
// ─── GET ITEMS ───────────────────────────────────────────────────
//
function getItems(item, gender) {
try {
var itemSearch = search.load({
id: 'customsearch_mx_itemsearch'
});
var defaultFilters = itemSearch.filters;
var arrFilters = [];
arrFilters.push(search.createFilter({
name: 'custitem5',//gender
operator: 'anyof',
values: [gender]
}));
arrFilters.push(search.createFilter({
name: 'internalid',
operator: 'anyof',
values: [item]
}));
//defaultFilters.push(arrFilters)
defaultFilters = defaultFilters.concat(arrFilters);
var results = getResults(itemSearch.run()).map(function (x) {
return {
'category': x.getText({
name: "custitem10",
join: "parent"
}),
'season': x.getValue({
name: "custitem11",
join: "parent"
}),
'riselabel': x.getValue({
name: "custitem_itemriselabel",
join: "parent"
}),
'fit': x.getValue({
name: "custitem9",
join: "parent"
}),
'name': x.getValue({ //sku
name: "itemid",
join: "parent"
}),
'style': x.getValue({
name: "custitem8",
join: "parent"
}),
'inseam': x.getValue({
name: "custitem7",
join: "parent"
}),
'wash': x.getValue({
name: "custitem_washname",
join: "parent"
}),
};
});
return results;
} catch (e) {
log.error('error in getItems', e)
}
}
return {
execute: execute
};
});
You have the req, res, and param arguments defined for generateReport(), but you aren't actually populating them when you call generateReport() within execute(). You will need to pass values for those parameters.
I'm having the activiti Bpmn file, in that there is having transition of task. While transition I need to create the due date for that new task. my problem is due date and new task happening on same time. because of that I'm getting error.
onClose: function (date) {
if (valid) {
date = Date.parse(date);
if (oldDate !== date) {
var tasks = getSet(context, 'task') || getSet(context, 'tasks'),
trans = Ember.get(context, 'transition') || Ember.get(context, 'propertyMap.transition'),
requestData = [];
if (!tasks.length) {
resolve();
return;
}
if (!trans) {
trans = 'Done';
}
tasks.forEach(function (task) {
requestData.push({ name: 'id', value: (Ember.get(task, 'id') || Ember.get(task, 'currentTask.id') )});
requestData.push({ name: 'transition', value: trans || '' });
});
if (context.get('serviceParams')) {
Object.asAjaxData(context.get('serviceParams')).forEach(function (param) {
requestData.push(param);
});
}
return (Core.services({
type: 'post',
service: 'workflow/task/transition',
data: requestData,
json: true
})
.done(function (res) {
Core.Action('Core:updateTask', context, { dtDue: date });
Core.model.ingestResources(res);
var inspected = Core.controller.detailsObject,
wf = res.workflows || {};
if (inspected) {
Object.keys(wf).forEach(function (w) {
var hist = wf[w].historicalTaskIds;
if (hist.contains(inspected.currentTaskId)) {
inspected.set('currentTaskId', wf[w].openTaskIds[0]);
}
});
}
resolve();
})
.fail(function (xhr, status, error) {
Core.Error.show(error);
})
.always(function () {
tasks.forEach(function (task) {
if (Ember.get(task, 'isClip')) {
Core.model.clip.clear();
}
});
var wfController = Core.Tab.Workflow.getController();
var sel = wfController.get('selection');
wfController.reloadResultSet();
var rs = wfController.get('resultSet');
rs && rs.done(function () {
var s = Ember.Set.create();
rs.get('content').forEach(function (item) {
if (!item) { return; }
s.addObject(item);
});
sel.forEach(function (item) {
if (!s.contains(item)) {
sel.remove(item);
}
});
});
sel.clear();
resolve(tasks);
})
);
}
}
}
In that Core.Action('Core:updateTask', context, { dtDue: date }); is using for updating the duedate. If I use on the top If statement Due Date is updated, but Transistion is not happening. If I'm using on the done function, the transistion is happened and moved to the new Task Id. Because of that it searching Task Id and showing error.
Please provide me suggestion on this. I need to create both the Transistion and meanwhile update the date.
I have 2 javascript files.
1 of those files functions looks like this.
var database = new localStorageDB("FormsDatabase", localStorage);
this.Create = function (item) {
database.insertOrUpdate("Value", { Id: item.Id }, item);
database.commit();
};
The other looks like this.
var database = new localStorageDB("FormsDatabase", localStorage);
this.SynchronizeValue = function () {
var items = database.queryAll("Value", { query: function (row) {
if (row.IsSent == false && row.IsDeleted == false)
{ return true; } else { return false; } }, limit: 100 });
};
Why is it that the first file i can do a query right after doing an insertOrUpdate and a commit and i can get a return but in the second file the "Value" tables contents have dissapeared?